text:
var expect = require('chai').expect;
var starWars = require('./index');

describe('starwars-names', function(){
    describe('all', function(){
        it('should be an array of strings', function(){
            expect(starWars.all).to.satisfy(isArrayOfStrings);
            function isArrayOfStrings(array){
                return array.every(function(item){
                   return typeof item === 'string';
                });
            }
        });

        it("should contain 'Luke Skywalker", function(){
            expect(starWars.all).to.include('Luke Skywalker');
        })
    });

    describe('random', function(){
        it ("should return a random item from the starwars.all", function(){
            var randomItem = starWars.random();
            expect(starWars.all).to.include(randomItem);

        });
        it("should return an array of random items if passed a number", function(){
            var randomItems = starWars.random(3);
            expect(randomItems).to.have.length(3);
            randomItems.forEach(function(item){
                expect(starWars.all).to.include(item);
            });
        });
    });
});


text:
package com.google.android.vending.expansion.downloader.impl;

import com.android.vending.expansion.downloader.R;
import com.google.android.vending.expansion.downloader.Helpers;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;

public class V3CustomNotification implements DownloadNotification.ICustomNotification {

	CharSequence mTitle;
	CharSequence mPausedText;
	CharSequence mTicker;
	int mIcon;
	long mTotalBytes = -1;
	long mCurrentBytes = -1;
	long mTimeRemaining;
	PendingIntent mPendingIntent;
	Notification mNotification = new Notification();

	@Override
	public void setIcon(int icon) {
		mIcon = icon;
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
	}

	@Override
	public void setPausedText(CharSequence pausedText) {
		mPausedText = pausedText;
	}

	@Override
	public void setTotalBytes(long totalBytes) {
		mTotalBytes = totalBytes;
	}

	@Override
	public void setCurrentBytes(long currentBytes) {
		mCurrentBytes = currentBytes;
	}

	@Override
	public Notification updateNotification(Context c) {
        Notification n = mNotification;

        boolean hasPausedText = (mPausedText != null);
        n.icon = mIcon;

        n.flags |= Notification.FLAG_ONGOING_EVENT;

        // Build the RemoteView object
        RemoteViews expandedView = new RemoteViews(
        		c.getPackageName(),
                R.layout.status_bar_ongoing_event_progress_bar);

        if (hasPausedText) {
            expandedView.setViewVisibility(R.id.progress_bar_frame, View.GONE);
            expandedView.setViewVisibility(R.id.description, View.GONE);
            expandedView.setTextViewText(R.id.paused_text, mPausedText);
            expandedView.setViewVisibility(R.id.time_remaining, View.GONE);
        } else {
            expandedView.setTextViewText(R.id.title, mTitle);
            // look at strings
            expandedView.setViewVisibility(R.id.description, View.VISIBLE);
			expandedView.setTextViewText(R.id.description, Helpers.getDownloadProgressString(mCurrentBytes, mTotalBytes));
            expandedView.setViewVisibility(R.id.progress_bar_frame, View.VISIBLE);
            expandedView.setViewVisibility(R.id.paused_text, View.GONE);
            expandedView.setProgressBar(R.id.progress_bar,
            		(int)(mTotalBytes>>8),
                    (int)(mCurrentBytes>>8),
                    mTotalBytes <= 0);
            expandedView.setViewVisibility(R.id.time_remaining, View.VISIBLE);
            expandedView.setTextViewText(R.id.time_remaining, c.getString(R.string.time_remaining_notification, Helpers.getTimeRemaining(mTimeRemaining)));
        }
        expandedView.setTextViewText(R.id.progress_text,
                Helpers.getDownloadProgressPercent(mCurrentBytes, mTotalBytes));
        expandedView.setImageViewResource(R.id.appIcon, mIcon);
        n.contentView = expandedView;
        n.contentIntent = mPendingIntent;
        return n;
	}

    @Override
    public void setPendingIntent(PendingIntent contentIntent) {
        mPendingIntent = contentIntent;
    }

    @Override
    public void setTicker(CharSequence ticker) {
        mTicker = ticker;
    }

