text:
//#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#include "../include/entity.h"
#include "../include/buttonui.h"
#include "../include/clickgesture.h"
#include "../include/checkboxui.h"
#include "../include/checkboxgroup.h"
#include "../include/controlmanagerui.h"
#include "../include/event.h"
#include "../include/inputmanager.h"
#include "../include/mousecontroller.h"
#include "../include/keyboardcontroller.h"
#include "../include/sliderui.h"
#include "../include/windowui.h"

#include "../include/u-gine.h"

#include <assert.h>

int main() {
	Screen::Instance().Open(800, 600, false);

	//Entity
	Image * alienImg = ResourceManager::Instance().LoadImage("data/alien.png");
	alienImg->SetMidHandle();
	CEntity entity(alienImg);
	entity.GetSprite()->SetPosition(350, 340);

	CEntity entity2(alienImg);
	entity2.GetSprite()->SetPosition(700, 300);

	//Windows
	Image * backgroundImg = ResourceManager::Instance().LoadImage("data/background.jpg");
	Image * windowImg = ResourceManager::Instance().LoadImage("data/window4.png");

	//button Imgs
	Image * buttonImgDefault = ResourceManager::Instance().LoadImage("data/button_default.png");
	buttonImgDefault->SetMidHandle();
	Image * buttonImgOnClick = ResourceManager::Instance().LoadImage("data/button_onclick.png");
	buttonImgOnClick->SetMidHandle();
	Image * buttonImgInactive = ResourceManager::Instance().LoadImage("data/button_inactive.png");
	buttonImgInactive->SetMidHandle();

	//checkbox Imgs
	Image * checkboxImgDefault = ResourceManager::Instance().LoadImage(
	"data/checkbox_disabled.png");
	checkboxImgDefault->SetMidHandle();
	Image * checkboxImgOnClick = ResourceManager::Instance().LoadImage(
	"data/checkbox_enabled.png");
	checkboxImgOnClick->SetMidHandle();

	//slider Imgs
	Image * sliderBallImg = ResourceManager::Instance().LoadImage("data/slider_ball.png");
	sliderBallImg->SetHandle(
		static_cast<float>(sliderBallImg->GetWidth() * sliderBallImg->GetHFrames() / 2),
		static_cast<float>(sliderBallImg->GetHeight() * sliderBallImg->GetVFrames()));

	Image * sliderBarImg = ResourceManager::Instance().LoadImage("data/slider_bar.png");
	sliderBarImg->SetHandle(0,
		static_cast<float>(sliderBarImg->GetHeight() * sliderBarImg->GetVFrames()));

	Image * sliderLeftDefaultImg = ResourceManager::Instance().LoadImage(
		"data/slider_left_default.png");
	sliderLeftDefaultImg->SetMidHandle();

	Image * sliderRightDefaultImg = ResourceManager::Instance().LoadImage(
		"data/slider_right_default.png");
	sliderRightDefaultImg->SetMidHandle();

	Image * sliderLeftOnClickImg = ResourceManager::Instance().LoadImage(
		"data/slider_left_onclick.png");
	sliderLeftOnClickImg->SetMidHandle();

	Image * sliderRightOnClickImg = ResourceManager::Instance().LoadImage(
		"data/slider_right_onclick.png");
	sliderRightOnClickImg->SetMidHandle();

	//Input & Control managers
	CInputManager * inputManager = &CInputManager::Instance();

	assert(inputManager != nullptr);

	CControlManagerUI controlManager;

	controlManager.Init();

	String str;
	//Controls
	CWindowUI background;
	background.Init(0, 0, backgroundImg);
	background.SetId(0);
	controlManager.AddControl(&background);

	CWindowUI windowSlider;
	windowSlider.Init(100, 0, windowImg);
	windowSlider.SetId(1);
	controlManager.AddControl(&windowSlider);

	CButtonUI button;
	button.Init(350, 80, buttonImgDefault, buttonImgOnClick, buttonImgInactive);
	button.SetId(0);
	str = "Inactive";
	button.SetText(str);
	controlManager.AddControl(&button);
	button.SetCurrentState(EGUICS_INACTIVE);

	CButtonUI button2;
	button2.Init(350, 140, buttonImgDefault, buttonImgOnClick, buttonImgInactive);
	button2.SetId(1);
	str = "Click";
	button2.SetText(str);
	controlManager.AddControl(&button2);

	CSliderUI slider;
	slider.Init(200, 400, 0, 10, sliderBarImg, sliderBallImg, sliderLeftDefaultImg,
		sliderLeftOnClickImg, sliderRightDefaultImg, sliderRightOnClickImg);
	slider.SetId(0);
	controlManager.AddControl(&slider);

	CCheckBoxUI checkbox;
	checkbox.Init(300, 220, checkboxImgDefault, checkboxImgOnClick);
	checkbox.SetId(0);

	CCheckBoxUI checkbox2;
	checkbox2.Init(340, 220, checkboxImgDefault, checkboxImgOnClick);
	checkbox2.SetId(1);

	CCheckBoxUI checkbox3;
	checkbox3.Init(380, 220, checkboxImgDefault, checkboxImgOnClick);
	checkbox3.SetId(2);

	CCheckBoxGroup cbGroup;
	cbGroup.Init();
	cbGroup.AddControl(&checkbox);
	cbGroup.AddControl(&checkbox2);
	cbGroup.AddControl(&checkbox3);
	controlManager.AddControl(&cbGroup);
	cbGroup.AddEventListener(&entity);

	checkbox.SetCurrentState(EGUICS_ONCLICK);

	button2.AddEventListener(&entity);
	slider.AddEventListener(&entity);
	entity.GetSprite()->SetColor(entity.GetSprite()->GetRed(), entity.GetSprite()->GetGreen(),
		entity.GetSprite()->GetBlue(), 0);
	/*entity.Register(EEC_MOUSE, EME_LMB_PRESS);
	entity.Register(EEC_MOUSE, EME_LMB_RELEASE);
	entity.Register(EEC_MOUSE, EME_LMB_CLICK);
	entity.Register(EEC_MOUSE, EME_RMB_PRESS);
	entity.Register(EEC_KEYBOARD, EKE_SPACE);*/
	entity2.Register(EEC_MOUSE, EME_LMB_DRAG);

	Renderer::Instance().SetBlendMode(Renderer::BlendMode::ALPHA);

	while (Screen::Instance().IsOpened() && !Screen::Instance().KeyPressed(GLFW_KEY_ESC)) {
		Renderer::Instance().Clear();

		inputManager->Update();

		controlManager.Update();
		controlManager.Render();

		entity.GetSprite()->Update(Screen::Instance().ElapsedTime());
		entity.GetSprite()->Render();

		entity2.GetSprite()->Update(Screen::Instance().ElapsedTime());
		entity2.GetSprite()->Render();

		Screen::Instance().Refresh();
	}

	ResourceManager::Instance().FreeResources();
}


text:
module Bomberman
  class Error < StandardError; end

  class BadRequest < Error; end

  class Unauthorized < Error; end

  class RateLimitExceeded < Error; end

  class Forbidden < Error; end

  class NotFound < Error; end

  class NotAcceptable < Error; end

  class UnprocessableEntity < Error; end

  class InternalServerError < Error; end

  class NotImplemented < Error; end

  class BadGateway < Error; end

  class ServiceUnavailable < Error; end

  class LanguageNotSupported < Error; end
end

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

using NUnit.Framework;

using RememBeer.Business.Logic.Admin.Breweries;
using RememBeer.Models.Contracts;

namespace RememBeer.Tests.Business.Logic.Admin.Breweries.ViewModel
{
    [TestFixture]
    public class Setters_Should
    {
        [Test]
        public void SetUpPropertiesCorrectly()
        {
            var expected = new List<IBrewery>();

            var viewModel = new BreweriesViewModel();
            viewModel.Breweries = expected;

            Assert.AreSame(expected, viewModel.Breweries);
        }
    }
}


text:
package com.badlogic.gdx.backends.iosrobovm;

import org.robovm.cocoatouch.glkit.GLKViewDrawableColorFormat;
import org.robovm.cocoatouch.glkit.GLKViewDrawableDepthFormat;
import org.robovm.cocoatouch.glkit.GLKViewDrawableMultisample;
import org.robovm.cocoatouch.glkit.GLKViewDrawableStencilFormat;

public class IOSApplicationConfiguration {
	// FIXME add compass, framebuffer bit depth, stencil, just like on Android if possible
	/** whether to enable screen dimming. */
	public boolean preventScreenDimming = true;
	/** whether or not portrait orientation is supported. */
	public boolean orientationPortrait = true;
	/** whether or not landscape orientation is supported. */
	public boolean orientationLandscape = true;

	/** the color format, RGB565 is the default **/
	public GLKViewDrawableColorFormat colorFormat = GLKViewDrawableColorFormat.RGB565;

	/** the depth buffer format, Format16 is default **/
	public GLKViewDrawableDepthFormat depthFormat = GLKViewDrawableDepthFormat.Format16;

	/** the stencil buffer format, None is default **/
	public GLKViewDrawableStencilFormat stencilFormat = GLKViewDrawableStencilFormat.None;

	/** the multisample format, None is default **/
	public GLKViewDrawableMultisample multisample = GLKViewDrawableMultisample.None;

	/** number of frames per second, 60 is default **/
	public int preferredFramesPerSecond = 60;

	/**
	 * Scale factor to use on large screens  with retina display, i.e. iPad 3+ (has no effect on non-retina screens).
	 *

	 *
1.0 = no scaling (everything is in pixels)
	 *
0.5 = LibGDX will behave as you would only have half the pixels. I.e. instead of 2048x1536 you
	 *       will work in 1024x768. This looks pixel perfect and will save you the trouble to create bigger
	 *       graphics for the retina display.
	 *
any other value: scales the screens according to your scale factor. A scale factor
	 *       oof 0.75, 0.8, 1.2, 1.5 etc. works very well without any artifacts!
	 *

    */
	public float displayScaleLargeScreenIfRetina = 1.0f;
	/**
	 * Scale factor to use on small screens with retina display, i.e. iPhone 4+, iPod 4+ (has no effect on non-retina screens).
	 *

	 *
1.0 = no scaling (everything is in pixels)
	 *
0.5 = LibGDX will behave as you would only have half the pixels. I.e. instead of 960x640 you
	 *       will work in 480x320. This looks pixel perfect and will save you the trouble to create bigger
	 *       graphics for the retina display.
	 *
any other value: scales the screens according to your scale factor. A scale factor
	 *       of 0.75, 0.8, 1.2, 1.5 etc. works very well without any artifacts!
	 *

    */
	public float displayScaleSmallScreenIfRetina = 1.0f;
	/**
	 * Scale factor to use on large screens  without retina display, i.e. iPad 1+2 (has no effect on retina screens).
	 *

	 *
1.0 = no scaling (everything is in pixels)
	 *
any other value: scales the screens according to your scale factor. A scale factor
	 *       of 0.75, 0.8, 1.2, 1.5 etc. works very well without any artifacts!
	 *

    */
	public float displayScaleLargeScreenIfNonRetina = 1.0f;
	/**
	 * Scale factor to use on small screens without retina display, i.e. iPhone 1-3, iPod 1-3 (has no effect on retina screens).
	 *

	 *
1.0 = no scaling (everything is in pixels)
	 *
any other value: scales the screens according to your scale factor. A scale factor
	 *       of 0.75, 0.8, 1.2, 1.5 etc. works very well without any artifacts!
	 *

    */
	public float displayScaleSmallScreenIfNonRetina = 1.0f;

	/** whether to use the accelerometer, default true **/
	public boolean useAccelerometer = true;
	/** the update interval to poll the accelerometer with, in seconds **/
	public float accelerometerUpdate = 0.05f;

	/** whether to use the compass, default true **/
	public boolean useCompass = true;
}


text:
export interface NumericSet {
  add: (value: number) => void;
  contains: (value: number) => boolean;
}

type LookupObject = {
  [key: number]: boolean;
};

export let NumericSet = {
  create: createSet
};

function createSet(): NumericSet {
  let lookup: LookupObject = Object.create(null);

  return {
    add(value: number) {
      lookup[value] = true;
    },

    contains(value: number) {
      return value in lookup;
    }
  };
}


text:
import types

def pathAdder(pathVarName, separator, env, value):
    """

    Comment when works.

    """
    if pathVarName in env:
        env[pathVarName] += separator + value
    else:
        env[pathVarName] = value

class PlatformSettings(object):
    """

    A bag of values that contains settings used with individual platforms, such
    as, for example, the object file suffix on this platform or preprocessor
    symbols to define when compiling for this platform (apart from the usual
    CHILLYBUILD_OS_<os name>).  See individual properties documentation for more.

    This implementation provides default values for some properties which are
    potentially useful on a wide variety of platforms.  See also
    getPlatformSettings below.

    """

    def __init__(self):
        self._objectFileSuffix = ".o"
        self._preprocessorSymbols = {"__STDC_FORMAT_MACROS" : None}
        self._staticLibName = \
                lambda projectName: "lib%s.a" % projectName
        self._sharedLibName = lambda project, major, minor: "lib%s.so.%d.%d" % \
                                                            (project,
                                                             major,
                                                             minor)
        self._soName = lambda project, major, minor: "lib%s.so.%d" % \
                                                     (project,
                                                      major)
        self._soLinkerName = lambda project, major, minor: "lib%s.so" % project
        self._executableName = lambda project: project
        self._staticLinker = \
                lambda out, filelist, optimize, disableThreading: ["ar", "-c", "-r", out] + filelist
        self._sharedLibLoaderPathAdder = \
                lambda env, path: pathAdder("LD_LIBRARY_PATH", ":", env, path)

    def _getObjectFileSuffix(self):
        assert isinstance(self._objectFileSuffix, str)
        return self._objectFileSuffix

    def _setObjectFileSuffix(self, value):
        assert isinstance(value, str)
        self._objectFileSuffix = value

    def _getPreprocessorSymbols(self):
        assert isinstance(self._preprocessorSymbols, dict)
        return self._preprocessorSymbols

    def _setPreprocessorSymbols(self, value):
        assert isinstance(value, dict)
        self._preprocessorSymbols = value

    def _getStaticLibName(self):
        assert isinstance(self._staticLibName, types.FunctionType)
        return self._staticLibName

    def _setStaticLibName(self, value):
        assert isinstance(value, types.FunctionType)
        self._staticLibName = value

    def _getSharedLibName(self):
        assert isinstance(self._sharedLibName, types.FunctionType)
        return self._sharedLibName

    def _setSharedLibName(self, value):
        assert isinstance(value, types.FunctionType)
        self._sharedLibName = value

    def _getSoName(self):
        assert isinstance(self._soName, types.FunctionType)
        return self._soName

    def _setSoName(self, value):
        assert isinstance(value, types.FunctionType)
        self._soName = value

    def _getSoLinkerName(self):
        assert isinstance(self._soLinkerName, types.FunctionType)
        return self._soLinkerName

    def _setSoLinkerName(self, value):
        assert isinstance(value, types.FunctionType)
        self._soLinkerName = value

    def _getExecutableName(self):
        assert isinstance(self._staticLinker, types.FunctionType)
        return self._executableName

    def _setExecutableName(self, value):
        assert isinstance(value, types.FunctionType)
        self._executableName = value

    def _getStaticLinker(self):
        assert isinstance(self._staticLinker, types.FunctionType)
        return self._staticLinker

    def _setStaticLinker(self, value):
        assert isinstance(value, types.FunctionType)
        self._staticLinker = value

    def _getSharedLibLoaderPathAdder(self):
        assert isinstance(self._sharedLibLoaderPathAdder, types.FunctionType)
        return self._sharedLibLoaderPathAdder

    def _setSharedLibLoaderPathAdder(self, value):
        assert isinstance(value, types.FunctionType)
        self._sharedLibLoaderPathAdder = value

    objectFileSuffix = property(fget = _getObjectFileSuffix,
                                fset = _setObjectFileSuffix,
                                doc = """
         The suffix that needs to be added to the object file name on
         this platform.  This is really a part of the interface between the
         platform and the linker, and often is just a convention that can be
         ignored.  That said, some platforms/linkers do require that the object
         files they produce/consume end in a certain suffix.  An example of this
         setting would be ".o" for most Unix platforms and ".obj" for Windows.
         """
                               )

    preprocessorSymbols = property(fget = _getPreprocessorSymbols,
                                   fset = _setPreprocessorSymbols,
                                   doc = """
         The mapping of additional preprocessor symbols (apart from
         CHILLYBUILD_OS_<osname>) that this platform requires to be defined (an
         example would be WIN32 and its variations on Windows/x86).
         """
                                  )

    staticLibName = property(fget = _getStaticLibName,
                             fset = _setStaticLibName,
                             doc = """
         A function that takes one argument: project name.  It then
         returns the static library name for this project, for example,
         for a project named "whatever", on a typical Unix system, the
         functions will return "libwhatever.a".
         """
                            )

    sharedLibName = property(fget = _getSharedLibName,
                             fset = _setSharedLibName,
                             doc = """

         A function that takes three arguments: project name, major version and
         a minor version.  It then returns the shared library name for this
         project, for example, for a project named "whatever", on a typical Unix
         system, the function will return something like "libwhatever.so.1.0".

         """
                            )

    soName = property(fget = _getSoName,
                      fset = _setSoName,
                      doc = """

         A function that takes three arguments: project name, major version and
         a minor version.  On ELF platforms, it then returns the soname to be
         used for building the shared library for this project on this platform.
         On non-ELF systems, the function is a no-op and the return value is
         None.  The meaning of soname is detailed, e.g., in GNU loader man page
         (man ld on a Linux system).  Practically, for a project named
         "whatever", on a typical Unix system, the function will return
         something like "libwhatever.so.1".

         """
                            )

    soLinkerName = property(fget = _getSoLinkerName,
                            fset = _setSoLinkerName,
                            doc = """

         A function that takes three arguments: project name, major version and
         a minor version.  On ELF platforms, it then returns the linker name
         for the shared library for this project on this platform.  The linker
         name in this context is the name which will be passed to the linker
         when linking things (executables and other shared libraries) with this
         library.  On a typical Unix system, for a project named "whatever",
         this function will return "libwhatever.so".  On non-ELF systems, the
         function is a no-op and the return value is None.

         """
                            )

    executableName = property(fget = _getExecutableName,
                              fset = _setExecutableName,
                              doc = """
         A function that takes one argument: project name.  It then
         returns the static library name for this project, for example,
         for a project named "whatever", on a Windows system, the
         functions will return "whatever.exe".

                            """
                            )

    staticLinker = property(fget = _getStaticLinker,
                            fset = _setStaticLinker,
                            doc = """
         A function that takes two arguments: the output (static
         library) file name (as a string) and a sequence of input
         (object files) file names, in that order.  The function then
         returns a list of argv elements suitable for passing to Popen
         for invocation of the static linker.
         """
                           )

    sharedLibLoaderPathAdder = property(fget = _getSharedLibLoaderPathAdder,
                                        fset = _setSharedLibLoaderPathAdder,
                                        doc = """
         A function that takes two arguments: an environment dictionary (see
         os.environ for an example) and a path component.  The function's return
         value, if any, should be ignored.  Once the function is called,
         starting a process with the environment dictionary passed to the
         function, should result in the process being able to locate its
         dependent shared libraries located under the corresponding path.
         """
                                       )