    @Override
    public void setTimeRemaining(long timeRemaining) {
        mTimeRemaining = timeRemaining;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Entity;

use Core\Entity\Entity;

class ReportEntity Extends Entity {
    /**
     * Report id.
     *
     * @var integer
     */
    protected $reportId;

    /**
     * Comment id
     *
     * @var integer
     */
    protected $commentID;

    /**
     * id of the author's comment.
     *
     * @var string
     */
    protected $comAuthorID;

        /**
     * id of the reporter.
     *
     * @var string
     */
    protected $reportByID;

	/**
     * date of the Report.
     *
     * @var dateTime
     */
    protected $reportDate;

	// GETTERS

    public function getReportId() {
        return $this->reportId;
    }

    public function getCommentID() {
        return $this->commentID;
    }

	public function getComAuthorID() {
        return $this->comAuthorID;
    }

    public function getReportByID() {
        return $this->reportByID;
    }

	public function getReportDate(){
		return $this->reportDate;
	}

	// SETTERS

    public function setReportId($id) {
        $this->reportId = $id;
        return $this;
    }

    public function setCommentId($id) {
        $this->commentID = $id;
        return $this;
    }

    public function setComAuthorID($id) {
        $this->comAuthorID = $id;
        return $this;
    }

    public function setReportByID($id) {
        $this->reportByID = $id;
        return $this;
    }

}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Server" type="#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory" factoryName="Local" APPLICATION_SERVER_NAME="Tomcat 7" ALTERNATIVE_JRE_ENABLED="false" ALTERNATIVE_JRE_PATH="">
    <option name="OPEN_IN_BROWSER" value="false" />
    <option name="OPEN_IN_BROWSER_URL" value="http://localhost:8080/bs" />
    <option name="COMMON_VM_ARGUMENTS" value="-ea -Xmx384m -XX:MaxPermSize=200m -Ddebug=true -server -XX:+HeapDumpOnOutOfMemoryError -Djava.awt.headless -DTC.res.disableAll=true -Dteamcity.development.mode=true -Dteamcity.development.shadowCopyClasses=true -Dteamcity.data.path=$TeamCityDistribution$/../PluginDev.Data -Dteamcity_logs=$TeamCityDistribution$/logs -Dlog4j.configuration=file:$TeamCityDistribution$/conf/teamcity-server-log4j.xml" />
    <option name="UPDATING_POLICY" value="redeploy-artifacts" />
    <deployment>
      <file path="$TeamCityDistribution$/webapps/ROOT">
        <settings>
          <option name="CONTEXT_PATH" value="/bs" />
        </settings>
      </file>
    </deployment>
    <server-settings>
      <option name="BASE_DIRECTORY_NAME" value="Unnamed__NETPackagesSupport_2" />
    </server-settings>
    <predefined_log_file id="TOMCAT_LOCALHOST_LOG_ID" enabled="true" />
    <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
    <RunnerSettings RunnerId="Cover" />
    <RunnerSettings RunnerId="Debug">
      <option name="DEBUG_PORT" value="60644" />
      <option name="TRANSPORT" value="0" />
      <option name="LOCAL" value="true" />
    </RunnerSettings>
    <RunnerSettings RunnerId="Profile ">
      <option name="myExternalizedOptions" value="
additional-options2=onexit\=snapshot
" />
    </RunnerSettings>
    <RunnerSettings RunnerId="Run" />
    <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Cover">
      <option name="USE_ENV_VARIABLES" value="true" />
      <STARTUP>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </STARTUP>
      <SHUTDOWN>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </SHUTDOWN>
    </ConfigurationWrapper>
    <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Debug">
      <option name="USE_ENV_VARIABLES" value="true" />
      <STARTUP>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </STARTUP>
      <SHUTDOWN>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </SHUTDOWN>
    </ConfigurationWrapper>
    <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Profile ">
      <option name="USE_ENV_VARIABLES" value="true" />
      <STARTUP>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </STARTUP>
      <SHUTDOWN>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </SHUTDOWN>
    </ConfigurationWrapper>
    <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Run">
      <option name="USE_ENV_VARIABLES" value="true" />
      <STARTUP>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </STARTUP>
      <SHUTDOWN>
        <option name="USE_DEFAULT" value="true" />
        <option name="SCRIPT" value="" />
        <option name="VM_PARAMETERS" value="" />
        <option name="PROGRAM_PARAMETERS" value="" />
      </SHUTDOWN>
    </ConfigurationWrapper>
    <method>
      <option name="BuildArtifacts" enabled="true">
        <artifact name="deploy" />
      </option>
    </method>
  </configuration>
</component>


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S15.4.4.7_A6.1;
* @section: 15.4.4.7, 15.2.4.7, 12.6.4;
* @assertion: The length property of push has the attribute DontEnum;
* @description: Checking use propertyIsEnumerable, for-in;
*/

//CHECK#1
if (Array.prototype.push.propertyIsEnumerable('length') !== false) {
  $ERROR('#1: Array.prototype.push.propertyIsEnumerable(\'length\') === false. Actual: ' + (Array.prototype.push.propertyIsEnumerable('length')));
}

//CHECK#2
result = true;
for (p in Array.prototype.push){
  if (p === "length") {
    result = false;
  }
}

if (result !== true) {
  $ERROR('#2: result = true; for (p in Array.push) { if (p === "length") result = false; }  result === true;');
}


text:
class Project < ActiveRecord::Base
  include DateTimeConverter
  include IndexCheck

  has_many :tasks
  has_many :notes
  has_many :tags, through: :tasks
  has_many :comments, through: :tasks
  enum status: [:active, :complete]

  has_many :user_projects, foreign_key: "collaboration_project_id"
  has_many :collaborators, through: :user_projects
  belongs_to :owner, class_name: "User"

  scope :complete, -> { where(status: 1) }
  scope :active, -> { where(status: 0)}
  scope :overdue, -> { where("due_date < ? AND status = ?", Date.today, 0)}

  validates :name, :description, :due_date, :status, presence: true

  def collaborator_emails=(emails)
    email_array = emails.split(",").map{|email| email.strip}
    email_array.each do |email|
      collaborator = User.find_by(email: email)
      if collaborator == nil || collaborator == self.owner || self.collaborators.include?(collaborator)
        next
      end
      self.collaborators << collaborator
      self.save
    end
  end

  def collaborator_emails
    emails = self.collaborators.collect {|collaborator| collaborator.email}
    emails.join(", ")
  end

  def active_tasks
    self.tasks.active
  end

  def complete_tasks
    self.tasks.complete
  end

  def overdue_tasks
    self.tasks.overdue
  end

  def tasks_complete?
    tasks.any? { |task| task.status == "active"} ? false : true
  end

end


text:
start-dev: node_modules
	@./node_modules/.bin/nodemon --delay 500ms

# Install dependencies from npm.
node_modules: package.json
	@npm install

# Clean non-checked-in files.
clean:
	@rm -rf node_modules

# Phony targets.
.PHONY: clean


text: package mongostore


text:
module ShouldCompile where

flatten :: Int		-- Indentation
        -> Bool		-- True => just had a newline
        -> Float	-- Current seq to flatten
        -> [(Int,Float)]-- Work list with indentation
        -> String

flatten n nlp 0.0 seqs = flattenS nlp seqs
flatten n nlp 1.0 seqs = flatten n nlp 1.1 ((n,1.2) : seqs)

flattenS :: Bool -> [(Int, Float)] -> String
flattenS nlp [] = ""
flattenS nlp ((col,seq):seqs) = flatten col nlp seq seqs


text:
<?php
namespace Bee\Security;

use ReflectionClass;

/**
 * Interface IRunAsManager
 * @package Bee\Security
 */
interface IRunAsManager {
    //~ Methods ========================================================================================================

    /**
     * Returns a replacement Authentication object for the current secure object invocation, or
     * null if replacement not required.
     *
     * @param IAuthentication $authentication the caller invoking the secure object
     * @param mixed $object the secured object being called
     * @param ConfigAttributeDefinition $config the configuration attributes associated with the secure object being invoked
     *
     * @return IAuthentication a replacement object to be used for duration of the secure object invocation, or null if
     *         the Authentication should be left as is
     */
    function buildRunAs(IAuthentication $authentication, $object, ConfigAttributeDefinition $config);

    /**
     * Indicates whether this RunAsManager is able to process the passed
     * ConfigAttribute.
This allows the AbstractSecurityInterceptor to check every
     * configuration attribute can be consumed by the configured AccessDecisionManager and/or
     * RunAsManager and/or AfterInvocationManager.

     *
     * @param ConfigAttribute $attribute a configuration attribute that has been configured against the
     *        AbstractSecurityInterceptor
     *
     * @return boolean true if this RunAsManager can support the passed configuration attribute
     */
    function supports(ConfigAttribute $attribute);

    /**
     * Indicates whether the RunAsManager implementation is able to provide run-as replacement for
     * the indicated secure object type.
     *
     * @param ReflectionClass|string $classOrClassName the class that is being queried
     *
     * @return boolean true if the implementation can process the indicated class
     */
    function supportsClass($classOrClassName);

}


text:
package arn

import (
	"errors"
	"fmt"
	"sort"

	"github.com/aerogo/nano"
)

// CharacterID represents a character ID.
type CharacterID = ID

// Character represents an anime or manga character.
type Character struct {
	Name        CharacterName         `json:"name" editable:"true"`
	Image       Image                 `json:"image"`
	MainQuoteID QuoteID               `json:"mainQuoteId" editable:"true"`
	Description string                `json:"description" editable:"true" type:"textarea"`
	Spoilers    []Spoiler             `json:"spoilers" editable:"true"`
	Attributes  []*CharacterAttribute `json:"attributes" editable:"true"`

	hasID
	hasPosts
	hasMappings
	hasCreator
	hasEditor
	hasLikes
	hasDraft
}

// NewCharacter creates a new character.
func NewCharacter() *Character {
	return &Character{
		hasID: hasID{
			ID: GenerateID("Character"),
		},
		hasCreator: hasCreator{
			Created: DateTimeUTC(),
		},
	}
}

// Link ...
func (character *Character) Link() string {
	return "/character/" + character.ID
}

// TitleByUser returns the preferred title for the given user.
func (character *Character) TitleByUser(user *User) string {
	return character.Name.ByUser(user)
}

// String returns the canonical name of the character.
func (character *Character) String() string {
	return character.Name.Canonical
}

// TypeName returns the type name.
func (character *Character) TypeName() string {
	return "Character"
}

// Self returns the object itself.
func (character *Character) Self() Loggable {
	return character
}

// MainQuote ...
func (character *Character) MainQuote() *Quote {
	quote, _ := GetQuote(character.MainQuoteID)
	return quote
}

// AverageColor returns the average color of the image.
func (character *Character) AverageColor() string {
	color := character.Image.AverageColor

	if color.Hue == 0 && color.Saturation == 0 && color.Lightness == 0 {
		return ""
	}

	return color.String()
}

// ImageLink ...
func (character *Character) ImageLink(size string) string {
	extension := ".jpg"

	if size == "original" {
		extension = character.Image.Extension
	}

	return fmt.Sprintf("//%s/images/characters/%s/%s%s?%v", MediaHost, size, character.ID, extension, character.Image.LastModified)
}

// Publish publishes the character draft.
func (character *Character) Publish() error {
	// No name
	if character.Name.Canonical == "" {
		return errors.New("No canonical character name")
	}

	// No image
	if !character.HasImage() {
		return errors.New("No character image")
	}

	return publish(character)
}

// Unpublish turns the character into a draft.
func (character *Character) Unpublish() error {
	return unpublish(character)
}

// Anime returns a list of all anime the character appears in.
func (character *Character) Anime() []*Anime {
	var results []*Anime

	for animeCharacters := range StreamAnimeCharacters() {
		if animeCharacters.Contains(character.ID) {
			anime, err := GetAnime(animeCharacters.AnimeID)

			if err != nil {
				continue
			}

			results = append(results, anime)
		}
	}

	return results
}

// GetCharacter ...
func GetCharacter(id CharacterID) (*Character, error) {
	obj, err := DB.Get("Character", id)

	if err != nil {
		return nil, err
	}

	return obj.(*Character), nil
}

// Merge deletes the character and moves all existing references to the new character.
func (character *Character) Merge(target *Character) {
	// Check anime characters
	for list := range StreamAnimeCharacters() {
		for _, animeCharacter := range list.Items {
			if animeCharacter.CharacterID == character.ID {
				animeCharacter.CharacterID = target.ID
				list.Save()
				break
			}
		}
	}

	// Check quotes
	for quote := range StreamQuotes() {
		if quote.CharacterID == character.ID {
			quote.CharacterID = target.ID
			quote.Save()
		}
	}

	// Check log
	for entry := range StreamEditLogEntries() {
		if entry.ObjectType != "Character" {
			continue
		}

		if entry.ObjectID == character.ID {
			// Delete log entries for the old character
			DB.Delete("EditLogEntry", entry.ID)
		}
	}

	// Merge likes
	for _, userID := range character.Likes {
		if !Contains(target.Likes, userID) {
			target.Likes = append(target.Likes, userID)
		}
	}

	target.Save()

	// Delete image files
	character.DeleteImages()

	// Delete character
	DB.Delete("Character", character.ID)
}

// DeleteImages deletes all images for the character.
func (character *Character) DeleteImages() {
	deleteImages("characters", character.ID, character.Image.Extension)
}

// Quotes returns the list of quotes for this character.
func (character *Character) Quotes() []*Quote {
	return FilterQuotes(func(quote *Quote) bool {
		return !quote.IsDraft && quote.CharacterID == character.ID
	})
}

// SortCharactersByLikes sorts the given slice of characters by the amount of likes.
func SortCharactersByLikes(characters []*Character) {
	sort.Slice(characters, func(i, j int) bool {
		aLikes := len(characters[i].Likes)
		bLikes := len(characters[j].Likes)

		if aLikes == bLikes {
			return characters[i].Name.Canonical < characters[j].Name.Canonical
		}

		return aLikes > bLikes
	})
}

// StreamCharacters returns a stream of all characters.
func StreamCharacters() <-chan *Character {
	channel := make(chan *Character, nano.ChannelBufferSize)

	go func() {
		for obj := range DB.All("Character") {
			channel <- obj.(*Character)
		}

		close(channel)
	}()

	return channel
}

// FilterCharacters filters all characters by a custom function.
func FilterCharacters(filter func(*Character) bool) []*Character {
	var filtered []*Character

	channel := DB.All("Character")

	for obj := range channel {
		realObject := obj.(*Character)

		if filter(realObject) {
			filtered = append(filtered, realObject)
		}
	}

	return filtered
}

// AllCharacters returns a slice of all characters.
func AllCharacters() []*Character {
	all := make([]*Character, 0, DB.Collection("Character").Count())

	stream := StreamCharacters()

	for obj := range stream {
		all = append(all, obj)
	}

	return all
}


text:
package disparity.rpg.items.armor;

import disparity.rpg.items.Armor;
import disparity.rpg.items.Quality;

public class Leggings extends Armor{

	/**
	 * Leggings constructor
	 *
	 * Leggings have a base AC bonus of 2
	 */
	public Leggings(Quality quality){
		super("Leggings", quality, 2);
	}

	/**
	 * Empty Constructor for reading
	 * Beings from JSON files
	 */
	public Leggings() {
	}
}


text:
#include "mqsProvider/ListClient.h"
#include "mqsProvider/MessageQueueServiceClient.h"
#include "mqsProvider/MessageQueueClient.h"
#include "mqsProvider/MessageQueueServiceHeader.h"
#include "mqsProvider/MutualExclusionClient.h"
#include "mqsProvider/Controller.h"

#include <appUtil/JJJException.h>
#include <appUtil/Shortcuts.h>
#include <string>

#if defined(_MSC_VER)
#	include <windows.h>
#	define CONTROLLER_SLEEP(DELAY)	Sleep(DELAY)
#else
#	if defined(GCC) || defined(XLC) || defined(__GNUC__)
#		include<unistd.h>
#		define CONTROLLER_SLEEP(DELAY)	usleep(DELAY*1000)
#	endif
#endif

namespace mqsProvider
{
	Controller::Controller(
			MessageQueueServiceClient* a_messageQueueServiceClient,
			MutualExclusionClient* a_mutexClient )
	{
		m_messageQueueServiceClient	= a_messageQueueServiceClient;
		m_mutexClient				= a_mutexClient;
		appUtil::assertPointer( m_messageQueueServiceClient );
		appUtil::assertPointer( m_mutexClient );
	}
	Controller::~Controller(void)
	{
		VOID_RETURN_IF_NULL( m_mutexClient );
		VOID_RETURN_IF_NULL( m_messageQueueServiceClient );
		m_mutexClient->close();
		m_messageQueueServiceClient->close();
	}
	bool Controller::open(void)
	{
		appUtil::assertPointer( m_messageQueueServiceClient );
		appUtil::assertPointer( m_mutexClient);
		appUtil::assert( m_mutexClient->open(),"Controller::open: Error opening Mutex" );

		MutualExclusionClient::ENTER_CRITICAL_AREA_STATUS l_enterStatus =
				m_mutexClient->enterCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);
		appUtil::assert(
				l_enterStatus == MutualExclusionClient::ENTER_SUCCESS,
				"Controller::open: Could not enter in critical area" );

		bool l_mqscliRet =
				m_messageQueueServiceClient->open();

		m_mutexClient->exitCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);
		appUtil::assert(
				l_mqscliRet,
				"Controller::open: Error opening MessageQueueServiceClient" );

		return true;
	}
	void Controller::close(void)
	{
		m_mutexClient->close();
		m_messageQueueServiceClient->close();
	}

	bool Controller::createMessageQueue(
			const char* a_msgqName,
			unsigned int a_countLimit,
			unsigned int a_timeToLive ) const
	{
		appUtil::assertPointer( m_messageQueueServiceClient );
		appUtil::assertPointer( m_mutexClient);
		MutualExclusionClient::ENTER_CRITICAL_AREA_STATUS l_enterStatus =
				m_mutexClient->enterCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);
		appUtil::assert(
				l_enterStatus == MutualExclusionClient::ENTER_SUCCESS,
				"Controller::open: Could not enter in critical area" );