def getPlatformSettings(osName, osVersion, procArch):
    """

    Returns an instance of the PlatformSettings class (above) with all
    properties set to the correct values for the caller-supplied combination of
    OS name/version and processor architecture.

    """

    settings = PlatformSettings()

    if osName.lower() == "windows":
        settings.objectFileSuffix = ".obj"
        settings.staticLibName = lambda projectName: "%s.lib" % projectName
        settings.sharedLibName = lambda projectName, major, minor: "%s.dll" % \
                                                                   projectName
        settings.soName = lambda projectName, major, minor: None
        settings.soLinkerName = lambda projectName, major, minor: None
        settings.executableName = lambda projectName: "%s.exe" % projectName
        settings.staticLinker = \
                lambda out, filelist, optimize, disableThreading: \
                ["lib.exe", "-nologo", "-out:%s" % out] + filelist
        if procArch == "x86_64" or procArch == "ia64":
            settings.preprocessorSymbols = {"WIN64" : None, "_WIN64" : None}
        else:
            settings.preprocessorSymbols = {"WIN32" : None, "_WIN32" : None}

        # MSVC complains if these are not defined.  I am not sure if the
        # _WIN32_WINNT symbol is specific to 32-bit versions of Windows; but
        # I am thinking not.  Practically, it doesn't appear to matter what
        # we set this to, so I am setting it to Windows 7.  We can probably
        # safely set it to a lower setting if necessary.
        settings.preprocessorSymbols["_WIN32_WINNT"] = "_WIN32_WINNT_WIN7"
        settings.preprocessorSymbols["NTDDI_VERSION"] = "NTDDI_WIN7"

        settings.sharedLibLoaderPathAdder = \
                lambda env, path: pathAdder("PATH", ";", env, path)
    elif osName.lower() == "darwin":
        settings.staticLinker = \
                lambda out, filelist, optimize, disableThreading: \
                ["libtool", "-static", "-o", out] + filelist
        settings.sharedLibName = lambda projectName, major, minor: \
                                        "lib%s.%s.%s.dylib" % \
                                        (projectName,
                                         major,
                                         minor)
        settings.soName = lambda projectName, major, minor: None
        settings.soLinkerName = lambda projectName, major, minor: None
        settings.sharedLibLoaderPathAdder = \
                lambda env, path: pathAdder("DYLD_LIBRARY_PATH", ":", env, path)
    elif osName.lower() == "linux":
        settings.staticLinker = \
                lambda out, filelist, optimize, disableThreading: \
                ["ar", "rc", out] + filelist

    return settings


text:
<?php

defined('JPATH_PLATFORM') or die;

/**
 * Field to select a user ID from a modal list.
 *
 * @package     Joomla.Libraries
 * @subpackage  Form
 * @since       1.6
 */
class JFormFieldUser extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	public $type = 'User';

	/**
	 * Method to get the user field input markup.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$html = array();
		$groups = $this->getGroups();
		$excluded = $this->getExcluded();
		$link = 'index.php?option=com_users&view=users&layout=modal&tmpl=component&field=' . $this->id
			. (isset($groups) ? ('&groups=' . base64_encode(json_encode($groups))) : '')
			. (isset($excluded) ? ('&excluded=' . base64_encode(json_encode($excluded))) : '');

		// Initialize some field attributes.
		$attr = !empty($this->class) ? ' class="' . $this->class . '"' : '';
		$attr .= !empty($this->size) ? ' size="' . $this->size . '"' : '';
		$attr .= $this->required ? ' required' : '';

		// Load the modal behavior script.
		JHtml::_('behavior.modal', 'a.modal_' . $this->id);

		// Build the script.
		$script = array();
		$script[] = '	function jSelectUser_' . $this->id . '(id, title) {';
		$script[] = '		var old_id = document.getElementById("' . $this->id . '_id").value;';
		$script[] = '		if (old_id != id) {';
		$script[] = '			document.getElementById("' . $this->id . '_id").value = id;';
		$script[] = '			document.getElementById("' . $this->id . '").value = title;';
		$script[] = '			document.getElementById("' . $this->id . '").className = document.getElementById("' . $this->id . '").className.replace(" invalid" , "");';
		$script[] = '			' . $this->onchange;
		$script[] = '		}';
		$script[] = '		SqueezeBox.close();';
		$script[] = '	}';

		// Add the script to the document head.
		JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

		// Load the current username if available.
		$table = JTable::getInstance('user');

		if (is_numeric($this->value))
		{
			$table->load($this->value);
		}
		// Handle the special case for "current".
		elseif (strtoupper($this->value) == 'CURRENT')
		{
			$table->load(JFactory::getUser()->id);
		}
		else
		{
			$table->username = JText::_('JLIB_FORM_SELECT_USER');
		}

		// Create a dummy text field with the user name.
		$html[] = '
';
		$html[] = '	<input type="text" id="' . $this->id . '" value="' . htmlspecialchars($table->name, ENT_COMPAT, 'UTF-8') . '"'
			. ' readonly' . $attr . ' />';

		// Create the user select button.
		if ($this->readonly === false)
		{
			$html[] = '		id . '" title="' . JText::_('JLIB_FORM_CHANGE_USER') . '" href="' . $link . '"'
				. ' rel="{handler: \'iframe\', size: {x: 800, y: 500}}">';
			$html[] = '';
		}

		$html[] = '
';

		// Create the real field, hidden, that stored the user id.
		$html[] = '<input type="hidden" id="' . $this->id . '_id" name="' . $this->name . '" value="' . (int) $this->value . '" />';

		return implode("\n", $html);
	}

	/**
	 * Method to get the filtering groups (null means no filtering)
	 *
	 * @return  mixed  array of filtering groups or null.
	 *
	 * @since   1.6
	 */
	protected function getGroups()
	{
		return null;
	}

	/**
	 * Method to get the users to exclude from the list of users
	 *
	 * @return  mixed  Array of users to exclude or null to to not exclude them
	 *
	 * @since   1.6
	 */
	protected function getExcluded()
	{
		return null;
	}
}


text:
class AddTlsCriteria < ActiveRecord::Migration[4.2]
  def change
    add_column :projects, :crypto_used_network_status, :string, default: '?'
    add_column :projects, :crypto_used_network_justification, :text

    add_column :projects, :crypto_tls12_status, :string, default: '?'
    add_column :projects, :crypto_tls12_justification, :text

    add_column :projects,
               :crypto_certificate_verification_status, :string, default: '?'
    add_column :projects, :crypto_certificate_verification_justification, :text

    add_column :projects,
               :crypto_verification_private_status, :string, default: '?'
    add_column :projects, :crypto_verification_private_justification, :text
  end
end


text:
chmod 700 ../cloud/provisioner/certs/ca.crt
cp CA/cacert.pem ../cloud/provisioner/certs/ca.crt
cp certs/cloud/cloud.server.crt ../cloud/provisioner/certs/server.crt
openssl rsa -in certs/cloud/cloud.server.key -passin file:certs/cloud/cloud-passwd -out ../cloud/provisioner/certs/server.key
# make a dh param file for the web server
[ ! -f ../cloud/provisioner/certs/dh.pem ] && openssl dhparam -out ../cloud/provisioner/certs/dh.pem 2048

# CA copy for the provisioner
chmod 700 ../cloud/provisioner/data/ca-passwd

rm -rf ../cloud/provisioner/data/CA/
cp -R CA ../cloud/provisioner/data/CA/
cp ca-passwd ../cloud/provisioner/data/
cp openssl.conf ../cloud/provisioner/data/
sed -i '' -e 's|dir = CA|dir = /data/CA|' ../cloud/provisioner/data/openssl.conf

# Trust and Key Stores for the NiFis
for server in secloud cloud booth
do
  rm -rf ../$server/nifi/certs/
  mkdir ../$server/nifi/certs/
  cp certs/$server/$server.client.keystore.jks ../$server/nifi/certs/client.keystore.jks
  cp certs/$server/$server.server.keystore.jks ../$server/nifi/certs/keystore.jks
  cp certs/$server/$server.truststore.jks ../$server/nifi/certs/truststore.jks
  cat certs/$server/pass-* | sed 's/: /=/' > ../$server/nifi/certs/passwd
done

for server in piwinifi1 piwinifi2 piwinifi3
do
  mkdir -p ../secloud/nifi/certs/
  cp certs/$server/$server.server.keystore.jks ../secloud/nifi/certs/$server.keystore.jks
  cp certs/$server/$server.truststore.jks ../secloud/nifi/certs/$server.truststore.jks
  cat certs/$server/pass-* | sed 's/: /=/' > ../secloud/nifi/certs/$server.passwd
done

# add pi certs
cp CA/cacert.pem ../pi/deploy/ca.crt
openssl rsa -in certs/cloud/cloud.client.key -passin file:certs/cloud/cloud-client-passwd -out ../pi/deploy/client.key
cp certs/cloud/cloud.client.crt ../pi/deploy/client.crt


text:
package metrics

type metric struct {
	Name string
	Tags map[string]string
	Rate float64
}

type intMetric struct {
	metric
	Value int64
}

type floatMetric struct {
	metric
	Value float64
}

type fakeMetricsReporter struct {
	LastCountMetric              *intMetric
	LastTimeInMillisecondsMetric *floatMetric
}

func newFakeMetricsReporter() *fakeMetricsReporter {
	return &fakeMetricsReporter{}
}

func (r *fakeMetricsReporter) Count(name string, value int64, tags map[string]string, rate float64) error {
	r.LastCountMetric = &intMetric{
		metric{name, tags, rate},
		value,
	}
	return nil
}

func (r *fakeMetricsReporter) Gauge(name string, value float64, tags map[string]string, rate float64) error {
	return nil
}

func (r *fakeMetricsReporter) Histogram(name string, value float64, tags map[string]string, rate float64) error {
	return nil
}

func (r *fakeMetricsReporter) Distribution(name string, value float64, tags map[string]string, rate float64) error {
	return nil
}

func (r *fakeMetricsReporter) Set(name string, value string, tags map[string]string, rate float64) error {
	return nil
}

func (r *fakeMetricsReporter) TimeInMilliseconds(name string, value float64, tags map[string]string, rate float64) error {
	r.LastTimeInMillisecondsMetric = &floatMetric{
		metric{name, tags, rate},
		value,
	}
	return nil
}

func (r *fakeMetricsReporter) Close() error {
	return nil
}


text:
package org.gearvrf;

/** GVRF version strings. */
public class GVRVersion {
    /** Final HQ version. */
    public static final String V_1_5_0 = "1.5.0";

    /**
     * San Jose version, with a cleaner package structure.
     *
     * Future versions will be backward compatible with 1.6.0.
     */
    public static final String V_1_6_0 = "1.6.0";

    /** Adds asynchronous texture loading */
    public static final String V_1_6_1 = "1.6.1";

    /** Adds asynchronous mesh loading */
    public static final String V_1_6_2 = "1.6.2";

    /** Adds float point textures, and texture updating */
    public static final String V_1_6_3 = "1.6.3";

    /** Splash screen */
    public static final String V_1_6_4 = "1.6.4";

    /**
     * Remove deprecated loadMesh() methods; add blocking
     * {@link GVRContext#loadTexture(GVRAndroidResource)} method.
     */
    public static final String V_1_6_5 = "1.6.5";

    /**
     * Add high-level
     * {@link GVRPicker#findObjects(GVRScene, float, float, float, float, float, float)}
     * method.
     */
    public static final String V_1_6_6 = "1.6.6";

    /** Simpler asynch */
    public static final String V_1_6_7 = "1.6.7";

    /**
     * Add API ({@link GVRContext#captureScreen3D(GVRScreenshot3DCallback)}) to
     * capture 3D screenshot.
     *
     * Add high-level {@link GVRSceneObject#GVRSceneObject(GVRContext,
     * Future<GVRMesh>, Future<GVRTexture>)} constructor.
     *
     * Add {@link FutureWrapper} to generate required Future<T> for the new
     * constructor.
     */
    public static final String V_1_6_8 = "1.6.8";

    /**
     * Add cube map texture support.
     */
    public static final String V_1_6_9 = "1.6.9";

    /**
     * No more reference counting - Java objects control native objects'
     * lifecycles.
     */
    public static final String V_2_0_0 = "2.0.0";

    /**
     * Optimize memory management by getting rid of {@code finalize()} method.
     * Add support for Future<{@link GVREyePointee}>s. Add
     * {@link GVRContext#getActivity()}.
     */
    public static final String V_2_0_1 = "2.0.1";

    /** Resource caching */
    public static final String V_2_0_2 = "2.0.2";

    public static final String CURRENT = V_2_0_2;
}


text:
#pragma once

#include <app/clusters/content-launch-server/content-launch-server.h>
#include <vector>

using chip::CharSpan;
using chip::EndpointId;
using chip::app::AttributeValueEncoder;
using chip::app::CommandResponseHelper;
using ContentLauncherDelegate = chip::app::Clusters::ContentLauncher::Delegate;
using LaunchResponseType      = chip::app::Clusters::ContentLauncher::Commands::LaunchResponse::Type;
using ParameterType           = chip::app::Clusters::ContentLauncher::Structs::Parameter::DecodableType;
using BrandingInformationType = chip::app::Clusters::ContentLauncher::Structs::BrandingInformation::Type;

class ContentEntry
{
public:
    std::string mName;
    std::vector<ParameterType> mSearchFields;
};

class ContentLauncherManager : public ContentLauncherDelegate
{
public:
    ContentLauncherManager() : ContentLauncherManager({ "example", "example" }, 0){};
    ContentLauncherManager(std::list<std::string> acceptHeaderList, uint32_t supportedStreamingProtocols);

    void HandleLaunchContent(CommandResponseHelper<LaunchResponseType> & helper,
                             const chip::app::DataModel::DecodableList<ParameterType> & parameterList, bool autoplay,
                             const CharSpan & data) override;
    void HandleLaunchUrl(CommandResponseHelper<LaunchResponseType> & helper, const CharSpan & contentUrl,
                         const CharSpan & displayString, const BrandingInformationType & brandingInformation) override;
    CHIP_ERROR HandleGetAcceptHeaderList(AttributeValueEncoder & aEncoder) override;
    uint32_t HandleGetSupportedStreamingProtocols() override;

    uint32_t GetFeatureMap(chip::EndpointId endpoint) override;

protected:
    std::list<std::string> mAcceptHeaderList;
    uint32_t mSupportedStreamingProtocols;
    std::vector<ContentEntry> mContentList;

private:
    EndpointId mEndpointId;
    // TODO: set this based upon meta data from app
    uint32_t mDynamicEndpointFeatureMap = 3;
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.alexishida.controller;

import com.alexishida.utils.Id3tag;
import com.alexishida.utils.LastFM;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.URIException;
import org.blinkenlights.jid3.ID3Exception;
import org.json.JSONException;

/**
 *
 * @author 94954658268
 */
public class Musica {

    public String nomeMusica = "";
    public String nomeArtista = "";

    public boolean renomear(String localArquivo,String nomeArquivo) {

        Id3tag id3tag = new Id3tag();
        try {
            id3tag.renomear(localArquivo, getArtista(nomeArquivo), getTitulo(nomeArquivo));
            return true;
        } catch (ID3Exception ex) {
           return false;
        }

    }

    private String getTitulo(String nomeArquivo) {

            String retorno = "";
            String musica = removeExtensao(nomeArquivo);
            musica = musica.trim();
            String[] musica_string = musica.split("-");

            if (musica_string.length == 2)
            {

                retorno = musica_string[1].trim();

            }

            else if (musica_string.length == 3)
            {

                retorno = musica_string[2].trim();

            }

            else
            {

                retorno = "";

            }

            this.nomeMusica = retorno;

            return retorno;

    }

     private String getArtista(String nomeArquivo)
        {

            String retorno = "";

            String musica = removeExtensao(nomeArquivo);
            musica = musica.trim();
            String[] musica_string = musica.split("-");

            if (musica_string.length == 2)
            {

                retorno = musica_string[0].trim();

            }

            else if (musica_string.length == 3)
            {

                retorno = musica_string[0].trim() + "-" + musica_string[1].trim();

            }

            else
            {

                retorno = musica;

            }

            this.nomeArtista = retorno;
            return retorno;

        }

     private String removeExtensao(String nome) {

        String retorno;

        retorno = nome.trim();
        retorno = retorno.replaceAll(".mp3", "");
        retorno = retorno.replaceAll(".Mp3", "");
        retorno = retorno.replaceAll(".MP3", "");

        return retorno;

     }

     public byte[] obtemCapa(String artista,String titulo) {

         String json = "";
         String link_capa = "";
         LastFM last_fm = new LastFM();

        try {
            json = last_fm.buscaPorMusicaJson(artista, titulo);

            try {
                 link_capa = last_fm.obtemLinkCapa(json);
                 System.out.println(link_capa);
                return last_fm.downloadUrl(link_capa);

             } catch (JSONException ex) {
                 //Logger.getLogger(Musica.class.getName()).log(Level.SEVERE, null, ex);
                 return null;
             }

        } catch (URIException ex) {
           // Logger.getLogger(Musica.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (MalformedURLException ex) {
           // Logger.getLogger(Musica.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (IOException ex) {
          //   Logger.getLogger(Musica.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

     }
}


text:
package container;

/**
 * Implement a min heap.
 */
public class BinaryHeap<E extends Comparable<E>> {
    private E[] arr;   // arr[0] not used
    int N;          // arr[1, N] used

    /**
     * Creates a binary heap.
     * @param capacity The initial capacity of the heap.
     */
    @SuppressWarnings(value="unchecked")
    public BinaryHeap(int capacity) {
        arr = (E[]) new Comparable[capacity + 1];
        N = 0;
    }

    /**
     * Creates a binary heap with initial capacity 15.
     */
    public BinaryHeap() {
        this(15);
    }