		bool l_created =
				m_messageQueueServiceClient->createMessageQueue(
						a_msgqName,
						a_countLimit,
						a_timeToLive );
		MessageQueueClient l_mqCli;
		bool l_found =
				m_messageQueueServiceClient->findMessageQueue(
						a_msgqName,
						&l_mqCli );
		if( l_created && l_found ){
			unsigned int l_semNum =
					l_mqCli.semaphoreNumber();
			m_mutexClient->setMutex( l_semNum, true );
		}

		m_mutexClient->exitCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);

		return l_created;
	}
	bool Controller::destroyMessageQueue( const char* a_msgqName ) const
	{

		appUtil::assertPointer( m_messageQueueServiceClient );
		appUtil::assertPointer( m_mutexClient );

		MutualExclusionClient::ENTER_CRITICAL_AREA_STATUS l_enterStatus =
				MutualExclusionClient::ENTER_SUCCESS;
		l_enterStatus = m_mutexClient->enterCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);
		RETURN_IF( l_enterStatus != MutualExclusionClient::ENTER_SUCCESS, false );

		MessageQueueClient l_mqCli;
		bool l_found = m_messageQueueServiceClient->findMessageQueue(
				a_msgqName, &l_mqCli );
		m_mutexClient->exitCriticalArea(GLOBAL_LISTS_SEMAPHORE_NUMBER);
		RETURN_IF( !l_found, false );

		//FECHA A PORTA DE ENTRADA DA MESSAGE QUEUE
		bool l_ret = enableMessageQueueInput(
				&l_mqCli,
				false );
		//CERTIFICA QUE A PORTA DE SAIDA ESTA ABERTA
		l_ret = enableMessageQueueOutput(
				&l_mqCli,
				true );

		//ESPERA A MESSAGE QUEUE SER CONSUMIDA
		unsigned int l_timeout		=
				m_messageQueueServiceClient->mqsHeader()->parameters.destroyMessageQueueWaitSeconds;
		unsigned int l_msecsTimeout = l_timeout * 1000;
		const unsigned int l_poll	= 12;
		unsigned int l_countMsg = 0;
		for(unsigned int l_countTries = 0;l_countTries < l_poll; ++l_countTries)
		{
			l_countMsg = countMessages( &l_mqCli );
			BREAK_IF( l_countMsg == 0 );
			CONTROLLER_SLEEP( l_msecsTimeout / l_poll );
		}

		//DEVOLVE OS RECURSOS DA MESSAGEQUEUE
		l_enterStatus = MutualExclusionClient::ENTER_SUCCESS;

		unsigned short l_mqSemNum = l_mqCli.semaphoreNumber();

		l_enterStatus = m_mutexClient->enterCriticalArea(l_mqSemNum);
		RETURN_IF( l_enterStatus != MutualExclusionClient::ENTER_SUCCESS, false );

		if( l_countMsg > 0 ){
			this->emptyMessageQueue( &l_mqCli );
		}

		l_ret = m_messageQueueServiceClient->destroyMessageQueue(
				a_msgqName );

		m_mutexClient->exitCriticalArea(l_mqSemNum);

		return l_ret;
	}
	void Controller::emptyMessageQueue(
			MessageQueueClient* a_mqClient) const
	{
		std::string l_dropped;
		date_t l_messageDate;

		//const char* l_path = m_messageQueueServiceClient->mqsHeader()->parameters.droppedMessagesFilePath;
		while( a_mqClient->receiveMessage(
				"",
				l_dropped,
				l_messageDate ) ){
		}
	}

	bool Controller::enableMessageQueueInput(
			MessageQueueClient* a_mqClient,
			bool a_enable) const
	{
		MutualExclusionClient::ENTER_CRITICAL_AREA_STATUS l_enterStatus =
				MutualExclusionClient::ENTER_SUCCESS;

		unsigned short l_mqSemNum = a_mqClient->semaphoreNumber();

		l_enterStatus = m_mutexClient->enterCriticalArea(l_mqSemNum);
		RETURN_IF( l_enterStatus != MutualExclusionClient::ENTER_SUCCESS, false );

		a_mqClient->enableInput( a_enable );

		m_mutexClient->exitCriticalArea(l_mqSemNum);

		return true;
	}

	bool Controller::enableMessageQueueOutput(
			MessageQueueClient* a_mqClient,
			bool a_enable) const
	{
		MutualExclusionClient::ENTER_CRITICAL_AREA_STATUS l_enterStatus =
				MutualExclusionClient::ENTER_SUCCESS;

		unsigned short l_mqSemNum = a_mqClient->semaphoreNumber();

		l_enterStatus = m_mutexClient->enterCriticalArea(l_mqSemNum);
		RETURN_IF( l_enterStatus != MutualExclusionClient::ENTER_SUCCESS, false );

		a_mqClient->enableOutput( a_enable );

		m_mutexClient->exitCriticalArea(l_mqSemNum);

		return true;
	}

	unsigned int Controller::countMessages(
			MessageQueueClient* a_mqClient) const
	{
		unsigned int l_pendingMessages = a_mqClient->countMessages();

		return l_pendingMessages;
	}
}//namespace mqsProvider


text:
package voltkv;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class PayloadProcessor
{
    public static class Pair
    {
        public final String Key;
        private final byte[] RawValue;
        private final byte[] StoreValue;
        protected Pair(String key, byte[] rawValue, byte[] storeValue)
        {
            this.Key = key;
            this.RawValue = rawValue;
            this.StoreValue = storeValue;
        }
        public long getStoreValueLength()
        {
            if (this.StoreValue == null)
                return this.RawValue.length;
            return this.StoreValue.length;
        }
        public long getRawValueLength()
        {
            return this.RawValue.length;
        }
        public byte[] getStoreValue()
        {
            if (this.StoreValue == null)
                return this.RawValue;
            return this.StoreValue;
        }
        public byte[] getRawValue()
        {
            return this.RawValue;
        }
    }

    private final int KeySize;
    private final int MinValueSize;
    private final int MaxValueSize;
    private final int PoolSize;
    private final boolean UseCompression;
    public final String KeyFormat;
    private final int Entropy;
    private final Random Rand = new Random(0);

    /*
     * Volt deals with 2 megs at the most so 4 megabytes of entropy is plenty
     */
    private final ByteBuffer entropyBytesGlobal = ByteBuffer.allocate (1024 * 1024 * 4);

    /*
     * Create a thread local copy of the buffer because multiple threads will be manipulating the position pointers.
     * Give each thread it's own wrapper around the global byte buffer.
     */
    private final ThreadLocal<ByteBuffer> entropyBytes =
        new ThreadLocal <ByteBuffer> () {
            @Override protected ByteBuffer initialValue() {
                return entropyBytesGlobal.duplicate();
        }
    };

    public PayloadProcessor(
            int keySize,
            int minValueSize,
            int maxValueSize,
            int entropy,
            int poolSize,
            boolean useCompression)
    {
        this.KeySize = keySize;
        this.MinValueSize = minValueSize;
        this.MaxValueSize = maxValueSize;
        this.PoolSize = poolSize;
        this.UseCompression = useCompression;
        this.Entropy = entropy;
        if (entropy < 1 || entropy > 127) {
            throw new IllegalArgumentException("Entropy must be a number between 1 and 127");
        }
        while (entropyBytes.get().hasRemaining()) {
            entropyBytes.get().put((byte)(Rand.nextInt(127) % Entropy));
        }
        // Get the base key format string used to generate keys
        this.KeyFormat = "K%1$" + String.valueOf(this.KeySize-1) + "s";
    }

    public Pair generateForStore()
    {
        final String key = String.format(this.KeyFormat, this.Rand.nextInt(this.PoolSize));
        final byte[] rawValue = new byte[this.MinValueSize+this.Rand.nextInt(this.MaxValueSize-this.MinValueSize+1)];
        if (entropyBytes.get().remaining() > rawValue.length){
            entropyBytes.get().get(rawValue);
        } else {
            entropyBytes.get().position(0);
            entropyBytes.get().get(rawValue);
        }
        if (this.UseCompression)
            return new Pair(key, rawValue, gzip(rawValue));
        else
            return new Pair(key, rawValue, null);
    }

    public String [] generateAdjecentKeys( int count)
    {
        if (count < 0) return new String [0];

        String [] keys = new String[count];

        int start = this.Rand.nextInt(this.PoolSize);

        for (int i = 0; i < count; ++i) {
            int keyNo = (start + i) % this.PoolSize;
            keys[i] =  String.format(this.KeyFormat, keyNo);
        }
        return keys;
    }

    synchronized public String generateRandomKeyForRetrieval()
    {
        return String.format(this.KeyFormat, this.Rand.nextInt(this.PoolSize));
    }

    public Pair retrieveFromStore(String key, byte[] storeValue)
    {
        if (this.UseCompression)
            return new Pair(key, gunzip(storeValue), storeValue);
        else
            return new Pair(key, storeValue, null);
    }

    private static byte[] gzip(byte[] bytes)
    {
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(bytes.length * 0.7));
            GZIPOutputStream gzos = new GZIPOutputStream(baos);
            gzos.write(bytes);
            gzos.close();
            return baos.toByteArray();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private static byte[] gunzip(byte bytes[])
    {
        // Check to see if it's gzip-compressed
        // GZIP Magic Two-Byte Number: 0x8b1f (35615)
        if( (bytes != null) && (bytes.length >= 4) )
        {

            int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
            if( GZIPInputStream.GZIP_MAGIC == head )
            {
                ByteArrayInputStream  bais = null;
                GZIPInputStream gzis = null;
                ByteArrayOutputStream baos = null;
                byte[] buffer = new byte[2048];
                int    length = 0;

                try
                {
                    baos = new ByteArrayOutputStream();
                    bais = new ByteArrayInputStream( bytes );
                    gzis = new GZIPInputStream( bais );

                    while( ( length = gzis.read( buffer ) ) >= 0 )
                        baos.write(buffer,0,length);

                    // No error? Get new bytes.
                    bytes = baos.toByteArray();

                }   // end try
                catch( java.io.IOException e )
                {
                    e.printStackTrace();
                    // Just return originally-decoded bytes
                }   // end catch
                finally
                {
                    try{ baos.close(); } catch( Exception e ){}
                    try{ gzis.close(); } catch( Exception e ){}
                    try{ bais.close(); } catch( Exception e ){}
                }   // end finally

            }   // end if: gzipped
        }   // end if: bytes.length >= 2
        return bytes;
    }
}


text:
import base64
import hashlib
from hashlib import sha1
import hmac
import sys
import time
try:
  from urllib.parse import urlparse
except ImportError:
  from urlparse import urlparse
from requests.auth import AuthBase

from .constant import Constant