    private void exch(int i, int j) {
        E tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    /**
     * Bottom-up reheapify, if the kth element is smaller than its parent.
     */
    private void swim(int k) {
        // exchange the node with its parent until in heap order.
        while (k > 1 && arr[k].compareTo(arr[k/2]) < 0) {
            exch(k, k/2);
            k = k/2;
        }
    }

    /**
     * Top-down reheapify,
     * if the kth element is greater than one or both of its children.
     */
    private void sink(int k) {
        // exchange the node with its smaller node until in heap order.
        int j = 2*k;   // index of the smaller child
        while (j <= N) {
            if (j < N && arr[j].compareTo(arr[j+1]) > 0) j++;
            if (arr[k].compareTo(arr[j]) > 0) {
                exch(j, k);
                k = j;
                j = 2*k;
            } else {
                break;
            }
        }
    }

    /**
     * Return the size of the heap.
     * @return number of elements in the heap.
     */
    public int size() {
        return N;
    }

    /**
     * Check if the heap is empty.
     * @return ture if the heap is empty.
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * Return the minimal(top) elements in the heap.
     * @return the top element in the heap.
     * @throws EmptyHeapException If the heap is empty.
     */
    public E getMin() {
        if (N == 0) {
            throw new EmptyHeapException();
        }
        return arr[1];
    }

    /**
     * Insert an element into the heap.
     * @param item The element to insert.
     * @return The heap itself.
     */
    @SuppressWarnings(value="unchecked")
    public BinaryHeap<E> insert(E item) {
        if (++N == arr.length) {
            E[] narr = (E[]) new Comparable[N*2];
            System.arraycopy(arr, 0, narr, 0, N);
            arr = narr;
        }
        arr[N] = item;
        swim(N);
        return this;
    }

    /**
     * Retrieve and remove the minimal(top) element in the heap.
     * @return the top element in the heap.
     * @throws EmptyHeapException If the heap is empty.
     */
    @SuppressWarnings(value="unchecked")
    public E extractMin() {
        E min = getMin();
        arr[1] = arr[N];
        arr[N--] = null;
        sink(1);
        if (N <= arr.length/4 && N > 15) {
            E[] narr = (E[]) new Comparable[N*2];
            System.arraycopy(arr, 0, narr, 0, N);
            arr = narr;
        }
        return min;
    }
}

class EmptyHeapException extends RuntimeException {
    public EmptyHeapException() {
    }
}


text:
import {LayoutView} from 'marionette';
import ListItemButton from 'foreground/view/behavior/listItemButton';
import playListItemButtonTemplate from 'template/listItemButton/playListItemButton.hbs!';
import playIconTemplate from 'template/icon/playIcon_18.hbs!';

var PlayPlaylistButtonView = LayoutView.extend({
  template: playListItemButtonTemplate,
  templateHelpers: {
    playIcon: playIconTemplate
  },

  behaviors: {
    ListItemButton: {
      behaviorClass: ListItemButton
    }
  },

  streamItems: null,
  playlist: null,

  playlistItemsEvents: {
    'add:completed': '_onPlaylistItemsAddCompleted',
    'remove': '_onPlaylistItemsRemove',
    'reset': '_onPlaylistItemsReset'
  },

  initialize: function(options) {
    this.streamItems = options.streamItems;
    this.playlist = options.playlist;
    this.bindEntityEvents(this.playlist.get('items'), this.playlistItemsEvents);
  },

  onRender: function() {
    this._setState(this.playlist.get('items').isEmpty());
  },

  onClick: function() {
    var videos = this.playlist.get('items').pluck('video');

    this.streamItems.addVideos(videos, {
      playOnAdd: true
    });
  },

  _onPlaylistItemsAddCompleted: function(collection) {
    this._setState(collection.isEmpty());
  },

  _onPlaylistItemsRemove: function(model, collection) {
    this._setState(collection.isEmpty());
  },

  _onPlaylistItemsReset: function(collection) {
    this._setState(collection.isEmpty());
  },

  _setState: function(isEmpty) {
    this.$el.toggleClass('is-disabled', isEmpty);
    this.model.set('enabled', !isEmpty);

    var tooltipText = isEmpty ? chrome.i18n.getMessage('playlistEmpty') : chrome.i18n.getMessage('play');
    this.$el.attr('data-tooltip-text', tooltipText);
  }
});

export default PlayPlaylistButtonView;


text:
var services = angular.module('Services', []);

/**
* Service handling the internationalization of the UI.
* Acts as a wrapper around the i18n.js variable.
**/
services.factory('Lang', function Lang(){
  var lang = i18n;
  var languages = [];
  for (var key in lang) {
      languages.push(key);
  }
  lang.all_lang = languages;
  lang.curr_lang = 'en_us';
  lang.setLanguage = function(language){
    for(var i = 0 ; i < this.all_lang.length ; i++){
      if(this.all_lang[i] == language){
        this.curr_lang = this.all_lang[i];
      }
    }
  };
  lang.getLanguage = function(){
    return this.curr_lang;
  };

  lang.get = function(getstr){

    //Getting all of the text for the set language
    var all_indexes = this[this.curr_lang];
    //Finding next index of the dot or the next opening square bracket
    var dotindex = getstr.indexOf('.');
    var arrindex = getstr.indexOf('[');
    var is_dotindex;
    var str;
    while(dotindex !== -1 || arrindex !== -1){

      //Determines if next level is object or array
      is_dotindex = (dotindex < arrindex && dotindex !== -1) || arrindex === -1;

      //Finding the json index
      str = getstr.substring(0, (is_dotindex)? dotindex:arrindex);

      if(all_indexes[str] !== undefined){
        //console.log(all_indexes[str]);
        all_indexes = all_indexes[str];
      }else{
        return undefined;
      }

      //Finds the array index between the square brackets
      if(!is_dotindex){
        str = getstr.substring(arrindex+1, getstr.indexOf(']'));
        //console.log('!is_dotindex str: '+ str);
        if(all_indexes[str] !== undefined){
          //console.log(all_indexes[str]);
          all_indexes = all_indexes[str];
        }else{
          return undefined;
        }
      }

      //Update indexes and get string
      getstr = getstr.substring(((is_dotindex)? dotindex:getstr.indexOf(']'))+1, getstr.length);
      dotindex = getstr.indexOf('.');
      arrindex = getstr.indexOf('[');

      //Checks for extreme cases (multidimensional arrays, dot right after array notation)
      while(arrindex === 0){

        str = getstr.substring(arrindex+1, getstr.indexOf(']'));

        if(all_indexes[str] !== undefined){
          all_indexes = all_indexes[str];
        }else{
          return undefined;
        }
        getstr = getstr.substring(((is_dotindex)? dotindex:getstr.indexOf(']'))+1, getstr.length);
        dotindex = getstr.indexOf('.');
        arrindex = getstr.indexOf('[');
      }
      if(dotindex === 0){
        is_dotindex = true;
        getstr = getstr.substring(1, getstr.length);
        dotindex = getstr.indexOf('.');
        arrindex = getstr.indexOf('[');
        if(dotindex === 0 || arrindex === 0){
          return undefined;
        }
      }
    }

    //Getting the final value of interest
    if(is_dotindex){
      if(all_indexes[getstr] !== undefined){
        return all_indexes[getstr];
      }else{
        return undefined;
      }
    }else{
      return all_indexes;
    }

  };
  return lang;
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Reyna.Interfaces
{
    public interface IStoreService : IDisposable
    {
        void Initialize(IRepository sourceStore, IRepository targetStore);

        void Start();

        void Stop();
    }
}


text:
__author__="kebo"
__date__ ="$2009-11-16 14:05:55$"
import sys
import getopt
import string
import cx_Oracle
from py_interface import erl_node
from py_interface import erl_opts
from py_interface import erl_eventhandler
db = cx_Oracle.connect('dsm', 'dsm', 'localhost:1521/dsmdb')
db.autocommit = True
counter = 0

m=None

n=None

def _TestMBoxRPCResponse(msg):
    print "hello"

def __TestMBoxCallback(msg):
   global counter
   global db
   counter +=1
   cur = db.cursor()
   #print msg
   roam_in = 0
   if string.find(msg[0],"+86") == -1 :
   	roam_in = 1
   cur.execute("insert into stat_session(id,msisdn,teid_i,teid,end_user_addr, begin_time, end_time,upload,download,session_duration,apn,roam_in) values(stat_session_seq.nextval,:a,:b,:c,:d,:e,:f,:g,:h,:i,:j,:k)",{'a':msg[0],'b':msg[1],'c':msg[2],'d':msg[3],'e':msg[4][0],'f':msg[5][0],'g':msg[6],'h':msg[7],'i':msg[8],'j':msg[9],'k':roam_in})

def main(argv):
    global m
    try:
        opts, args = getopt.getopt(argv[1:], "?n:c:")
    except getopt.error, info:
        print info
        sys.exit(1)

    hostName = "localhost"
    ownNodeName = "dsm_session_statistics_node"
    cookie = "cookie"

    for (optchar, optarg) in opts:
        if optchar == "-?":
            print "Usage: %s erlnode" % argv[0]
            sys.exit(1)
        elif optchar == "-c":
            cookie = optarg
        elif optchar == "-n":
            ownNodeName = optarg

    print "Creating node..."
    n = erl_node.ErlNode(ownNodeName, erl_opts.ErlNodeOpts(cookie=cookie))
    print "Publishing node..."
    n.Publish()
    print "Creating mbox..."
    m = n.CreateMBox(__TestMBoxCallback)
    print "Registering mbox as p..."
    m.RegisterName("db")

    print "Looping..."
    evhand = erl_eventhandler.GetEventHandler()
    evhand.Loop()
    db.close()

main(sys.argv)


text:
#include <zxing/qrcode/decoder/BitMatrixParser.h>
#include <zxing/qrcode/decoder/DataMask.h>

namespace zxing {
namespace qrcode {

int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) {
  return bitMatrix_->get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1;
}

BitMatrixParser::BitMatrixParser(Ref<BitMatrix> bitMatrix) :
    bitMatrix_(bitMatrix), parsedVersion_(0), parsedFormatInfo_() {
  size_t dimension = bitMatrix->getDimension();
  if ((dimension < 21) || (dimension & 0x03) != 1) {
    throw ReaderException("Dimension must be 1 mod 4 and >= 21");
  }
}

Ref<FormatInformation> BitMatrixParser::readFormatInformation() {
  if (parsedFormatInfo_ != 0) {
    return parsedFormatInfo_;
  }

  // Read top-left format info bits
  int formatInfoBits1 = 0;
  for (int i = 0; i < 6; i++) {
    formatInfoBits1 = copyBit(i, 8, formatInfoBits1);
  }
  // .. and skip a bit in the timing pattern ...
  formatInfoBits1 = copyBit(7, 8, formatInfoBits1);
  formatInfoBits1 = copyBit(8, 8, formatInfoBits1);
  formatInfoBits1 = copyBit(8, 7, formatInfoBits1);
  // .. and skip a bit in the timing pattern ...
  for (int j = 5; j >= 0; j--) {
    formatInfoBits1 = copyBit(8, j, formatInfoBits1);
  }

  // Read the top-right/bottom-left pattern
  int dimension = (int)bitMatrix_->getDimension();
  int formatInfoBits2 = 0;
  int jMin = dimension - 7;
  for (int j = dimension - 1; j >= jMin; j--) {
    formatInfoBits2 = copyBit(8, j, formatInfoBits2);
  }
  for (int i = dimension - 8; i < dimension; i++) {
    formatInfoBits2 = copyBit(i, 8, formatInfoBits2);
  }

  parsedFormatInfo_ = FormatInformation::decodeFormatInformation(formatInfoBits1,formatInfoBits2);
  if (parsedFormatInfo_ != 0) {
    return parsedFormatInfo_;
  }
  throw ReaderException("Could not decode format information");
}

Version *BitMatrixParser::readVersion() {
  if (parsedVersion_ != 0) {
    return parsedVersion_;
  }

  int dimension = (int)bitMatrix_->getDimension();

  int provisionalVersion = (dimension - 17) >> 2;
  if (provisionalVersion <= 6) {
    return Version::getVersionForNumber(provisionalVersion);
  }

  // Read top-right version info: 3 wide by 6 tall
  int versionBits = 0;
  for (int y = 5; y >= 0; y--) {
    int xMin = dimension - 11;
    for (int x = dimension - 9; x >= xMin; x--) {
      versionBits = copyBit(x, y, versionBits);
    }
  }

  parsedVersion_ = Version::decodeVersionInformation(versionBits);
  if (parsedVersion_ != 0 && parsedVersion_->getDimensionForVersion() == dimension) {
    return parsedVersion_;
  }

  // Hmm, failed. Try bottom left: 6 wide by 3 tall
  versionBits = 0;
  for (int x = 5; x >= 0; x--) {
    int yMin = dimension - 11;
    for (int y = dimension - 9; y >= yMin; y--) {
      versionBits = copyBit(x, y, versionBits);
    }
  }

  parsedVersion_ = Version::decodeVersionInformation(versionBits);
  if (parsedVersion_ != 0 && parsedVersion_->getDimensionForVersion() == dimension) {
    return parsedVersion_;
  }
  throw ReaderException("Could not decode version");
}

ArrayRef<unsigned char> BitMatrixParser::readCodewords() {
  Ref<FormatInformation> formatInfo = readFormatInformation();
  Version *version = readVersion();

  //	cerr << *bitMatrix_ << endl;
  //	cerr << bitMatrix_->getDimension() << endl;

  // Get the data mask for the format used in this QR Code. This will exclude
  // some bits from reading as we wind through the bit matrix.
  DataMask &dataMask = DataMask::forReference((int)formatInfo->getDataMask());
  //	cout << (int)formatInfo->getDataMask() << endl;
  int dimension = (int)bitMatrix_->getDimension();
  dataMask.unmaskBitMatrix(*bitMatrix_, dimension);

  //		cerr << *bitMatrix_ << endl;
  //	cerr << version->getTotalCodewords() << endl;

  Ref<BitMatrix> functionPattern = version->buildFunctionPattern();

  //	cout << *functionPattern << endl;

  bool readingUp = true;
  ArrayRef<unsigned char> result(version->getTotalCodewords());
  int resultOffset = 0;
  int currentByte = 0;
  int bitsRead = 0;
  // Read columns in pairs, from right to left
  for (int x = dimension - 1; x > 0; x -= 2) {
    if (x == 6) {
      // Skip whole column with vertical alignment pattern;
      // saves time and makes the other code proceed more cleanly
      x--;
    }
    // Read alternatingly from bottom to top then top to bottom
    for (int counter = 0; counter < dimension; counter++) {
      int y = readingUp ? dimension - 1 - counter : counter;
      for (int col = 0; col < 2; col++) {
        // Ignore bits covered by the function pattern
        if (!functionPattern->get(x - col, y)) {
          // Read a bit
          bitsRead++;
          currentByte <<= 1;
          if (bitMatrix_->get(x - col, y)) {
            currentByte |= 1;
          }
          // If we've made a whole byte, save it off
          if (bitsRead == 8) {
            result[resultOffset++] = (unsigned char)currentByte;
            bitsRead = 0;
            currentByte = 0;
          }
        }
      }
    }
    readingUp = !readingUp; // switch directions
  }

  if (resultOffset != version->getTotalCodewords()) {
    throw ReaderException("Did not read all codewords");
  }
  return result;
}

}
}


text:
package tests

import (
	"fmt"
	"testing"
)

func TestTimeConsuming(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}
	fmt.Printf("done\n")
}

func TestTrololo(t *testing.T) {
	fmt.Printf("trololo\n")
	fmt.Printf("done\n")
}


text:
package main_test

import (
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/vito/cmdtest"
	. "github.com/vito/cmdtest/matchers"

	"github.com/vito/gocart/dependency"
	"github.com/vito/gocart/set"
)

var currentDirectory,
	fakeDiverseRepoPath,
	fakeLockedGitRepoPath,
	fakeGitRepoPath, fakeGitRepoWithRevisionPath,
	fakeLockedGitRepoWithNewDepPath,
	fakeLockedGitRepoWithRemovedDepPath,
	fakeHgRepoPath, fakeHgRepoWithRevisionPath,
	fakeBzrRepoPath, fakeBzrRepoWithRevisionPath,
	fakeUnlockedRepoWithRecursiveDependencies,
	fakeUnlockedRepoWithRecursiveConflictingDependencies,
	fakeUnlockedRepoWithTestDependencies string

var _ = BeforeEach(func() {
	var err error

	_, currentFile, _, _ := runtime.Caller(0)
	currentDirectory = path.Dir(currentFile)

	destTmpDir, err := ioutil.TempDir(os.TempDir(), "wtf")
	Ω(err).ShouldNot(HaveOccurred())

	err = walkTheDinosaur(currentDirectory, destTmpDir)
	Ω(err).ShouldNot(HaveOccurred())

	gocartDir := path.Join(destTmpDir, "gocart")

	fakeDiverseRepoPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_diverse_repo"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeLockedGitRepoPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_git_repo_locked"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeLockedGitRepoWithNewDepPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_git_repo_locked_with_new_dep"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeLockedGitRepoWithRemovedDepPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_git_repo_locked_with_removed_dep"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeGitRepoPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_git_repo"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeGitRepoWithRevisionPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_git_repo_with_revision"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeBzrRepoPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_bzr_repo"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeBzrRepoWithRevisionPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_bzr_repo_with_revision"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeHgRepoPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_hg_repo"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeHgRepoWithRevisionPath, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_hg_repo_with_revision"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeUnlockedRepoWithRecursiveDependencies, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_recursive_repo"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeUnlockedRepoWithRecursiveConflictingDependencies, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_recursive_repo_with_conflicting_dependencies"),
	)
	Ω(err).ShouldNot(HaveOccurred())

	fakeUnlockedRepoWithTestDependencies, err = filepath.Abs(
		path.Join(gocartDir, "fixtures", "fake_repo_with_test_tag"),
	)
	Ω(err).ShouldNot(HaveOccurred())
})

var _ = Describe("install", func() {
	gocartPath, err := cmdtest.Build("github.com/vito/gocart")
	if err != nil {
		panic(err)
	}

	// TODO: move to cmdtest
	err = os.Chmod(gocartPath, 0755)
	if err != nil {
		panic(err)
	}

	var installCmd *exec.Cmd
	var gopath string

	teeToStdout := func(w io.Writer) io.Writer {
		return io.MultiWriter(w, os.Stdout)
	}

	installing := func() *cmdtest.Session {
		sess, err := cmdtest.StartWrapped(installCmd, teeToStdout, teeToStdout)
		Expect(err).ToNot(HaveOccurred())

		return sess
	}

	install := func() {
		sess := installing()

		Expect(sess).To(Say("OK"))
		Expect(sess).To(ExitWith(0))
	}

	BeforeEach(func() {
		installCmd = exec.Command(gocartPath, "install")

		var err error

		gopath, err = ioutil.TempDir(os.TempDir(), "fake_repo_GOPATH")
		Expect(err).ToNot(HaveOccurred())

		installCmd.Env = []string{
			"GOPATH=" + gopath,
			"GOROOT=" + os.Getenv("GOROOT"),
			"PATH=" + os.Getenv("PATH"),
			"PYTHONPATH=" + os.Getenv("PYTHONPATH"), // bzr
		}
	})

	Context("without a Cartridge.lock", func() {
		It("downloads git dependencies", func() {
			installCmd.Dir = fakeGitRepoPath

			dependencyPath := path.Join(gopath, "src", "github.com", "vito", "gocart")

			Expect(listing(dependencyPath)).ToNot(ExitWith(0))

			install()

			Expect(listing(dependencyPath)).To(ExitWith(0))
		})

		It("checks out git repos to the given ref", func() {
			installCmd.Dir = fakeGitRepoWithRevisionPath

			dependencyPath := path.Join(gopath, "src", "github.com", "vito", "gocart")

			install()

			Expect(gitRevision(dependencyPath, "HEAD")).To(Say("7c9d1a95d4b7979bc4180d4cb4aebfc036f276de"))
		})

		It("downloads bzr dependencies", func() {
			installCmd.Dir = fakeBzrRepoPath

			dependencyPath := path.Join(gopath, "src", "launchpad.net", "gocheck")

			Expect(listing(dependencyPath)).ToNot(ExitWith(0))

			install()

			Expect(listing(dependencyPath)).To(ExitWith(0))
		})

		It("checks out bzr repos to the given ref", func() {
			installCmd.Dir = fakeBzrRepoWithRevisionPath

			dependencyPath := path.Join(gopath, "src", "launchpad.net", "gocheck")

			install()

			Expect(bzrRevision(dependencyPath)).To(Say("1"))
		})

		It("downloads hg dependencies", func() {
			installCmd.Dir = fakeHgRepoPath

			dependencyPath := path.Join(gopath, "src", "code.google.com", "p", "go.crypto", "ssh")

			Expect(listing(dependencyPath)).ToNot(ExitWith(0))

			install()

			Expect(listing(dependencyPath)).To(ExitWith(0))
		})

		It("checks out hg repos to the given ref", func() {
			installCmd.Dir = fakeHgRepoWithRevisionPath

			dependencyPath := path.Join(gopath, "src", "code.google.com", "p", "go.crypto", "ssh")

			install()

			Expect(hgRevision(dependencyPath)).To(Say("1e7a3e301825"))
		})

		It("generates a Cartridge.lock file", func() {
			installCmd.Dir = fakeDiverseRepoPath

			install()

			set, err := set.LoadFrom(installCmd.Dir)
			Expect(err).ToNot(HaveOccurred())

			dependency0Version := currentGitRevision(path.Join(gopath, "src", "github.com", "vito", "gocart"))
			dependency1Version := currentHgRevision(path.Join(gopath, "src", "code.google.com", "p", "go.crypto", "ssh"))

			Expect(set.Dependencies).To(HaveLen(2))
			Expect(set.Dependencies).To(Equal([]dependency.Dependency{
				{
					Path:    "github.com/vito/gocart",
					Version: dependency0Version,
				},
				{
					Path:    "code.google.com/p/go.crypto/ssh",
					Version: dependency1Version,
				},
			}))
		})
	})

	Context("with a Cartridge.lock", func() {
		It("installs the locked-down versions", func() {
			installCmd.Dir = fakeLockedGitRepoPath

			dependencyPath := path.Join(gopath, "src", "github.com", "vito", "gocart")

			install()

			Expect(gitRevision(dependencyPath, "HEAD")).To(Say("7c9d1a95d4b7979bc4180d4cb4aebfc036f276de"))
		})

		Context("when there are new dependencies in the Cartridge", func() {
			It("locks them down", func() {
				installCmd.Dir = fakeLockedGitRepoWithNewDepPath

				dependencyPath := path.Join(gopath, "src", "github.com", "onsi", "ginkgo")

				install()

				Expect(gitRevision(dependencyPath, "HEAD")).To(Say("334e06b31ec28f58e7f2df287d2bcf68f59af2b3"))

				set, err := set.LoadFrom(installCmd.Dir)
				Ω(err).ShouldNot(HaveOccurred())

				Expect(set.Dependencies).To(HaveLen(2))
				Expect(set.Dependencies).To(ContainElement(
					dependency.Dependency{
						Path: "github.com/onsi/ginkgo",
						// cfd6b07da4e69326bbd6b7057bbb4693cb78577b~1
						Version: "334e06b31ec28f58e7f2df287d2bcf68f59af2b3",
					},
				))
			})
		})

		Context("when there are dependencies removed from the Cartridge", func() {
			It("removes them from the lock", func() {
				installCmd.Dir = fakeLockedGitRepoWithRemovedDepPath

				install()

				set, err := set.LoadFrom(installCmd.Dir)
				Expect(err).ToNot(HaveOccurred())

				Expect(set.Dependencies).To(Equal([]dependency.Dependency{
					{
						Path:    "github.com/vito/gocart",
						Version: "7c9d1a95d4b7979bc4180d4cb4aebfc036f276de",
					},
				}))
			})
		})
	})

	Context("with -r", func() {
		BeforeEach(func() {
			installCmd.Args = append([]string{installCmd.Args[0], "-r"}, installCmd.Args[1:]...)
		})

		It("recursively installs dependencies", func() {
			installCmd.Dir = fakeUnlockedRepoWithRecursiveDependencies

			sess := installing()
			Expect(sess).To(Say("github.com/vito/gocart"))
			Expect(sess).To(Say("39ada75afb9b654b4621822e707258812bff34ac"))
			Expect(sess).To(Say("github.com/vito/cmdtest"))
			Expect(sess).To(Say("4b86f8c2259c55e86e4b971cd7dc5dfb03e41b80"))
			Expect(sess).ToNot(Say("github.com/onsi/(ginkgo|gomega)"))
			Expect(sess).To(Say("OK"))
			Expect(sess).To(ExitWith(0))

			Expect(gitRevision(
				path.Join(gopath, "src", "github.com", "vito", "cmdtest"),
				"HEAD",
			)).To(Say("4b86f8c2259c55e86e4b971cd7dc5dfb03e41b80"))
		})

		It("checks for conflicting dependencies (different SHAs)", func() {
			installCmd.Dir = fakeUnlockedRepoWithRecursiveConflictingDependencies

			sess := installing()
			Expect(sess).To(SayError("version conflict"))
			Expect(sess).ToNot(ExitWith(0))
		})
	})

	Context("with -x", func() {
		BeforeEach(func() {
			installCmd.Args = append(
				[]string{installCmd.Args[0], "-x", "test"},
				installCmd.Args[1:]...,
			)
		})

		It("excludes dependencies matching any of the given tags", func() {
			installCmd.Dir = fakeUnlockedRepoWithTestDependencies

			sess := installing()
			Expect(sess).To(Say("github.com/vito/gocart"))
			Expect(sess).To(Say("origin/master"))
			Expect(sess).ToNot(Say("github.com/onsi/(ginkgo|gomega)"))
			Expect(sess).To(ExitWith(0))
		})
	})
})

var _ = Describe("check", func() {
	gocartPath, err := cmdtest.Build("github.com/vito/gocart")
	if err != nil {
		panic(err)
	}

	// TODO: move to cmdtest
	err = os.Chmod(gocartPath, 0755)
	if err != nil {
		panic(err)
	}

	var installCmd *exec.Cmd
	var checkCmd *exec.Cmd
	var gopath string

	teeToStdout := func(w io.Writer) io.Writer {
		return io.MultiWriter(w, os.Stdout)
	}

	installing := func() *cmdtest.Session {
		sess, err := cmdtest.StartWrapped(installCmd, teeToStdout, teeToStdout)
		Expect(err).ToNot(HaveOccurred())

		return sess
	}

	checking := func() *cmdtest.Session {
		sess, err := cmdtest.StartWrapped(checkCmd, teeToStdout, teeToStdout)
		Expect(err).ToNot(HaveOccurred())

		return sess
	}

	install := func() {
		sess := installing()

		Expect(sess).To(Say("OK"))
		Expect(sess).To(ExitWith(0))
	}

	BeforeEach(func() {
		installCmd = exec.Command(gocartPath, "install")

		var err error

		gopath, err = ioutil.TempDir(os.TempDir(), "fake_repo_GOPATH")
		Expect(err).ToNot(HaveOccurred())

		installCmd.Env = []string{
			"GOPATH=" + gopath,
			"GOROOT=" + os.Getenv("GOROOT"),
			"PATH=" + os.Getenv("PATH"),
			"PYTHONPATH=" + os.Getenv("PYTHONPATH"), // bzr
		}

		checkCmd = exec.Command(gocartPath, "check")
		checkCmd.Env = installCmd.Env
	})

	itCorrectlyDetectsDirtyDependency := func(repo ...string) {
		Context("when the dependency is in a dirty state", func() {
			var repoPath string
			var repoImportPath string

			BeforeEach(func() {
				repoPath = path.Join(append([]string{gopath, "src"}, repo...)...)
				repoImportPath = path.Join(repo...)

				file, err := os.Create(path.Join(repoPath, "butts"))
				Ω(err).ShouldNot(HaveOccurred())

				file.Close()
			})

			It("reports it as dirty", func() {
				check := checking()
				Expect(check).To(Say(repoImportPath))
				Expect(check).To(ExitWith(1))
			})
		})

		Context("when the repo is so fresh and so clean clean", func() {
			It("exits 0", func() {
				check := checking()
				Expect(check).To(ExitWith(0))
			})
		})
	}

	Context("when the dependencies are not on disk", func() {
		BeforeEach(func() {
			checkCmd.Dir = fakeGitRepoPath

			// don't install
		})

		It("exits 0", func() {
			check := checking()
			Expect(check).To(ExitWith(0))
		})
	})

	Context("when the repo is on a different revision", func() {
		var repoPath string

		BeforeEach(func() {
			installCmd.Dir = fakeGitRepoPath
			checkCmd.Dir = fakeGitRepoPath

			install()

			repoPath = path.Join(gopath, "src", "github.com", "vito", "gocart")

			checkout := exec.Command("git", "checkout", "HEAD~1")
			checkout.Dir = repoPath

			err = checkout.Run()
			Ω(err).ShouldNot(HaveOccurred())
		})

		It("reports it as dirty", func() {
			check := checking()
			Expect(check).To(Say("github.com/vito/gocart"))
			Expect(check).To(Say(".*1.* behind"))
			Expect(check).To(ExitWith(1))
		})
	})

	Context("with recursive dependencies", func() {
		BeforeEach(func() {
			installCmd.Args = append([]string{installCmd.Args[0], "-r"}, installCmd.Args[1:]...)

			installCmd.Dir = fakeUnlockedRepoWithRecursiveDependencies
			checkCmd.Dir = fakeUnlockedRepoWithRecursiveDependencies

			install()
		})

		itCorrectlyDetectsDirtyDependency("github.com", "vito", "cmdtest")
	})

	Context("with a git dependency", func() {
		BeforeEach(func() {
			installCmd.Dir = fakeGitRepoPath
			checkCmd.Dir = fakeGitRepoPath

			install()
		})

		itCorrectlyDetectsDirtyDependency("github.com", "vito", "gocart")
	})

	Context("with a hg dependency", func() {
		BeforeEach(func() {
			installCmd.Dir = fakeHgRepoPath
			checkCmd.Dir = fakeHgRepoPath

			install()
		})

		itCorrectlyDetectsDirtyDependency("code.google.com", "p", "go.crypto", "ssh")
	})

	Context("with a bzr dependency", func() {
		BeforeEach(func() {
			installCmd.Dir = fakeBzrRepoPath
			checkCmd.Dir = fakeBzrRepoPath

			install()
		})

		itCorrectlyDetectsDirtyDependency("launchpad.net", "gocheck")
	})
})

func gitRevision(path, rev string) *cmdtest.Session {
	git := exec.Command("git", "rev-parse", rev)
	git.Dir = path

	sess, err := cmdtest.Start(git)
	Expect(err).ToNot(HaveOccurred())

	return sess
}

func bzrRevision(path string) *cmdtest.Session {
	bzr := exec.Command("bzr", "revno", "--tree")
	bzr.Dir = path

	sess, err := cmdtest.Start(bzr)
	Expect(err).ToNot(HaveOccurred())

	return sess
}

func hgRevision(path string) *cmdtest.Session {
	hg := exec.Command("hg", "id", "-i")
	hg.Dir = path

	sess, err := cmdtest.Start(hg)
	Expect(err).ToNot(HaveOccurred())

	return sess
}

func currentGitRevision(path string) string {
	sess := gitRevision(path, "HEAD")
	Expect(sess).To(ExitWith(0))

	return strings.Trim(string(sess.FullOutput()), "\n")
}

func currentBzrRevision(path string) string {
	sess := bzrRevision(path)
	Expect(sess).To(ExitWith(0))

	return strings.Trim(string(sess.FullOutput()), "\n")
}

func currentHgRevision(path string) string {
	sess := hgRevision(path)
	Expect(sess).To(ExitWith(0))

	return strings.Trim(string(sess.FullOutput()), "\n")
}

func listing(path string) *cmdtest.Session {
	sess, err := cmdtest.Start(exec.Command("ls", path))
	Expect(err).ToNot(HaveOccurred())

	return sess
}

func walkTheDinosaur(src, dest string) error {
	cp := exec.Command("cp", "-a", src, dest)
	cp.Stdout = os.Stdout
	cp.Stderr = os.Stderr
	return cp.Run()
}


text:
require 'spec_helper'

describe Api::SequencesController do
  before :each do
    request.headers["accept"] = 'application/json'
  end