class Signer(AuthBase):
  """The signer class used to sign the request."""

  def __init__(self, app_key, app_secret):
    self._app_key = str(app_key)
    self._app_secret = str(app_secret)

  def __call__(self, request):
    path = urlparse(request.url).path
    if not request.body:
      request.body = ""
    timestamp = request.headers.get(Constant.TIMESTAMP, str(int(time.time())))
    if sys.version_info > (3, 0):
      content_md5 = request.headers.get(
          Constant.CONTENT_MD5,
          hashlib.md5(request.body.encode("utf-8")).hexdigest())
    else:
      content_md5 = request.headers.get(Constant.CONTENT_MD5,
                                        hashlib.md5(request.body).hexdigest())

    request.headers[Constant.TIMESTAMP] = timestamp
    request.headers[Constant.CONTENT_MD5] = content_md5
    request.headers[
        Constant.
        AUTHORIZATION] = Constant.AUTHORIZATION_PREFIX + self._sign_to_base64(
            path, timestamp, content_md5, self._app_secret)
    request.headers[Constant.SECRET_KEY_ID] = self._app_key
    return request

  def _sign(self, path, timestamp, content_md5, app_secret):
    """Sign the specified http request."""

    string_to_sign = "{}\n{}\n{}\n".format(path, timestamp, content_md5)
    if sys.version_info > (3, 0):
      digest = hmac.new(
          app_secret.encode("utf-8"),
          string_to_sign.encode("utf-8"),
          digestmod=sha1)
    else:
      digest = hmac.new(app_secret, string_to_sign, digestmod=sha1)
    return digest.digest()

  def _sign_to_base64(self, path, timestamp, content_md5, app_secret):
    """Sign the specified request to base64 encoded result."""

    signature = self._sign(path, timestamp, content_md5, app_secret)
    if sys.version_info > (3, 0):
      return base64.encodestring(signature).strip().decode("utf-8")
    else:
      return base64.encodestring(signature).strip()

  def _get_header_value(self, http_headers, name):
    if http_headers is not None and name in http_headers:
      value = http_headers[name]
      if type(value) is list:
        return http_headers[name][0]
      else:
        return value
    return ""


text:
import React, {Component, PropTypes} from 'react';

export default class Ammo extends Component {
  render() {
    return (

{(`0${Math.floor(this.props.count/10)}`).slice(-2)}

    );
  }
};

Ammo.propTypes = {
    count: PropTypes.number.isRequired
};

Ammo.contextTypes = {
  scale: PropTypes.number
};


text:
package com.whp.moonphases.activities;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import com.whp.android.BasicApplication;
import com.whp.android.BasicFragmentActivity;
import com.whp.android.ImageManager;
import com.whp.android.Log;
import com.whp.android.SharedPreferencesDao;
import com.whp.android.SimpleGestureFilter;
import com.whp.android.location.BasicLocator.Hemisphere;

import com.whp.moonphases.R;

import com.whp.moonphases.calculator.MoonCalculator;
import com.whp.moonphases.calculator.MoonPhase;

import android.os.Build;
import android.os.Bundle;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.renderscript.ProgramFragmentFixedFunction.Builder.Format;
import android.support.v4.app.DialogFragment;

import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.DatePicker;

import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends BasicFragmentActivity implements SimpleGestureFilter.SimpleGestureListener {

	private SimpleGestureFilter detector;

	private static final String TAG = MainActivity.class.getCanonicalName();

	private DialogFragment datePickerFragment = null;
	private DialogFragment infoFragment = null;
	private DialogFragment aboutFragment = null;
	private DialogFragment locationFragment = null;

	private Typeface tf	= null;

	private static final float MAX_IMAGES_QTY_FLT	= 23.0f;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		if (Build.VERSION.SDK_INT < 11) {
			tf = Typeface.createFromAsset(getAssets(),
		            "fonts/Roboto-Light.ttf");

		}

		detector = new SimpleGestureFilter(this,this);

		updateMoonPhase();
	}
/*
	@Override
	protected void onPause() {
	    if (datePickerFragment != null && datePickerFragment.isVisible())
	    	datePickerFragment.dismiss();
	    if (infoFragment != null && infoFragment.isVisible())
	    	infoFragment.dismiss();
	    if (aboutFragment != null && aboutFragment.isVisible())
	    	aboutFragment.dismiss();
	    super.onPause();
	}
	*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void updateMoonPhase() {

		SharedPreferencesDao dao	= new SharedPreferencesDao(BasicApplication.getAppContext());
		String dateString	= dao.get("moon_phase_date");
		String hemisphereString	= dao.get("moon_phase_hemisphere");
		if (hemisphereString.equals("")) hemisphereString = "NORTH";

		Calendar	date	= Calendar.getInstance();
		if ((dateString != null) && (dateString != "")) {
			date.setTimeInMillis(Long.parseLong(dateString));
		}
		Log.d(TAG,String.valueOf( date.getTimeInMillis() ));

		double normalizedPhase	= MoonCalculator.getPhase(date);
		int phase = (int) (normalizedPhase * 8.0);
		MoonPhase	moonPhase	= MoonPhase.fromInt(phase);

		ImageView	imgMoonPhase	;
		imgMoonPhase	= (ImageView) findViewById(R.id.imgMoonPhase);
		Resources r	= getResources();
		String[] imageArray	= r.getStringArray(R.array.moon_phases_image_list);
		float angle = ("NORTH".equals(hemisphereString))?0.0f:180f;
		try {
			int imageId = (int) (normalizedPhase * MAX_IMAGES_QTY_FLT);
			ImageManager.showImage(imgMoonPhase, imageArray[imageId], angle);
		} catch (IOException e) {
			Log.d(TAG,"run IOException" + e.getMessage());
		}

		//TextView moonPhaseDays = (TextView) findViewById(R.id.txtMoonPhaseDays);
		//int moonDays	= (int) (normalizedPhase * MoonCalculator.MOON_PHASE_LENGTH);
		//moonPhaseDays.setText(String.valueOf(moonDays));

		String[] nameArray	= r.getStringArray(R.array.moon_phases_name_list);
		TextView moonPhaseName = (TextView) findViewById(R.id.txtMoonPhaseName);

		int moonDays	= (int) (normalizedPhase * MoonCalculator.MOON_PHASE_LENGTH);

		moonPhaseName.setText(nameArray[moonPhase.getValue()] + " (" + String.valueOf(moonDays) + ")");
		if (tf != null) moonPhaseName.setTypeface(tf);

//		SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
//		String formattedDate = df.format(date.getTime());

		DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
		String formattedDate = dateFormat.format(date.getTime());

		TextView moonPhaseDate = (TextView) findViewById(R.id.txtMoonPhaseDate);
		moonPhaseDate.setText(formattedDate);
		if (tf != null) moonPhaseDate.setTypeface(tf);

		String[] hemispheres = r.getStringArray(R.array.hemispheres);
		TextView moonPhaseHemisphere = (TextView) findViewById(R.id.txtMoonPhaseHemisphere);
		moonPhaseHemisphere.setText(hemispheres[Hemisphere.valueOf(hemisphereString).getValue()]);
		if (tf != null) moonPhaseHemisphere.setTypeface(tf);

	}

	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.hasSubMenu() == false) {

			Log.d(TAG,"Item : " + item.getItemId());

			switch (item.getItemId()) {
			case R.id.menu_settings_date:
				datePickerFragment = new DatePickerFragment(this);
				Bundle args	= new Bundle();
				datePickerFragment.setArguments(args);
				datePickerFragment.show(getSupportFragmentManager(), "datePicker");
				break;
			case R.id.menu_settings_info:
				infoFragment = new InfoDialog();
				infoFragment.show(getSupportFragmentManager(), "info_dialog");
				break;
			case R.id.menu_settings_about:
				aboutFragment = new AboutDialog();
				aboutFragment.show(getSupportFragmentManager(), "about_dialog");
				break;
			case R.id.menu_settings_location:
				locationFragment = new LocationDialog(this);
				locationFragment.show(getSupportFragmentManager(), "location_dialog");
				break;
			}

		}

		// Consume the selection event.
		return true;
	}

	public static class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		MainActivity	parentActivity;

		public DatePickerFragment() {
		}

		public DatePickerFragment(MainActivity parentActivity) {
			this.parentActivity	= parentActivity;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {

			SharedPreferencesDao dao	= new SharedPreferencesDao(BasicApplication.getAppContext());
			String dateString	= dao.get("moon_phase_date");
			Calendar	date	= Calendar.getInstance();
			if ((dateString != null) && (dateString != "")) {
				date.setTimeInMillis(Long.parseLong(dateString));
			}

			int year = date.get(Calendar.YEAR);
			int month = date.get(Calendar.MONTH);
			int day = date.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			// Save the preferences
			SharedPreferencesDao dao	= new SharedPreferencesDao(BasicApplication.getAppContext());
			Calendar	date	= new GregorianCalendar(year, month, day);
			dao.update("moon_phase_date", String.valueOf( date.getTimeInMillis() ));
			this.parentActivity.updateMoonPhase();
		}
	}

	@Override
    public boolean dispatchTouchEvent(MotionEvent me){

		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);

    }

	@Override
	public void onSwipe(int direction) {

		switch (direction) {
		case SimpleGestureFilter.SWIPE_RIGHT :
			moveToNextDay();
			break;
		case SimpleGestureFilter.SWIPE_LEFT :
			moveToPrevDay();
			break;
		}

	}
	@Override
	public void onDoubleTap() {
		// TODO Auto-generated method stub

	}

	private void moveToNextDay() {
		SharedPreferencesDao dao	= new SharedPreferencesDao(BasicApplication.getAppContext());
		String dateString	= dao.get("moon_phase_date");

		Calendar	date	= Calendar.getInstance();
		if ((dateString != null) && (dateString != "")) {
			date.setTimeInMillis(Long.parseLong(dateString));
		}

		date.add(Calendar.DATE, 1);

		dao.update("moon_phase_date", String.valueOf( date.getTimeInMillis() ));

		updateMoonPhase();

	}

	private void moveToPrevDay() {

		SharedPreferencesDao dao	= new SharedPreferencesDao(BasicApplication.getAppContext());
		String dateString	= dao.get("moon_phase_date");

		Calendar	date	= Calendar.getInstance();
		if ((dateString != null) && (dateString != "")) {
			date.setTimeInMillis(Long.parseLong(dateString));
		}

		date.add(Calendar.DATE, -1);

		dao.update("moon_phase_date", String.valueOf( date.getTimeInMillis() ));

		updateMoonPhase();

	}

}


text:
var name = "null";
var set  = "null";

// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
  // If the tabs url starts with "http://specificsite.com"...
  var str = "http://gatherer.wizards.com/pages/card"
  if (tab.url.toLowerCase().indexOf(str) == 0) {
    // ... show the page action.
    chrome.pageAction.show(tabId);
  }
};

// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

// Listen for messages from Content containing cardinfo
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.cardinfo) {
      name = request.cardinfo.cardname;
      set  = request.cardinfo.cardset;
    }
    // Do cool stuff here?
});


text:
PYTHON ?= python
NOSETESTS=`which nosetests`

.PHONY: zipdoc sdist egg upload_to_pypi trailing-spaces clean-pyc clean-so clean-build clean-ctags clean in inplace test-code test-coverage test html specs check-before-commit check

zipdoc: html
	zip documentation.zip doc/_build/html

sdist: zipdoc
	@echo "Building source distribution..."
	python setup.py sdist
	@echo "Done building source distribution."
	# XXX copy documentation.zip to dist directory.

egg: zipdoc
	@echo "Building egg..."
	python setup.py bdist_egg
	@echo "Done building egg."

upload_to_pypi: zipdoc
	@echo "Uploading to PyPi..."
	python setup.py sdist --formats=zip,gztar upload

trailing-spaces:
	find . -name "*[.py|.rst]" -type f | xargs perl -pi -e 's/[ \t]*$$//'
	@echo "Reverting test_docparse"
	git checkout nipype/utils/tests/test_docparse.py

clean-pyc:
	find . -name "*.pyc" | xargs rm -f
	find . -name "__pycache__" -type d | xargs rm -rf

clean-so:
	find . -name "*.so" | xargs rm -f
	find . -name "*.pyd" | xargs rm -f

clean-build:
	rm -rf build

clean-ctags:
	rm -f tags

clean-doc:
	rm -rf doc/_build

clean-tests:
	rm -f .coverage

clean: clean-build clean-pyc clean-so clean-ctags clean-doc clean-tests

in: inplace # just a shortcut
inplace:
	$(PYTHON) setup.py build_ext -i

test-code: in
	py.test --doctest-module nipype

test-coverage: clean-tests in
	py.test --doctest-modules --cov-config .coveragerc --cov=nipype nipype

test: tests # just another name
tests: clean test-code

html:
	@echo "building docs"
	make -C doc clean htmlonly

specs:
	@echo "Checking specs and autogenerating spec tests"
	env PYTHONPATH=".:$(PYTHONPATH)" python tools/checkspecs.py

check: check-before-commit # just a shortcut
check-before-commit: specs trailing-spaces html test
	@echo "removed spaces"
	@echo "built docs"
	@echo "ran test"
	@echo "generated spec tests"


text:
<?php

namespace Symfony\Component\Cache\Adapter;

use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 */
class ProxyAdapter implements AdapterInterface
{
    private $pool;
    private $namespace;
    private $namespaceLen;
    private $createCacheItem;