  include Devise::Test::ControllerHelpers

  describe '#destroy' do
    let(:user) { FactoryGirl.create(:user) }
    let(:device) { user.device }
    let(:sequence) { FactoryGirl.create(:sequence, device: device) }

    it 'destroys a sequence' do
      sign_in user
      input = { id: sequence.id }
      delete :destroy, params: input
      expect(response.status).to eq(200)
      expect { sequence.reload }
        .to(raise_error(ActiveRecord::RecordNotFound))
    end

    it 'doesnt destroy other peoples sequence' do
      sign_in user
      other_persons = FactoryGirl.create(:sequence)
      input = { id: other_persons.id }
      delete :destroy, params: input
      expect(response.status).to eq(403)
    end

   it 'allows deletion of recurive sequences' do
     sign_in user
     s = Sequences::Create.run!({ device: user.device,
                                  name: "Rick-cursion", body: [] })
     patch :update,
           params: {id: s.id },
           body: {"sequence" => {
                  "body" => [{"kind"=>"execute",
                              "args"=>{ "sequence_id"=>s.id }}]}}.to_json,
           as: :json

     sequence.reload
     input = { id: sequence.id }
     before = Sequence.count
     delete :destroy, params: input
     after  = Sequence.count
     expect(response.status).to eq(200)
     expect(after).to be < before
     expect { s.reload }.to(raise_error(ActiveRecord::RecordNotFound))
   end