    public function __construct(CacheItemPoolInterface $pool, $namespace = '', $defaultLifetime = 0)
    {
        $this->pool = $pool;
        $this->namespace = '' === $namespace ? '' : $this->getId($namespace);
        $this->namespaceLen = strlen($namespace);
        $this->createCacheItem = \Closure::bind(
            function ($key, $value, $isHit) use ($defaultLifetime) {
                $item = new CacheItem();
                $item->key = $key;
                $item->value = $value;
                $item->isHit = $isHit;
                $item->defaultLifetime = $defaultLifetime;

                return $item;
            },
            $this,
            CacheItem::class
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getItem($key)
    {
        $f = $this->createCacheItem;
        $item = $this->pool->getItem($this->getId($key));

        return $f($key, $item->get(), $item->isHit());
    }

    /**
     * {@inheritdoc}
     */
    public function getItems(array $keys = array())
    {
        if ($this->namespaceLen) {
            foreach ($keys as $i => $key) {
                $keys[$i] = $this->getId($key);
            }
        }

        return $this->generateItems($this->pool->getItems($keys));
    }

    /**
     * {@inheritdoc}
     */
    public function hasItem($key)
    {
        return $this->pool->hasItem($this->getId($key));
    }

    /**
     * {@inheritdoc}
     */
    public function clear()
    {
        return $this->pool->clear();
    }

    /**
     * {@inheritdoc}
     */
    public function deleteItem($key)
    {
        return $this->pool->deleteItem($this->getId($key));
    }

    /**
     * {@inheritdoc}
     */
    public function deleteItems(array $keys)
    {
        if ($this->namespaceLen) {
            foreach ($keys as $i => $key) {
                $keys[$i] = $this->getId($key);
            }
        }

        return $this->pool->deleteItems($keys);
    }

    /**
     * {@inheritdoc}
     */
    public function save(CacheItemInterface $item)
    {
        return $this->doSave($item, __FUNCTION__);
    }

    /**
     * {@inheritdoc}
     */
    public function saveDeferred(CacheItemInterface $item)
    {
        return $this->doSave($item, __FUNCTION__);
    }

    /**
     * {@inheritdoc}
     */
    public function commit()
    {
        return $this->pool->commit();
    }

    private function doSave(CacheItemInterface $item, $method)
    {
        if (!$item instanceof CacheItem) {
            return false;
        }
        $item = (array) $item;
        $expiry = $item[CacheItem::CAST_PREFIX.'expiry'];
        $poolItem = $this->pool->getItem($this->namespace.$item[CacheItem::CAST_PREFIX.'key']);
        $poolItem->set($item[CacheItem::CAST_PREFIX.'value']);
        $poolItem->expiresAt(null !== $expiry ? \DateTime::createFromFormat('U', $expiry) : null);

        return $this->pool->$method($poolItem);
    }

    private function generateItems($items)
    {
        $f = $this->createCacheItem;

        foreach ($items as $key => $item) {
            if ($this->namespaceLen) {
                $key = substr($key, $this->namespaceLen);
            }

            yield $key => $f($key, $item->get(), $item->isHit());
        }
    }

    private function getId($key)
    {
        CacheItem::validateKey($key);

        return $this->namespace.$key;
    }
}


text:
module ApplicationHelper
  def page_title
    case controller_name
    when 'transactions'
      'Operações'
    end
  end
end


text:
window.setupStore = function(options) {
  var env = {};
  options = options || {};

  var container = env.container = new Ember.Container();

  var adapter = env.adapter = options.adapter || DS.JsonApiAdapter;
  var serializer = env.serializer = options.serializer || DS.JsonApiSerializer;

  delete options.adapter;
  delete options.serializer;

  for (var prop in options) {
    container.register('model:' + prop, options[prop]);
  }

  container.register('store:main', DS.Store.extend({
    adapter: adapter
  }));

  container.register('serializer:application', serializer);

  container.injection('serializer', 'store', 'store:main');

  env.serializer = container.lookup('serializer:application');
  env.store = container.lookup('store:main');
  env.adapter = env.store.get('defaultAdapter');

  return env;
};


text:
namespace chromeos {

class CapsLockMenuButtonTest : public CrosInProcessBrowserTest {
 protected:
  CapsLockMenuButtonTest()
      : CrosInProcessBrowserTest() {
  }

  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  const CapsLockMenuButton* GetCapsLockMenuButton() {
    const views::View* view =
#if defined(USE_AURA)
        ChromeShellDelegate::instance()->GetStatusArea();
#else
        static_cast<BrowserView*>(browser()->window());
#endif
    return static_cast<const CapsLockMenuButton*>(
        view->GetViewByID(VIEW_ID_STATUS_BUTTON_CAPS_LOCK));
  }
};

IN_PROC_BROWSER_TEST_F(CapsLockMenuButtonTest, InitialIndicatorTest) {
  const CapsLockMenuButton* caps_lock = GetCapsLockMenuButton();
  ASSERT_TRUE(caps_lock != NULL);

  // By default, the indicator shouldn't be shown.
  EXPECT_FALSE(caps_lock->visible());
}

}  // namespace chromeos


text:
/* THIS SAMPLE CODE IS PROVIDED AS IS AND IS SUBJECT TO ALTERATIONS. FUJITSU */
/* MICROELECTRONICS ACCEPTS NO RESPONSIBILITY OR LIABILITY FOR ANY ERRORS OR */
/* ELIGIBILITY FOR ANY PURPOSES.                                             */
/*                 (C) Fujitsu Microelectronics Europe GmbH                  */

/*------------------------------------------------------------------------
  watchdog.c
  - This file contains the function deefinition for hardware watchdog.
-------------------------------------------------------------------------*/
#include "mb96348hs.h"
#include "FreeRTOS.h"
#include "task.h"
#include "watchdog.h"

/*---------------------------------------------------------------------------
 * Setup Watchdog
 *---------------------------------------------------------------------------*/
#if WATCHDOG != WTC_NONE
void InitWatchdog( void )
{
	WDTC_WTI = WTC_PER_2_23;	/* 2^23/CLKWT */
	WDTC_WTCS = WTC_CLKMC;		/* CLKWT=CLKMC, Watchdog expiration delay = 2.097s @ 4MHZ CLKMC*/
	WDTCP = 0x00;				/* Activate Watchdog, Clear Pattern 0x00 */
}

#endif

/*---------------------------------------------------------------------------
 * The below task clears the watchdog and blocks itself for WTC_CLR_PER ticks.
 *---------------------------------------------------------------------------*/
#if WATCHDOG == WTC_IN_TASK
static void prvWatchdogTask( void *pvParameters )
{
	const portTickType	xFrequency = WTC_CLR_PER;
	portTickType		xLastWakeTime;
	( void ) pvParameters;

	/* Get currrent tick count */
	xLastWakeTime = xTaskGetTickCount();

	for( ;; )
	{
		/* Get currrent tick count */
		xLastWakeTime = xTaskGetTickCount();

		Kick_Watchdog();

		/* Block the task for WTC_CLR_PER ticks (1s) at watchdog overflow period of WTC_PER_2_23 CLKMC cycles */
		vTaskDelayUntil( &xLastWakeTime, xFrequency );
	}
}

#endif

/*---------------------------------------------------------------------------
 * The below function creates hardware watchdog task.
 *---------------------------------------------------------------------------*/
#if WATCHDOG == WTC_IN_TASK
void vStartWatchdogTask( unsigned portBASE_TYPE uxPriority )
{
	xTaskCreate( prvWatchdogTask, (signed portCHAR *) "KickWTC", portMINIMAL_STACK_SIZE, ( void * ) NULL, uxPriority, ( xTaskHandle * ) NULL );
}

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Frisch & Kalb, Biblthca Lichenol. 92: 464 (2006)

#### Original name
Myriotrema guianense Sipman

### Remarks
null


text:
package com.github.paolorotolo.appintro;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.nineoldandroids.view.ViewHelper;

/**
 * Created by rohit on 22/7/15.
 */
class ViewPagerTransformer implements ViewPager.PageTransformer {

    static enum TransformType {
        FLOW,
        DEPTH,
        ZOOM,
        SLIDE_OVER,
        FADE
    }

    private final TransformType mTransformType;

    ViewPagerTransformer(TransformType transformType) {
        mTransformType = transformType;
    }

    private static final float MIN_SCALE_DEPTH = 0.75f;
    private static final float MIN_SCALE_ZOOM = 0.85f;
    private static final float MIN_ALPHA_ZOOM = 0.5f;
    private static final float SCALE_FACTOR_SLIDE = 0.85f;
    private static final float MIN_ALPHA_SLIDE = 0.35f;

    @SuppressLint("NewApi")
    public void transformPage(View page, float position) {
        final float alpha;
        final float scale;
        final float translationX;

        switch (mTransformType) {
            case FLOW:
                page.setRotationY(position * -30f);
                return;

            case SLIDE_OVER:
                if (position < 0 && position > -1) {
                    // this is the page to the left
                    scale = Math.abs(Math.abs(position) - 1) * (1.0f - SCALE_FACTOR_SLIDE) + SCALE_FACTOR_SLIDE;
                    alpha = Math.max(MIN_ALPHA_SLIDE, 1 - Math.abs(position));
                    int pageWidth = page.getWidth();
                    float translateValue = position * -pageWidth;
                    if (translateValue > -pageWidth) {
                        translationX = translateValue;
                    } else {
                        translationX = 0;
                    }
                } else {
                    alpha = 1;
                    scale = 1;
                    translationX = 0;
                }
                break;

            case DEPTH:
                if (position > 0 && position < 1) {
                    // moving to the right
                    alpha = (1 - position);
                    scale = MIN_SCALE_DEPTH + (1 - MIN_SCALE_DEPTH) * (1 - Math.abs(position));
                    translationX = (page.getWidth() * -position);
                } else {
                    // use default for all other cases
                    alpha = 1;
                    scale = 1;
                    translationX = 0;
                }
                break;

            case ZOOM:
                if (position >= -1 && position <= 1) {
                    scale = Math.max(MIN_SCALE_ZOOM, 1 - Math.abs(position));
                    alpha = MIN_ALPHA_ZOOM +
                            (scale - MIN_SCALE_ZOOM) / (1 - MIN_SCALE_ZOOM) * (1 - MIN_ALPHA_ZOOM);
                    float vMargin = page.getHeight() * (1 - scale) / 2;
                    float hMargin = page.getWidth() * (1 - scale) / 2;
                    if (position < 0) {
                        translationX = (hMargin - vMargin / 2);
                    } else {
                        translationX = (-hMargin + vMargin / 2);
                    }
                } else {
                    alpha = 1;
                    scale = 1;
                    translationX = 0;
                }
                break;
            case FADE:
                if (position <= -1.0F || position >= 1.0F) {
                    ViewHelper.setAlpha(page, 0.0F);
                    page.setClickable(false);
                } else if (position == 0.0F) {
                    ViewHelper.setAlpha(page, 1.0F);
                    page.setClickable(true);
                } else {
                    // position is between -1.0F & 0.0F OR 0.0F & 1.0F
                    ViewHelper.setAlpha(page, 1.0F - Math.abs(position));
                }

            default:
                return;
        }

        page.setAlpha(alpha);
        page.setTranslationX(translationX);
        page.setScaleX(scale);
        page.setScaleY(scale);
    }
}


text:
class CreateOwners < ActiveRecord::Migration
  def change
    create_table :owners do |t|
      t.string :name
      t.string :lastname
      t.string :phone

      t.timestamps null: false
    end
  end
end


text:
<!DOCTYPE html>

There should be two small green squares vertically aligned below, and another red square to the top-right. The second green square does not overlap the red because it is conmposited, and hence not fragmented.


text:
import configureStore from 'redux-mock-store';

import { createSuccessAction, createErrorAction } from '../actions';

import { createServerSsrMiddleware } from '.';

const defer = () => {
  let res;
  let rej;
  const promise = new Promise((resolve, reject) => {
    res = resolve;
    rej = reject;
  });
  promise.resolve = res;
  promise.reject = rej;
  return promise;
};

describe('middleware', () => {
  describe('createServerSsrMiddleware', () => {
    const requestAction = { type: 'REQUEST', request: { url: '/' } };
    const successAction = createSuccessAction(requestAction, 'data');
    const errorAction = createErrorAction(requestAction, 'error');

    it('rejects promise on error response', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      store.dispatch(requestAction);
      store.dispatch(requestAction);
      store.dispatch(successAction);
      store.dispatch(errorAction);
      expect(store.getActions()).toEqual([
        requestAction,
        requestAction,
        successAction,
        errorAction,
      ]);
      await expect(requestsPromise).rejects.toEqual({
        successActions: [successAction],
        errorActions: [errorAction],
      });
    });

    it('resolves promise on finished successful requests', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      store.dispatch(requestAction);
      store.dispatch(requestAction);
      store.dispatch(successAction);
      store.dispatch(successAction);
      expect(store.getActions()).toEqual([
        requestAction,
        requestAction,
        successAction,
        successAction,
      ]);
      await expect(requestsPromise).resolves.toEqual([
        successAction,
        successAction,
      ]);
    });

    it('supports dependent actions', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      const firstRequestAction = {
        type: 'REQUEST',
        request: { url: '/' },
        meta: { dependentRequestsNumber: 2 },
      };
      const secondRequestAction = {
        type: 'REQUEST2',
        request: { url: '/' },
        meta: { isDependentRequest: true },
      };
      const thirdRequestAction = {
        type: 'REQUEST3',
        request: { url: '/' },
        meta: { isDependentRequest: true },
      };
      const firsResponseAction = createSuccessAction(firstRequestAction);
      const secondResponseAction = createSuccessAction(secondRequestAction);
      const thirdResponseAction = createSuccessAction(thirdRequestAction);
      store.dispatch(firstRequestAction);
      store.dispatch(firsResponseAction);
      store.dispatch(secondRequestAction);
      store.dispatch(thirdRequestAction);
      store.dispatch(secondResponseAction);
      store.dispatch(thirdResponseAction);
      expect(store.getActions()).toEqual([
        firstRequestAction,
        firsResponseAction,
        secondRequestAction,
        thirdRequestAction,
        secondResponseAction,
        thirdResponseAction,
      ]);
      await expect(requestsPromise).resolves.toEqual([
        firsResponseAction,
        secondResponseAction,
        thirdResponseAction,
      ]);
    });

    it('supports dependent actions when first one fails', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      const firstRequestAction = {
        type: 'REQUEST',
        request: { url: '/' },
        meta: { dependentRequestsNumber: 2 },
      };
      // const secondRequestAction = {
      //   type: 'REQUEST2',
      //   request: { url: '/' },
      //   meta: { isDependentRequest: true },
      // };
      // const thirdRequestAction = {
      //   type: 'REQUEST3',
      //   request: { url: '/' },
      //   meta: { isDependentRequest: true },
      // };
      const firsErrorAction = createErrorAction(firstRequestAction);
      // const secondResponseAction = createSuccessAction(secondRequestAction);
      // const thirdResponseAction = createSuccessAction(thirdRequestAction);
      store.dispatch(firstRequestAction);
      store.dispatch(firsErrorAction);
      // store.dispatch(secondRequestAction);
      // store.dispatch(thirdRequestAction);
      // store.dispatch(secondResponseAction);
      // store.dispatch(thirdResponseAction);
      expect(store.getActions()).toEqual([
        firstRequestAction,
        firsErrorAction,
        // secondRequestAction,
        // thirdRequestAction,
        // secondResponseAction,
        // thirdResponseAction,
      ]);
      await expect(requestsPromise).rejects.toEqual({
        successActions: [],
        errorActions: [firsErrorAction],
      });
    });

    it('supports dependent actions when 3rd action failes', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      const firstRequestAction = {
        type: 'REQUEST',
        request: { url: '/' },
        meta: { dependentRequestsNumber: 2 },
      };
      const secondRequestAction = {
        type: 'REQUEST2',
        request: { url: '/' },
        meta: { isDependentRequest: true },
      };
      const thirdRequestAction = {
        type: 'REQUEST3',
        request: { url: '/' },
        meta: { isDependentRequest: true },
      };
      const firsResponseAction = createSuccessAction(firstRequestAction);
      const secondResponseAction = createSuccessAction(secondRequestAction);
      const thirdErrorAction = createErrorAction(thirdRequestAction);
      store.dispatch(firstRequestAction);
      store.dispatch(firsResponseAction);
      store.dispatch(secondRequestAction);
      store.dispatch(thirdRequestAction);
      store.dispatch(secondResponseAction);
      store.dispatch(thirdErrorAction);
      expect(store.getActions()).toEqual([
        firstRequestAction,
        firsResponseAction,
        secondRequestAction,
        thirdRequestAction,
        secondResponseAction,
        thirdErrorAction,
      ]);
      await expect(requestsPromise).rejects.toEqual({
        successActions: [firsResponseAction, secondResponseAction],
        errorActions: [thirdErrorAction],
      });
    });

    it('supports dependent actions 1 => 2 => 3 when 2nd fails', async () => {
      const requestsPromise = defer();
      const mockStore = configureStore([
        createServerSsrMiddleware(requestsPromise),
      ]);
      const store = mockStore({});
      const firstRequestAction = {
        type: 'REQUEST',
        request: { url: '/' },
        meta: { dependentRequestsNumber: 1 },
      };
      const secondRequestAction = {
        type: 'REQUEST2',
        request: { url: '/' },
        meta: { isDependentRequest: true, dependentRequestsNumber: 1 },
      };
      // const thirdRequestAction = {
      //   type: 'REQUEST3',
      //   request: { url: '/' },
      //   meta: { isDependentRequest: true },
      // };
      const firsResponseAction = createSuccessAction(firstRequestAction);
      const secondErrorAction = createErrorAction(secondRequestAction);
      // const thirdResponseAction = createSuccessAction(thirdRequestAction);
      store.dispatch(firstRequestAction);
      store.dispatch(firsResponseAction);
      store.dispatch(secondRequestAction);
      // store.dispatch(thirdRequestAction);
      store.dispatch(secondErrorAction);
      // store.dispatch(thirdResponseAction);
      expect(store.getActions()).toEqual([
        firstRequestAction,
        firsResponseAction,
        secondRequestAction,
        // thirdRequestAction,
        secondErrorAction,
        // thirdResponseAction,
      ]);
      await expect(requestsPromise).rejects.toEqual({
        successActions: [firsResponseAction],
        errorActions: [secondErrorAction],
      });
    });
  });
});


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

namespace System.Collections.Concurrent.Partitioners
{
	// Represent a chunk partitioner
	internal class EnumerablePartitioner<T> : OrderablePartitioner<T>
	{
		IEnumerable<T> source;

		const int InitialPartitionSize = 1;
		const int PartitionMultiplier = 2;

		int initialPartitionSize;
		int partitionMultiplier;

		public EnumerablePartitioner (IEnumerable<T> source)
			: this (source, InitialPartitionSize, PartitionMultiplier)
		{

		}

		// This is used to get striped partitionning (for Take and Skip for instance
		public EnumerablePartitioner (IEnumerable<T> source, int initialPartitionSize, int partitionMultiplier)
			 : base (true, false, true)
		{
			this.source = source;
			this.initialPartitionSize = initialPartitionSize;
			this.partitionMultiplier = partitionMultiplier;
		}

		public override IList<IEnumerator<KeyValuePair<long, T>>> GetOrderablePartitions (int partitionCount)
		{
			if (partitionCount <= 0)
				throw new ArgumentOutOfRangeException ("partitionCount");

			IEnumerator<KeyValuePair<long, T>>[] enumerators
				= new IEnumerator<KeyValuePair<long, T>>[partitionCount];

			PartitionerState state = new PartitionerState ();
			IEnumerator<T> src = source.GetEnumerator ();
			bool isSimple = initialPartitionSize == 1 && partitionMultiplier == 1;

			for (int i = 0; i < enumerators.Length; i++) {
				enumerators[i] = isSimple ? GetPartitionEnumeratorSimple (src, state, i == enumerators.Length - 1) : GetPartitionEnumerator (src, state);
			}

			return enumerators;
		}