    it 'does not destroy a sequence when in use by a sequence' do
      before = SequenceDependency.count
      program = [
        {
          kind: "_if",
          args: {
            lhs:"x",
            op:"is",
            rhs:0,
            _then: {
              kind: "execute",
              args: { sequence_id: sequence.id }
            },
            _else: {
              kind: "execute",
              args: { sequence_id: sequence.id }
            },
          }
        }
      ]
      Sequences::Create.run!(name:   "Dep. tracking",
                             device: user.device,
                             body:   program)
      expect(SequenceDependency.count).to be > before
      sd = SequenceDependency.last
      newest = Sequence.last
      expect(sd.dependency).to eq(sequence)
      expect(sd.sequence).to eq(newest)

      sign_in user
      before = Sequence.count
      delete :destroy, params: { id: sequence.id }
      after = Sequence.count
      expect(response.status).to eq(422)
      expect(before).to eq(after)
      expect(json[:sequence]).to include("sequences are still relying on this sequence")
    end
  end
end


text:
from sqlalchemy import Column, Integer, String, LargeBinary, \
        Float
from sqlalchemy.orm import relationship, backref
from snailmail.database import Base
from snailmail.models import secure_pass

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key = True,nullable=False,
            autoincrement=True)
    username = Column(String, unique=True,nullable=False)
    password_key = Column(LargeBinary,nullable=False)
    password_salt = Column(LargeBinary,nullable=False)
    latitude = Column(Float)
    longitude = Column(Float)

    def __init__(self, username, password,
            latitude, longitude):
        self.username = username
        sp = secure_pass.Password(password)
        self.password_key = sp.get_hash()
        self.password_salt = sp.get_salt()
        self.latitude = latitude
        self.longitude = longitude

    def __repr__(self):
        return '<User %r, id=%d>' % (self.username,self.id)

    def serialize(self):
        return {
                'id':self.id,
                'username':self.username,
                'password_key':self.password_key,
                'password_salt':self.password_salt,
                'latitude':self.latitude,
                'longitude':self.longitude
                }

    @staticmethod
    def unserialize(indict,db_session):
        return User.query.filter(User.id==indict['id']).first()

    @staticmethod
    def get_user(username, password, db_session):
        user = User.query.filter(User.username == username).first()
        if user is None:
            raise Exception("Login incorrect")
        if secure_pass.Password.check_pass(
                password,
                user.password_key,
                user.password_salt):
            return user
        raise Exception("Login incorrect")

    @staticmethod
    def get_user_by_username(username,db_session):
        return User.query.filter(User.username == username).first()


text:
#ifndef ANDROID_VECTOR_IMPL_H
#define ANDROID_VECTOR_IMPL_H

#include <assert.h>
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>

// ---------------------------------------------------------------------------
// No user serviceable parts in here...
// ---------------------------------------------------------------------------

namespace android {

/*!
 * Implementation of the guts of the vector<> class
 * this ensures backward binary compatibility and
 * reduces code size.
 * For performance reasons, we expose mStorage and mCount
 * so these fields are set in stone.
 *
 */

class VectorImpl
{
public:
    enum { // flags passed to the ctor
        HAS_TRIVIAL_CTOR    = 0x00000001,
        HAS_TRIVIAL_DTOR    = 0x00000002,
        HAS_TRIVIAL_COPY    = 0x00000004,
    };

                            VectorImpl(size_t itemSize, uint32_t flags);
                            VectorImpl(const VectorImpl& rhs);
    virtual                 ~VectorImpl();

    /*! must be called from subclasses destructor */
            void            finish_vector();

            VectorImpl&     operator = (const VectorImpl& rhs);

    /*! C-style array access */
    inline  const void*     arrayImpl() const       { return mStorage; }
            void*           editArrayImpl();

    /*! vector stats */
    inline  size_t          size() const        { return mCount; }
    inline  bool            isEmpty() const     { return mCount == 0; }
            size_t          capacity() const;
            ssize_t         setCapacity(size_t size);

            /*! append/insert another vector or array */
            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
            ssize_t         appendVector(const VectorImpl& vector);
            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
            ssize_t         appendArray(const void* array, size_t length);

            /*! add/insert/replace items */
            ssize_t         insertAt(size_t where, size_t numItems = 1);
            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
            void            pop();
            void            push();
            void            push(const void* item);
            ssize_t         add();
            ssize_t         add(const void* item);
            ssize_t         replaceAt(size_t index);
            ssize_t         replaceAt(const void* item, size_t index);

            /*! remove items */
            ssize_t         removeItemsAt(size_t index, size_t count = 1);
            void            clear();

            const void*     itemLocation(size_t index) const;
            void*           editItemLocation(size_t index);

            typedef int (*compar_t)(const void* lhs, const void* rhs);
            typedef int (*compar_r_t)(const void* lhs, const void* rhs, void* state);
            status_t        sort(compar_t cmp);
            status_t        sort(compar_r_t cmp, void* state);

protected:
            size_t          itemSize() const;
            void            release_storage();

    virtual void            do_construct(void* storage, size_t num) const = 0;
    virtual void            do_destroy(void* storage, size_t num) const = 0;
    virtual void            do_copy(void* dest, const void* from, size_t num) const = 0;
    virtual void            do_splat(void* dest, const void* item, size_t num) const = 0;
    virtual void            do_move_forward(void* dest, const void* from, size_t num) const = 0;
    virtual void            do_move_backward(void* dest, const void* from, size_t num) const = 0;

    // take care of FBC...
    virtual void            reservedVectorImpl1();
    virtual void            reservedVectorImpl2();
    virtual void            reservedVectorImpl3();
    virtual void            reservedVectorImpl4();
    virtual void            reservedVectorImpl5();
    virtual void            reservedVectorImpl6();
    virtual void            reservedVectorImpl7();
    virtual void            reservedVectorImpl8();

private:
        void* _grow(size_t where, size_t amount);
        void  _shrink(size_t where, size_t amount);

        inline void _do_construct(void* storage, size_t num) const;
        inline void _do_destroy(void* storage, size_t num) const;
        inline void _do_copy(void* dest, const void* from, size_t num) const;
        inline void _do_splat(void* dest, const void* item, size_t num) const;
        inline void _do_move_forward(void* dest, const void* from, size_t num) const;
        inline void _do_move_backward(void* dest, const void* from, size_t num) const;

            // These 2 fields are exposed in the inlines below,
            // so they're set in stone.
            void *      mStorage;   // base address of the vector
            size_t      mCount;     // number of items

    const   uint32_t    mFlags;
    const   size_t      mItemSize;
};

class SortedVectorImpl : public VectorImpl
{
public:
                            SortedVectorImpl(size_t itemSize, uint32_t flags);
                            SortedVectorImpl(const VectorImpl& rhs);
    virtual                 ~SortedVectorImpl();

    SortedVectorImpl&     operator = (const SortedVectorImpl& rhs);

    //! finds the index of an item
            ssize_t         indexOf(const void* item) const;

    //! finds where this item should be inserted
            size_t          orderOf(const void* item) const;

    //! add an item in the right place (or replaces it if there is one)
            ssize_t         add(const void* item);

    //! merges a vector into this one
            ssize_t         merge(const VectorImpl& vector);
            ssize_t         merge(const SortedVectorImpl& vector);

    //! removes an item
            ssize_t         remove(const void* item);

protected:
    virtual int             do_compare(const void* lhs, const void* rhs) const = 0;

    // take care of FBC...
    virtual void            reservedSortedVectorImpl1();
    virtual void            reservedSortedVectorImpl2();
    virtual void            reservedSortedVectorImpl3();
    virtual void            reservedSortedVectorImpl4();
    virtual void            reservedSortedVectorImpl5();
    virtual void            reservedSortedVectorImpl6();
    virtual void            reservedSortedVectorImpl7();
    virtual void            reservedSortedVectorImpl8();

private:
            ssize_t         _indexOrderOf(const void* item, size_t* order = 0) const;

            // these are made private, because they can't be used on a SortedVector
            // (they don't have an implementation either)
            ssize_t         add();
            void            pop();
            void            push();
            void            push(const void* item);
            ssize_t         insertVectorAt(const VectorImpl& vector, size_t index);
            ssize_t         appendVector(const VectorImpl& vector);
            ssize_t         insertArrayAt(const void* array, size_t index, size_t length);
            ssize_t         appendArray(const void* array, size_t length);
            ssize_t         insertAt(size_t where, size_t numItems = 1);
            ssize_t         insertAt(const void* item, size_t where, size_t numItems = 1);
            ssize_t         replaceAt(size_t index);
            ssize_t         replaceAt(const void* item, size_t index);
};

}; // namespace android

// ---------------------------------------------------------------------------

#endif // ANDROID_VECTOR_IMPL_H


text:
if ([NSThread isMainThread]) \
block();\
else \
dispatch_async(dispatch_get_main_queue(), ^{\
block();\
});

@interface ViewController ()

@property (nonatomic, strong, readwrite) HMClient *apiClient;

@property (weak, nonatomic) IBOutlet UITextView *responseTextView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.apiClient = [[HMClient alloc] initWithConfigurator:^(HMClientConfigurator *configurator) {

        HMConfigurationManager *manager = [[HMConfigurationManager alloc] initWithPlistFileName:@"API-Config"];
        HMConfiguration *configuration = [manager configurationForEnvironment:HMEnvironmentProduction];
        [configurator configureWithConfiguration:configuration];

        configurator.cacheManagement = HMClientCacheManagementOffline;
        configurator.completionBlockQueue = dispatch_queue_create("com.mobilejazz.background-queue", DISPATCH_QUEUE_SERIAL);
        configurator.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
    }];

    self.apiClient.logLevel = HMClientLogLevelRequests;
}

- (IBAction)getFakeRequest:(id)sender
{
    HMRequest *request = [HMRequest requestWithPath:@"562158b5120000714c0113ff"];

    //NOTE: I am using Mocky.io to create a fake request with the custom header
    //          Cache-Control : max-age=30

    [_apiClient performRequest:request completionBlock:^(HMResponse *response) {
        NSString *newString;
        if (response.error) {
            newString = [NSString stringWithFormat:@"Received error:\n%@\n", [response.error localizedDescription]];
        }
        else {
            newString = [NSString stringWithFormat:@"Received response:\n%@\n", response.responseObject];
        }

        DoInForeground(^{
            _responseTextView.text = [_responseTextView.text stringByAppendingString:newString];
        });
    }];
}

@end