		// This partitioner that is simpler than the general case (don't use a list) is called in the case
		// of initialPartitionSize == partitionMultiplier == 1
		IEnumerator<KeyValuePair<long, T>> GetPartitionEnumeratorSimple (IEnumerator<T> src,
		                                                                 PartitionerState state,
		                                                                 bool last)
		{
			long index = -1;
			var value = default (T);

			try {
				do {
					lock (state.SyncLock) {
						if (state.Finished)
							break;
						if (state.Finished = !src.MoveNext ())
							break;

						index = state.Index++;
						value = src.Current;
					}

					yield return new KeyValuePair<long, T> (index, value);
				} while (!state.Finished);
			} finally {
				if (last)
					src.Dispose ();
			}
		}

		IEnumerator<KeyValuePair<long, T>> GetPartitionEnumerator (IEnumerator<T> src, PartitionerState state)
		{
			int count = initialPartitionSize;
			List<T> list = new List<T> ();

			while (!state.Finished) {
				list.Clear ();
				long ind = -1;

				lock (state.SyncLock) {
					if (state.Finished)
						break;

					ind = state.Index;

					for (int i = 0; i < count; i++) {
						if (state.Finished = !src.MoveNext ()) {
							if (list.Count == 0)
								yield break;
							else
								break;
						}

						list.Add (src.Current);
						state.Index++;
					}
				}

				for (int i = 0; i < list.Count; i++)
					yield return new KeyValuePair<long, T> (ind + i, list[i]);

				count *= partitionMultiplier;
			}
		}

		class PartitionerState
		{
			public bool Finished;
			public long Index = 0;
			public readonly object SyncLock = new object ();
		}
	}
}


text:
package com.intapp.vertx.guice.stubs;

import com.google.common.base.Preconditions;

import io.vertx.core.AbstractVerticle;

import javax.inject.Inject;

/**
 * Verticle which uses constructor injection to define dependent classes.
 */
public class VerticleWithDependency extends AbstractVerticle {
    private final Dependency dependency;

    @Inject
    public VerticleWithDependency(Dependency dependency) {
        this.dependency = Preconditions.checkNotNull(dependency);
    }

    public Dependency getDependency() {
        return dependency;
    }
}


text:
package diet.model;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@MappedSuperclass
public class PreparedFoodData {

	@XmlElement(name = "raw")
	@Column(name = "raw_quantity", nullable = false)
	int rawQuantity;

	@XmlElement(name = "cooked")
	@Column(name = "cooked_quantity", nullable = false)
	int cookedQuantity;

	protected PreparedFoodData() {
		super();
	}

	protected PreparedFoodData(PreparedFoodData data) {
		super();
		this.rawQuantity = data.rawQuantity;
		this.cookedQuantity = data.cookedQuantity;
	}

}


text:
from pymongo import MongoClient, MongoReplicaSetClient, ASCENDING, DESCENDING
from pymongo.errors import OperationFailure
from .utils import classproperty
from .exceptions import MultipleObjectsExist, DoesNotExist, QueryError

import os
import sys
import logging

logger = logging.getLogger(__name__)

# keep this stuff super secret
DAT_REPLICA_SET_URI = os.environ.get('DAT_REPLICA_SET_URI')
DAT_REPLICA_SET_NAME = os.environ.get('DAT_DATABASE_NAME')
# E.G.
# DAT_REPLICA_SET_URI = (
#     "mongodb://<USER_NAME>:<PASSWORD>@<URI_1>:<PORT_1>,<URI_2>:<PORT_2>/"
#     "<DATABASE_NAME>"
# )
# DAT_REPLICA_SET_NAME = "set-<UID_HASH>"

DATABASE_NAME = os.environ.get('DAT_DATABASE_NAME', 'dat')

if DAT_REPLICA_SET_URI and DAT_REPLICA_SET_NAME:
    mongo_client = MongoReplicaSetClient(
        DAT_REPLICA_SET_URI, replicaSet=DAT_REPLICA_SET_NAME
    )
else:
    mongo_client = MongoClient()

BSON_TYPES = {
    'Double': 1,
    'String': 2,
    'Object': 3,
    'Array': 4,
    'Binary': 5,
    'Undefined': 6,
    'ObjectId': 7,
    'Boolean': 8,
    'Date': 9,
    'Null': 10,
    'RegEx': 11,
    'JavaScript': 13,
    'Symbol': 14,
    'JavaScript': 15,
    'Integer32': 16,
    'Timestamp': 17,
    'Integer64': 18,
    'MinKey': 255,
    'MaxKey': 127
}

def getUniqueInnerKeys(document):
    unique_names = set()
    for key, dct in document.items():
        unique_names.add(*dct.keys())
    return unique_names

def parseUpdateKwargs(kwargs):
    for key, value in kwargs.items():
        if '__' in key:
            raise ValueError(
                'dat.db.QuerySet.update does not support alternate operators '
                'or modifiers via keyword arguments. Unsupported: %s' % key
            ), None, sys.exc_info()[2]
    return {'$set': kwargs}

class QuerySet(object):

    def __repr__(self):
        return '<QuerySet(%s, %s, %s, limit=%s)>' % (
            self.model_class.__name__,
            self.conditions,
            self.projection,
            self._limit
        )

    def __init__(self, model_class, conditions, projection, limit=None):
        self.conditions = conditions
        self.projection = projection
        self.model_class = model_class
        self._limit = limit

    def serialize(self, to_json=False):
        return [instance.serialize(to_json=to_json) for instance in self]

    def filter(
        self, conditions=None, projection=None, include=None, exclude=None,
        limit=None
    ):
        # busts _cursor
        conditions = conditions or {}
        projection = projection or {}
        self.conditions.update(conditions)
        if self.projection is None and projection:
            self.projection = {}
        if projection:
            self.projection.update(
                DatabaseInterface.parseProjections(
                    projection, include=include, exclude=exclude
                )
            )
        self._clear()
        return self

    def _clear(self):
        if hasattr(self, '_cursor'):
            del self._cursor
        if hasattr(self, '_cache'):
            del self._cache

    @property
    def cursor(self):
        if not hasattr(self, '_cursor'):
            self._cursor = self.model_class.collection.find(
                self.conditions, self.projection
            )
            if hasattr(self, '_limit') and self._limit:
                self._cursor = self._cursor.limit(self._limit)
            if hasattr(self, '_hint') and self._hint:
                self._cursor = self._cursor.hint(self._hint)
            if hasattr(self, '_sort') and self._sort:
                self._cursor = self._cursor.sort(*self._sort)
            if hasattr(self, '_skip') and self._skip:
                self._cursor = self._cursor.skip(self._skip)
        return self._cursor

    def skip(self, value):
        self._skip = value
        if hasattr(self, '_cursor'):
            del self._cursor
        return self

    def limit(self, value):
        self._limit = value
        self._clear()
        return self

    def sort(self, key_or_list, direction=ASCENDING):
        self._sort = (key_or_list, direction)
        self._clear()
        return self

    def hint(self, field):
        self._hint = field
        self._clear()
        return self

    def distinct(self, key_or_list):
        return self.cursor.distinct(key_or_list)

    def __iter__(self):
        cursor = self.cursor.clone()
        try:
            for document in cursor:
                yield self.model_class(_from_db=True, **document)
        except OperationFailure, e:
            raise QueryError(e.details.get('$err')), None, sys.exc_info()[2]

    def __getitem__(self, index):
        try:
            if not hasattr(self, '_cache'):
                self._cache = tuple(self)
            return self._cache[index]
        except OperationFailure, e:
            raise QueryError(e.details.get('errmsg')), None, sys.exc_info()[2]

    def __len__(self):
        return self.count(with_limit_and_skip=True)

    def count(self, with_limit_and_skip=False):
        return self.cursor.count(with_limit_and_skip=with_limit_and_skip)

    def exists(self):
        return bool(self.count(with_limit_and_skip=True))

    def update(
        self, document=None, multi=True, upsert=False,
        getUniqueInnerKeys=getUniqueInnerKeys,
        parseUpdateKwargs=parseUpdateKwargs, **kwargs
    ):
        """
        SINGLE VALUE FIELDS
        $currentDate    - Sets the value of a field to current date, either
                          as a Date or a Timestamp.
        $inc	        - Increments the value of the field by the specified
                          amount.
        $max	        - Only updates the field if the specified value is
                          greater than the existing field value.
        $min	        - Only updates the field if the specified value is
                          less than the existing field value.
        $mul	        - Multiplies the value of the field by the specified
                          amount.
        $rename	        - Renames a field.
        $setOnInsert	- Sets the value of a field if an update results in an
                          insert of a document. Has no effect on update
                          operations that modify existing documents.
        $set	        - Sets the value of a field in a document.
        $unset	        - Removes the specified field from a document.

        LIST/SET FIELDS
        $               - Acts as a placeholder to update the first element
                          that matches the query condition in an update.
        $addToSet       - Adds elements to an array only if they do not already
                          exist in the set.
        $pop            - Removes the first or last item of an array.
        $pullAll        - Removes all matching values from an array.
        $pull           - Removes all array elements that match a specified
                          query.
        $pushAll        - Deprecated. Adds several items to an array.
        $push           - Adds an item to an array.

        LIST MODIFIERS
        $each           - Modifies the $push and $addToSet operators to append
                          multiple items for array updates.
        $position       - Modifies the $push operator to specify the position
                          in the array to add elements.
        $slice          - Modifies the $push operator to limit the size of
                          updated arrays.
        $sort           - Modifies the $push operator to reorder documents
                          stored in an array.
        """
        document = document or {}
        if document and kwargs:
            raise ValueError(
                'Unsupported method input: using both a dictionary and kwargs '
                'is not supported. Please use %s or %s.' % (document, kwargs)
            ), None, sys.exc_info()[2]
        elif kwargs:
            document.update(parseUpdateKwargs(kwargs))
        elif not document:
            raise ValueError(
                'Either supply a mongo-like document with operators and '
                'modifiers, or a series of keyword arguements to be set.'
            ), None, sys.exc_info()[2]

        # maintain the integrity of the data schema by checking if the user has
        # tried to insert a new field to the found documents.
        actual_fieldnames = set(self.model_class.meta.fields.keys())
        doc_fieldnames = getUniqueInnerKeys(document)
        wrong_fieldnames = tuple(doc_fieldnames - actual_fieldnames)
        if wrong_fieldnames:
            raise ValueError(
                'Could not find the fields %s in the list of %r\'s fields: '
                '%s' % (
                    wrong_fieldnames,
                    self.model_class,
                    tuple(actual_fieldnames)
                )
            )

        acknowledgement = self.model_class.collection.update(
            self.conditions, document, multi=multi, upsert=upsert, **kwargs
        )
        logger.debug(acknowledgement)
        return self

class DatabaseInterface(object):
    """
    A mixin interface for models to connect with the database. It contains both
    class methods and instance methods to allow the user to update one or many
    documents in the .
    """

    MultipleObjectsExist = MultipleObjectsExist
    DoesNotExist = DoesNotExist
    QueryError = QueryError
    ASCENDING = ASCENDING
    DESCENDING = DESCENDING

    queryFactory = QuerySet
    _client = mongo_client

    @classproperty
    def _db(cls):
        return cls._client[DATABASE_NAME]

    @classproperty
    def collection(cls):
        if hasattr(cls, 'collection_name'):
            collection_name = cls.collection_name
        else:
            collection_name = cls.__name__.lower()
        return cls._db[collection_name]

    ###########################################################################
    # helper methods - cleaning developer input
    @classmethod
    def parseProjections(cls, projection, include=None, exclude=None):
        include = include or []
        exclude = exclude or []
        for field in include:
            projection[field] = 1
        for field in exclude:
            projection[field] = 0
        return projection

    @classmethod
    def parseConditions(cls, **kwargs):
        conditions = {}
        for key, value in kwargs.items():
            if not key:
                raise QueryError(
                    'Field name must be specified on a query, it may not be an'
                    'empty string or begin with "__".'
                ), None, sys.exc_info()[2]
            parts = key.split('__')
            num_parts = len(parts)
            if num_parts == 1:
                conditions[key] = value
            elif num_parts == 2:
                field, modifier = parts
                conditions[field] = {'$%s' % modifier: value}
            elif num_parts > 2:
                raise QueryError(
                    'Two occurrences of "__" is not supported in query '
                    'statements.'
                ), None, sys.exc_info()[2]
        return conditions

    ###########################################################################
    # Class methods to create and retrieve data
    @classmethod
    def bulk_create(cls, model_list):
        bulkop = cls.collection.initialize_unordered_bulk_op()
        for model in model_list:
            bulkop.insert(model.serialize())
        ack = bulkop.execute()
        logger.debug(ack)
        return len(model_list)

    @classmethod
    def create(cls, **data):
        """
        a convenience method that inserts the document without hitting the save
        method
        """
        model = cls(**data)
        _id = cls.collection.insert(model.serialize())
        model._id = _id
        model._from_db = True
        return model

    @classmethod
    def get(
        cls, conditions=None, projection=None, include=None, exclude=None,
        *args, **kwargs
    ):
        conditions = conditions or {}
        if kwargs:
            conditions.update(cls.parseConditions(**kwargs))
        projection = projection or {}
        projection = cls.parseProjections(
            projection, include=include, exclude=exclude
        )
        projection = projection or None
        cursor = cls.collection.find(conditions, projection)
        if cursor.count() > 1:
            raise MultipleObjectsExist(
                '%r.get returned multiple instances for the given conditions:'
                '\n%s' % (cls, conditions)
            ), None, sys.exc_info()[2]
        try:
            return cls(_from_db=True, _conditions=conditions, **cursor[0])
        except IndexError, e:
            logger.debug(str(e))
            raise DoesNotExist(
                '%r.get could not find an instance matching the '
                'given conditions:\n%s' % (cls, conditions)
            ), None, sys.exc_info()[2]

    @classmethod
    def filter(
        cls, conditions=None, projection=None, include=None, exclude=None,
        limit=None, *args, **kwargs
    ):
        """
        Returns a QuerySet which does not execute the cursor until a method
        that calls __iter__ is used. filters can be daisy chained and modified
        to include hints, sort, distinct, limit

        VALUE CONDITIONS
        $gt     - Matches values that are greater than the value specified in
                  the query.
        $gte	- Matches values that are greater than or equal to the value
                  specified in the query.
        $in	    - Matches any of the values that exist in an array specified in
                  the query.
        $lt	    - Matches values that are less than the value specified in the
                  query.
        $lte	- Matches values that are less than or equal to the value
                  specified in the query.
        $ne	    - Matches all values that are not equal to the value specified
                  in the query.
        $nin	- Matches values that do not exist in an array specified to the
                  query.

        ARRAY CONDITIONS
        $all        - Matches arrays that contain all elements specified in the
                      query.
        $elemMatch	- Selects documents if element in the array field matches
                      all the specified $elemMatch condition.
        $size       - Selects documents if the array field is a specified size.

        PROJECTIONS
        $           - Projects the first element in an array that matches the
                      query condition.
        $elemMatch	- Projects the first element in an array that matches the
                      specified $elemMatch condition.
        $meta       - Projects the document's score assigned during $text
                      operation.
        $slice      - Limits the number of elements projected from an array.
                      Supports skip and limit slices.

        ELEMENT
        $exists     - Matches documents that have the specified field.
        $type       - Selects documents if a field is of the specified type.

        LOGICAL
        $and	- Joins query clauses with a logical AND returns all documents
                  that match the conditions of both clauses.
        $nor	- Joins query clauses with a logical NOR returns all documents
                  that fail to match both clauses.
        $not	- Inverts the effect of a query expression and returns
                  documents that do not match the query expression.
        $or     - Joins query clauses with a logical OR returns all documents
                  that match the conditions of either clause.

        GEOSPATIAL
        $geoIntersects	- Selects geometries that intersect with a GeoJSON
                          geometry.
        $geoWithin      - Selects geometries within a bounding GeoJSON geometry
        $nearSphere     - Returns geospatial objects in proximity to a point on
                          a sphere.
        $near           - Returns geospatial objects in proximity to a point.
        """
        conditions = conditions or {}
        if kwargs:
            conditions.update(cls.parseConditions(**kwargs))
        projection = projection or {}
        projection = cls.parseProjections(
            projection, include=include, exclude=exclude
        )
        projection = projection or None
        return cls.queryFactory(cls, conditions, projection, limit=limit)

    @classmethod
    def all(cls, projection=None, include=None, exclude=None):
        "a convenience method that returns all documents in a collection"
        projection = projection or {}
        projection = cls.parseProjections(
            projection, include=include, exclude=exclude
        )
        projection = projection or None
        return cls.queryFactory(cls, {}, projection)

    ###########################################################################
    # Instance Methods
    def save(self, **kwargs):
        "saves the model document and sets _from_db to True"
        document = self.serialize()
        _id = self.collection.save(document, **kwargs)
        self._id = _id
        self._from_db = True
        return self


text:
/**
 * @file api.js
 * Xmasspace Xmas Admin Routes
 * @desc Xmas admin routes
 */

var rek = require('rekuire'),
    m_settings = rek('modules/xmas/settings'),
    xmasModel = rek('modules/xmas/data/models/xmas'),
    configModel = rek('modules/xmas/data/models/config'),
    voteImage = rek('modules/xmas/middlewares/vote_image'),
    loadImagesWithAuthorVotes= rek('modules/xmas/middlewares/load_images_with_author_votes'),
    settings= rek('/settings');

var routes = {};

/**
 * @desc  Parent admin Xmas route
 * @return object - Xmas admin parent page render
 */
routes[settings.apiPrefix + '/' + m_settings.route_prefix + '/misc/all'] =  {
    methods: ['get'],
    middleware: [loadImagesWithAuthorVotes(xmasModel)],
    fn: function(req, res, next) {
        res.send({
            'success':true,
            'categories':req.objects
            }
        );
    }
};

/**
 * @desc  Parent admin Xmas route
 * @return object - Xmas admin parent page render
 */
routes[settings.apiPrefix + '/' + m_settings.route_prefix + '/misc/xmas/vote/:id'] =  {
    methods: ['post'],
    middleware: [voteImage(xmasModel)],
    fn: function(req, res, next) {
        res.send({
            'success': true
            }
        );
    }
};

routes[settings.apiPrefix + '/' + m_settings.route_prefix + '/misc/config/add/category'] =  {
    methods: ['post'],
    middleware: [],
    fn: function(req, res, next) {
        configModel.addCategory(req.body.category, req, function() {
            res.send({
                'success':true
            });
        });
    }
};

routes[settings.apiPrefix + '/' + m_settings.route_prefix + '/misc/config/update/category'] =  {
    methods: ['post'],
    middleware: [],
    fn: function(req, res, next) {
        configModel.updateCategory(req.body.category, req, function() {
            res.send({
                'success':true
            });
        });
    }
};

routes[settings.apiPrefix + '/' + m_settings.route_prefix + '/misc/config/remove/category'] =  {
    methods: ['post'],
    middleware: [],
    fn: function(req, res, next) {
        configModel.removeCategory(req.body.category, req, function() {
            res.send({
                'success':true
            });
        });
    }
};

module.exports = routes;


text:
Welcome to Siegmeyer!

A SMACSS Boilerplate. Includes responsive grids & typographic rhythm.

Don't forget to adjust your cap heights on a per-font basis!


text:
if (process.env.NODE_ENV === 'production') {
  module.exports = require('./dist/react-tv.production.js');
} else {
  module.exports = require('./dist/react-tv.development.js');
}


text:
var app = angular.module('starter', ['ionic'])

.run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
      if (window.cordova && window.cordova.plugins.Keyboard) {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

        // Don't remove this line unless you know what you are doing. It stops the viewport
        // from snapping when text inputs are focused. Ionic handles this internally for
        // a much nicer keyboard experience.
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('playlistIndex', {
        url: '/playlistIndex',
        templateUrl: 'templates/videos-index.html',
        controller: 'VideosPlaylistIndexController as VideosPlaylistIndexCtrl'
      })
      .state('playlist', {
        url: '/playlist/:videoId/:playlistId',
        templateUrl: 'templates/videos-playlist.html',
        controller: 'VideosPlaylistController as VideosPlaylistCtrl'
      });
    $urlRouterProvider.otherwise('playlistIndex');
  })


text:
<!DOCTYPE html>

<title>View transitions: duplicate tags in the old DOM skip the transition</title>
<link rel="help" href="https://www.w3.org/TR/css-view-transitions-1/">
<link rel="author" href="mailto:khushalsagar@chromium.org">


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.vfs;

import java.io.IOException;
import java.util.List;

/**
 * An interface for doing a batch of stat() calls.
 */
public interface BatchStat {

  /**
   *
   * @param includeDigest whether to include a file digest in the return values.
   * @param includeLinks whether to include a symlink stat in the return values.
   * @param paths The input paths to stat(), relative to the exec root.
   * @return an array list of FileStatusWithDigest in the same order as the input. May
   *         contain null values.
   * @throws IOException on unexpected failure.
   * @throws InterruptedException on interrupt.
   */
  public List<FileStatusWithDigest> batchStat(boolean includeDigest,
                                              boolean includeLinks,
                                              Iterable<PathFragment> paths)
      throws IOException, InterruptedException;
}


text:
from __future__ import unicode_literals

from StringIO import StringIO

import sys

from ios_code_generator.generators import generate

__author__ = 'banxi'

def test_const():
    strio = StringIO(u"-User\nvideo;list;table;text;picture")
    sys.stdin = strio
    text = generate('const')
    print(text)


text:
Widget Position Constrain
=========================

An extension, which can be used with Base.build to add the ability to constrain
XY positioning for a widget to the viewport, or to another node. Also provides
"preventOverlap" support, to prevent the widget from overlapping the node to
which it is aligned (when using widget-position-align).