text:
module TestImport
    ( module TestImport
    , module X
    ) where

import Application           (makeFoundation, makeLogWare)
import ClassyPrelude         as X hiding (delete, deleteBy)
import Database.Persist      as X hiding (get)
import Database.Persist.Sql  (SqlPersistM, SqlBackend, runSqlPersistMPool, rawExecute, rawSql, unSingle, connEscapeName)
import Foundation            as X
import Model                 as X
import Test.Hspec            as X
import Yesod.Default.Config2 (ignoreEnv, loadYamlSettings)
import Yesod.Test            as X

-- Wiping the database
import Database.Persist.Sqlite              (sqlDatabase, wrapConnection, createSqlPool)
import qualified Database.Sqlite as Sqlite
import Control.Monad.Logger                 (runLoggingT)
import Settings (appDatabaseConf)
import Yesod.Core (messageLoggerSource)

runDB :: SqlPersistM a -> YesodExample App a
runDB query = do
    pool <- fmap appConnPool getTestYesod
    liftIO $ runSqlPersistMPool query pool

withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
    settings <- loadYamlSettings
        ["config/test-settings.yml", "config/settings.yml"]
        []
        ignoreEnv
    foundation <- makeFoundation settings
    wipeDB foundation
    logWare <- liftIO $ makeLogWare foundation
    return (foundation, logWare)

-- This function will truncate all of the tables in your database.
-- 'withApp' calls it before each test, creating a clean environment for each
-- spec to run in.
wipeDB :: App -> IO ()
wipeDB app = do
    -- In order to wipe the database, we need to temporarily disable foreign key checks.
    -- Unfortunately, disabling FK checks in a transaction is a noop in SQLite.
    -- Normal Persistent functions will wrap your SQL in a transaction,
    -- so we create a raw SQLite connection to disable foreign keys.
    -- Foreign key checks are per-connection, so this won't effect queries outside this function.

    -- Aside: SQLite by default *does not enable foreign key checks*
    -- (disabling foreign keys is only necessary for those who specifically enable them).
    let settings = appSettings app
    sqliteConn <- rawConnection (sqlDatabase $ appDatabaseConf settings)
    disableForeignKeys sqliteConn

    let logFunc = messageLoggerSource app (appLogger app)
    pool <- runLoggingT (createSqlPool (wrapConnection sqliteConn) 1) logFunc

    flip runSqlPersistMPool pool $ do
        tables <- getTables
        sqlBackend <- ask
        let queries = map (\t -> "DELETE FROM " ++ (connEscapeName sqlBackend $ DBName t)) tables
        forM_ queries (\q -> rawExecute q [])

rawConnection :: Text -> IO Sqlite.Connection
rawConnection = Sqlite.open

disableForeignKeys :: Sqlite.Connection -> IO ()
disableForeignKeys conn = Sqlite.prepare conn "PRAGMA foreign_keys = OFF;" >>= void . Sqlite.step

getTables :: MonadIO m => ReaderT SqlBackend m [Text]
getTables = do
    tables <- rawSql "SELECT name FROM sqlite_master WHERE type = 'table';" []
    return (fmap unSingle tables)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Translations {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Account {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Account() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SciReview.Web.App_LocalResources.Account", typeof(Account).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to I accept the terms and conditions of {0}..
        /// </summary>
        public static string AcceptTermsMessage {
            get {
                return ResourceManager.GetString("AcceptTermsMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Your account has been activated!.
        /// </summary>
        public static string AccountActivatedMessage {
            get {
                return ResourceManager.GetString("AccountActivatedMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Now you can log in with your email address..
        /// </summary>
        public static string AccuntLoginEmailMessage {
            get {
                return ResourceManager.GetString("AccuntLoginEmailMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to There is a registered account with that email, please select a different one..
        /// </summary>
        public static string AlreadyRegisteredAccount {
            get {
                return ResourceManager.GetString("AlreadyRegisteredAccount", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Associate your {0} account.
        /// </summary>
        public static string AssociateAccount {
            get {
                return ResourceManager.GetString("AssociateAccount", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Please enter your email address and personal information to proceed with the registration..
        /// </summary>
        public static string AssociateAccountMessage {
            get {
                return ResourceManager.GetString("AssociateAccountMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Please check your email and follow the instructions to activate your account..
        /// </summary>
        public static string CheckEmalMessage {
            get {
                return ResourceManager.GetString("CheckEmalMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Delete account.
        /// </summary>
        public static string DeleteAccount {
            get {
                return ResourceManager.GetString("DeleteAccount", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Don't have an account?.
        /// </summary>
        public static string DontHaveAccount {
            get {
                return ResourceManager.GetString("DontHaveAccount", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Email sent.
        /// </summary>
        public static string EmailSent {
            get {
                return ResourceManager.GetString("EmailSent", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Forgot your password?.
        /// </summary>
        public static string ForgotPassword {
            get {
                return ResourceManager.GetString("ForgotPassword", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Please check your email to retrieve your password..
        /// </summary>
        public static string ForgotPasswordConfirmMessage {
            get {
                return ResourceManager.GetString("ForgotPasswordConfirmMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Enter your email address in the form below. We'll send a message at that address containing instructions to reset your password..
        /// </summary>
        public static string ForgotPasswordMessage {
            get {
                return ResourceManager.GetString("ForgotPasswordMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Go to login page.
        /// </summary>
        public static string GoToLoginPage {
            get {
                return ResourceManager.GetString("GoToLoginPage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Login failure.
        /// </summary>
        public static string LoginFailure {
            get {
                return ResourceManager.GetString("LoginFailure", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unsuccessful login with service..
        /// </summary>
        public static string LoginFailureMessage {
            get {
                return ResourceManager.GetString("LoginFailureMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Login information.
        /// </summary>
        public static string LoginInfo {
            get {
                return ResourceManager.GetString("LoginInfo", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Login with your email.
        /// </summary>
        public static string LoginWithEmail {
            get {
                return ResourceManager.GetString("LoginWithEmail", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to We cannot log you in right now. Try to login from a new browser window or clearing your cookies. If the problem persist, please try again later..
        /// </summary>
        public static string OpenIDCannotLogin {
            get {
                return ResourceManager.GetString("OpenIDCannotLogin", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Password change.
        /// </summary>
        public static string PasswordChange {
            get {
                return ResourceManager.GetString("PasswordChange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Your password has been changed..
        /// </summary>
        public static string PasswordChangeMessage {
            get {
                return ResourceManager.GetString("PasswordChangeMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Personal information.
        /// </summary>
        public static string PersonalInfo {
            get {
                return ResourceManager.GetString("PersonalInfo", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Register with your email address.
        /// </summary>
        public static string RegisterWithEmail {
            get {
                return ResourceManager.GetString("RegisterWithEmail", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Remember me.
        /// </summary>
        public static string RememberMe {
            get {
                return ResourceManager.GetString("RememberMe", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to We've sent a confirmation email to.
        /// </summary>
        public static string SentEmailMessage {
            get {
                return ResourceManager.GetString("SentEmailMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Thanks for your registration!.
        /// </summary>
        public static string ThankYouRegistration {
            get {
                return ResourceManager.GetString("ThankYouRegistration", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unable to change your password. Make sure that your current password is correct..
        /// </summary>
        public static string UnableChangePassword {
            get {
                return ResourceManager.GetString("UnableChangePassword", resourceCulture);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{ ctrl.title }}

        <form role="form" class="search-pf has-button">

              Search
              <input type="text"  name="selectGroup"
                                  class="form-control combobox"
                                  id="select-build-group"
                                  placeholder="Enter build group name to search..."
                                  autocomplete="off"
                                  ng-model="ctrl.input"
                                  uib-typeahead="group as group.name for group in ctrl.fetchGroups($viewValue)"
                                  typeahead-on-select="ctrl.onSelect($item, $model, $label)"
                                  typeahead-wait-ms="300"
                                  typeahead-loading="ctrl.isLoading">
              <button type="button" class="clear" aria-hidden="true"></button>

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

        </form>

        <pf-list-view class="list-group list-view-pf list-view-pf-view"
                          id="build-group-list"
                          config="ctrl.config"
                          items="ctrl.selected"
                          action-buttons="ctrl.actionButtons">

                {{item.name}}

        </pf-list-view>

      <button class="btn btn-primary" type="button" ng-click="ctrl.save()">Save</button>
      <button class="btn btn-default" type="button" ng-click="ctrl.close()">Cancel</button>


text:
require 'spec_helper'
module Gisele
  class VM
    class Bytecode
      describe Builder, "to_a" do

        let(:builder){ Builder.new(namespace) }

        before do
          builder.at(:s0) do |b|
            b.then :s1
          end
          builder.at(:s1) do |b|
            b.push 12
          end
        end

        context 'without namespace' do
          let(:namespace){ nil }

          it 'returns blocks' do
            expected = [ :gvm,
              [:block, :s0, [:then, :s1]],
              [:block, :s1, [:push, 12 ]],
            ]
            builder.to_a.should eq(expected)
          end

          it 'returns valid bytecode' do
            (Grammar === builder.to_a).should be_true
          end
        end

        context 'without namespace' do
          let(:namespace){ 'Somewhere' }

          it 'uses namespaced labels' do
            expected = [ :gvm,
              [:block, :Somewhere_s0, [:then, :Somewhere_s1]],
              [:block, :Somewhere_s1, [:push, 12 ]],
            ]
            builder.to_a.should eq(expected)
          end

          it 'returns valid bytecode' do
            (Grammar === builder.to_a).should be_true
          end
        end

      end
    end
  end
end


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{#common.title}</title>

<link rel="stylesheet" type="text/css" href="../../css/index.php?type=im&theme=im&package=core_css" />

{#common.filter}

<input type="text" id="filter" name="filter" value="" />

{#common.directory}

{#common.createdir}

{#common.upload}

{#common.refresh}

{#panel.categories}

{#panel.folders}

{#common.loading}

{#common.page}

				<input type="text" id="curpage" name="curpage" value="1" />

{#common.of}

15

{#common.loading}

				<form action="#action" name="listOptions">
				{#view.mode}
					<select name="selectView" id="selectView">
						<option value="text">{#view.textlist}</option>
						<option value="thumbs" selected="selected">{#view.thumbnail}</option>
					</select>, <select name="setPages" id="setPages">
									<option value="25">25</option>
									<option value="50">50</option>
									<option value="100">100</option>
								</select> {#view.images_per_page}
				</form>


text:
<?php

final class PhageAgentTestCase extends PhutilTestCase {

  public function testPhagePHPAgent() {
    return $this->runBootloaderTests(new PhagePHPAgentBootloader());
  }

  private function runBootloaderTests(PhageAgentBootloader $boot) {
    $name = get_class($boot);

    $exec = new ExecFuture('%C', $boot->getBootCommand());
    $exec->write($boot->getBootSequence(), $keep_open = true);

    $exec_channel = new PhutilExecChannel($exec);
    $agent = new PhutilJSONProtocolChannel($exec_channel);

    $agent->write(
      array(
        'type'    => 'EXEC',
        'key'     => 1,
        'command' => 'echo phage',
        'timeout' => null,
      ));

    $this->agentExpect(
      $agent,
      array(
        'type'    => 'RSLV',
        'key'     => 1,
        'err'     => 0,
        'stdout'  => "phage\n",
        'stderr'  => '',
        'timeout' => false,
      ),
      pht("'%s' for %s", 'echo phage', $name));

    $agent->write(
      array(
        'type'    => 'EXIT',
      ));
  }

  private function agentExpect(PhutilChannel $agent, $expect, $what) {
    $message = $agent->waitForMessage();
    $this->assertEqual($expect, $message, $what);
  }

}


text:
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('fdbl-/daterangepicker', 'Integration | Component | fdbl /daterangepicker', {
  integration: true
});

test('it renders', function(assert) {

  this.set('model', Ember.Object.create({'p':{}}));

  this.render(hbs`{{fdbl-/daterangepicker model=model property='p'}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#fdbl-/daterangepicker model=model property='p'}}
      template block text
    {{/fdbl-/daterangepicker}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});

test('it hides the builtin label tag', function(assert) {

  this.set('model', Ember.Object.create({'p':{}}));

  this.render(hbs`{{fdbl-/daterangepicker model=model property='p'}}`);

  assert.equal(this.$("label").length, 1);

});


text:
package de.drippinger.util;

import de.drippinger.repository.StopWordRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.UrlValidator;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
import java.util.Set;

/**
 * Stop Word logic.
 *
 * @author Dennis Rippinger
 */
@Slf4j
@Named
public class StopWords {

	@Inject
	private StopWordRepository stopWordRepository;

	private Set<String> stopWords;

	private Set<String> locations;

	private List<String> regexs;

	private EmailValidator emailValidator = EmailValidator.getInstance();

	private UrlValidator urlValidator = UrlValidator.getInstance();

	/**
	 * Inits the class.
	 */
	@PostConstruct
	public void init() {
		stopWords = stopWordRepository.findAllStopWords();
		locations = stopWordRepository.findAllLocations();
		regexs = stopWordRepository.findAllRegex();

	}

	/**
	 * Is token applicable boolean.
	 *
	 * @param token the token
	 * @return the boolean
	 */
	public boolean isTokenApplicable(String token) {

		return token.length() > 1
			&& !stopWords.contains(token.toLowerCase())
			&& !locations.contains(token.toLowerCase())
			&& !containsAlphabetic(token)
			&& !StringUtils.isAlphanumericSpace(token)
			&& !emailValidator.isValid(token)
			&& !urlValidator.isValid(token)
			&& !matchesRegex(token);

	}

	private boolean containsAlphabetic(String token) {
		if (token == null) {
			return false;
		} else {
			int sz = token.length();

			for (int i = 0; i < sz; ++i) {
				if (!Character.isAlphabetic(token.codePointAt(i))) {
					return false;
				}
			}

			return true;
		}
	}

	private boolean matchesRegex(String token) {
		for (String regex : regexs) {
			if (token.matches(regex)) {
				return true;
			}
		}
		return false;
	}

}


text:
<form class="form-horizontal" action="index.php" method="get">
    <input type="hidden" name="p" value="home">
    <input type="hidden" name="c" value="checkDispo">

        <?php _t("Fecha de inicio"); ?>

            <input type="date" class="form-control" id="fi"  name="fi" placeholder="aaa-mm-dd" value="">

        <?php _t("Fecha de fin"); ?>

            <input type="date" class="form-control" id="ff" name="ff"placeholder="aa-mm-dd" value="">

        <?php _t("Horario"); ?>

            <select class="form-control" name="hi">
                <option value="25200">07h00 - 12h00</option>
                <option value="46800">13h00 - 24h00</option>
            </select>

            <button type="submit" class="btn btn-default"><?php _t("Verificar disponibilidad"); ?></button>

</form>


text:
import { Router } from './router';
import { AdminController } from '../controller/admin.controller';

export class AdminRouter extends Router {
    config() {
        let entityName = 'admin';
        let root = '/' + entityName;
        let controller = new AdminController(entityName);
        this.api.post(root + '/query-by-username-and-password', controller.queryByUsernameAndPassword.bind(controller));
        this.api.get(root, controller.find.bind(controller));
        this.api.get(root + '/:id', controller.findById.bind(controller));
        this.api.post(root, controller.create.bind(controller));
        this.api.put(root + '/:id', controller.update.bind(controller));
        this.api.del(root + '/:id', controller.destroyById.bind(controller));
    }
}


text:
namespace C42A.CAB42.Windows.Forms
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    public partial class RegistryKeyValueEditForm : Form
    {
        private RegistryKeyValue includeRule;

        public RegistryKeyValueEditForm()
        {
            this.InitializeComponent();
        }
        public RegistryKeyValue Value
        {
            get
            {
                return this.includeRule;
            }

            set
            {
                this.includeRule = value;

                if (value != null)
                {
                    this.tbName.Text = value.Name;
                }
                else
                {
                    this.tbName.Text = string.Empty;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.tbName.Text))
                {
                    MessageBox.Show(this, "The name must not be empty", this.Text);
                    return;
                }

                if (this.includeRule == null)
                {
                    this.includeRule = new RegistryKeyValue();
                }

                this.includeRule.Name = this.tbName.Text;
                this.includeRule.Type = this.GetValueType();
                this.includeRule.Value = this.GetFormatedValue(this.includeRule.Type, this.tbValue.Text);

                this.Close(DialogResult.OK);
            }
            catch (Exception x)
            {
                MessageBox.Show(this, x.Message, "Saving changes");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close(DialogResult.Cancel);
        }

        private void Close(System.Windows.Forms.DialogResult dialogResult)
        {
            this.DialogResult = dialogResult;

            this.Close();
        }

        private void UserVariableEditForm_Load(object sender, EventArgs e)
        {

        }

        private Cabwiz.RegistryValueTypes GetValueType()
        {
            var types = new Cabwiz.RegistryValueTypes[] {
                Cabwiz.RegistryValueTypes.String,
                Cabwiz.RegistryValueTypes.BINARY,
                Cabwiz.RegistryValueTypes.DWORD,
                Cabwiz.RegistryValueTypes.MULTI_SZ
            };

            if (this.comboBox1.SelectedIndex > -1 && this.comboBox1.SelectedIndex < types.Length)
            {
                return types[this.comboBox1.SelectedIndex];
            }
            else
            {
                return default(Cabwiz.RegistryValueTypes);
            }
        }

        private string GetFormatedValue(Cabwiz.RegistryValueTypes type, string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            switch (type)
            {
                case Cabwiz.RegistryValueTypes.SZ:
                case Cabwiz.RegistryValueTypes.MULTI_SZ:
                    return value;

                case Cabwiz.RegistryValueTypes.DWORD:
                    {
                        int nValue;

                        var invariant = System.Globalization.CultureInfo.InvariantCulture;

                        var cultures = new System.IFormatProvider[] {
                            System.Globalization.CultureInfo.CurrentUICulture,
                            invariant
                        };

                        foreach (var culture in cultures)
                        {
                            if (int.TryParse(value, System.Globalization.NumberStyles.Integer, culture, out nValue))
                            {
                                return nValue.ToString(invariant);
                            }
                        }

                        // If we have reached this point, no parse was successful. Whine a bit.
                        throw new FormatException("The value could not a well-formatted 32-bit integer.");
                    }

                case Cabwiz.RegistryValueTypes.BINARY:
                    {
                        throw new NotSupportedException("BINARY data types are not yet supported by the visual editor.");
                    }

                default:
                    {
                        throw new ArgumentOutOfRangeException("type");
                    }
            }
        }
    }
}


text:
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def _recover(self, root):
        if not root: return None, None

        lmin, lmax = self._recover(root.left)
        if not lmin: lmin, lmax = root, root
        rmin, rmax = self._recover(root.right)
        if not rmin: rmin, rmax = root, root

        # do not need recover
        if (lmin.val <= root.val and lmax.val <= root.val
            and rmin.val >= root.val and rmax.val >= root.val):
            return lmin, rmax

        # recover
        if lmax.val > root.val:
            lmax.val, root.val = root.val, lmax.val
            self._recover(root.left)
        if rmin.val < root.val:
            rmin.val, root.val = root.val, rmin.val
            self._recover(root.right)
        if lmax.val > root.val:
            lmax.val, root.val = root.val, lmax.val
            self._recover(root.left)

        return lmin, rmax

    # @param root, a tree node
    # @return a tree node
    def recoverTree(self, root):
        self._recover(root)
        return root

if __name__ == '__main__':
    s = Solution()
    root = TreeNode(1)
    assert root.val == s.recoverTree(root).val

    left = TreeNode(0)
    root.left = left
    assert root.val == s.recoverTree(root).val

    right = TreeNode(2)
    root.right = right
    assert root.val == s.recoverTree(root).val

    root.left = right
    root.right = left
    s.recoverTree(root)
    assert root.val == s.recoverTree(root).val

    root = TreeNode(3)
    right = TreeNode(2)
    root.right = right
    rr = TreeNode(1)
    right.right = rr
    root = s.recoverTree(root)
    assert 1 == root.val
    assert 2 == root.right.val
    assert 3 == root.right.right.val


text:
package darkly

import "strconv"

const _ChunkType_name = "ChunkEOFChunkEOLChunkSpaceChunkText"

var _ChunkType_index = [...]uint8{0, 8, 16, 26, 35}

func (i ChunkType) String() string {
	if i < 0 || i >= ChunkType(len(_ChunkType_index)-1) {
		return "ChunkType(" + strconv.FormatInt(int64(i), 10) + ")"
	}
	return _ChunkType_name[_ChunkType_index[i]:_ChunkType_index[i+1]]
}


text:
using System;
using System.ComponentModel.Composition;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
using GitHub.App;
using GitHub.Extensions;
using GitHub.Extensions.Reactive;
using GitHub.Logging;
using GitHub.Models;
using GitHub.Primitives;
using GitHub.Services;
using Octokit;
using ReactiveUI;
using Serilog;

namespace GitHub.ViewModels.Dialog
{
    [Export(typeof(IForkRepositorySwitchViewModel))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class ForkRepositorySwitchViewModel : ViewModelBase, IForkRepositorySwitchViewModel
    {
        readonly IRepositoryForkService repositoryForkService;

        [ImportingConstructor]
        public ForkRepositorySwitchViewModel(IRepositoryForkService repositoryForkService)
        {
            this.repositoryForkService = repositoryForkService;

            SwitchFork = ReactiveCommand.CreateFromObservable(OnSwitchFork);
        }

        public RepositoryModel SourceRepository { get; private set; }

        public RepositoryModel DestinationRepository { get; private set; }

        public ReactiveCommand<Unit, Unit> SwitchFork { get; }

        public string Title => Resources.SwitchOriginTitle;

        public IObservable<object> Done => SwitchFork.Where(value => value != null).SelectNull();

        public void Initialize(LocalRepositoryModel sourceRepository, RemoteRepositoryModel remoteRepository)
        {
            SourceRepository = sourceRepository;
            DestinationRepository = remoteRepository;
        }

        IObservable<Unit> OnSwitchFork()
        {
            return repositoryForkService.SwitchRemotes(DestinationRepository, UpdateOrigin, AddUpstream, ResetMasterTracking);
        }

        bool resetMasterTracking = true;
        public bool ResetMasterTracking
        {
            get { return resetMasterTracking; }
            set { this.RaiseAndSetIfChanged(ref resetMasterTracking, value); }
        }

        bool addUpstream = true;
        public bool AddUpstream
        {
            get { return addUpstream; }
            set { this.RaiseAndSetIfChanged(ref addUpstream, value); }
        }

        bool updateOrigin = true;
        public bool UpdateOrigin
        {
            get { return updateOrigin; }
            set { this.RaiseAndSetIfChanged(ref updateOrigin, value); }
        }
    }
}


text:
require 'rails_helper'

RSpec.describe ReportsController, type: :controller do
  login_user

  describe 'GET #current' do
    it 'redirects to current report' do
      expect(Report.current.id).to eq 1
      get :current
      expect(response).to redirect_to '/reports/present/1'
    end

    context 'no reports' do
      it 'renders a replacement template' do
        Report.destroy_all
        get :current
        expect(response).to render_template :no_reports
      end
    end
  end

  describe '#show' do
    it 'assigns the correct report' do
      create(:report, id: 42)
      get :show, params: { report_id: 42 }
    end
  end

  describe 'GET #present' do
    it "renders template 'present'" do
      expect(Report.current.id).to eq 1
      get :present, params: {report_id: 1}
      expect(response).to render_template :present
    end

    it "assigns the diary entries that belong to the report" do
      report = create(:report)
      expected = create(:diary_entry, report: report)
      not_expected = create(:diary_entry)
      get :present, params: {report_id: report.id}
      diary_entries = assigns(:diary_entries)
      expect(diary_entries).to include(expected)
      expect(diary_entries).not_to include(not_expected)
    end
  end
end


text:
package org.diirt.datasource.formula.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.diirt.datasource.formula.FormulaFunction;

import org.diirt.vtype.VString;
import org.diirt.vtype.VStringArray;
import org.diirt.vtype.ValueFactory;
import org.diirt.vtype.ValueUtil;

/**
 * @author shroffk
 *
 */
class ArrayOfStringFormulaFunction implements FormulaFunction {

    @Override
    public boolean isPure() {
        return true;
    }

    @Override
    public boolean isVarArgs() {
        return true;
    }

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

    @Override
    public String getDescription() {
        return "Constructs array from a series of string";
    }

    @Override
    public List<Class<?>> getArgumentTypes() {
        return Arrays.<Class<?>> asList(VString.class);
    }

    @Override
    public List<String> getArgumentNames() {
        return Arrays.asList("strArgs");
    }

    @Override
    public Class<?> getReturnType() {
        return VStringArray.class;
    }

    @Override
    public Object calculate(List<Object> args) {

        List<String> data = new ArrayList<>();
        for (Object arg : args) {
            VString str = (VString) arg;
            if (str == null || str.getValue() == null)
                data.add(null);
            else
                data.add(str.getValue());
        }

        return ValueFactory.newVStringArray(data,
                ValueUtil.highestSeverityOf(args, false),
                ValueUtil.latestValidTimeOrNowOf(args));
    }

}


text:
<resources>
    <string name="app_name">Lock_prototype_1</string>
    <string name="Submit_Button">Submit</string>
    <string name="clear">Clear</string>

    <string name="i_newPw">true</string>

    <string name="enable_Lockscreen">Enable Lockscreen</string>
    <string name="disable_Lockscreen">Disable Lockscreen</string>

    <string name="resetPassword">Reset Password</string>
    <string name="passwordAlready">Password Created, Use Change Password</string>

    <string name="filename">password.json</string>
    <string name="pwTag">password</string>
    <string name="lengthTag">length</string>

    <string name="checkPw">Enter Current Password</string>
    <string name="checkPw_confirm">not_true</string>
    <string name="change_pw">Enter New Password</string>
    <string name="enter_pw">Enter Password</string>
    <string name="actionBar">true</string>
    <string name="attempts">3</string>
    <string name="testTitle">Testing Password</string>
    <string name="attemptTitle">Attempt: </string>
    <string name="settingsScreen">Lock.Paint Settings</string>

    <string name="createPwWarn">Please Create a Password First</string>

    <string name="changePwOpt">Change Password</string>
    <string name="enablePwOpt">Enable Password</string>
    <string name="disablePwOpt">Disable Password</string>
    <string name="testPwOpt">Test Password</string>
    <string name="createPwOpt">Create Password</string>
</resources>


text:
<?php
/**
 * User: Zachary Tong
 * Date: 2/12/13
 * Time: 9:29 PM
 */

namespace Sherlock\responses;

/**
 * Class IndexResponse
 * @package Sherlock\responses
 */
class IndexResponse extends Response
{
    /**
     * @var int
     */
    public $ok;

    /**
     * @var int
     */
    public $acknowledged;

    /**
     * @param \Sherlock\common\tmp\RollingCurl\Request $response
     */
    public function __construct($response)
    {
        parent::__construct($response);

        if (isset($this->responseData['ok'])) {
            $this->ok = $this->responseData['ok'];
        }

        if (isset($this->responseData['acknowledged'])) {
            $this->acknowledged = $this->responseData['acknowledged'];
        }
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>jp.bananafish.spark</groupId>
	<artifactId>sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>sample</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-core_2.10</artifactId>
			<version>1.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.spark</groupId>
			<artifactId>spark-sql_2.10</artifactId>
			<version>1.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.5</version>
		</dependency>
		<dependency>
			<groupId>net.lingala.zip4j</groupId>
			<artifactId>zip4j</artifactId>
			<version>1.3.2</version>
		</dependency>
	</dependencies>
</project>


text:
package cqrs.publicserver

import java.net.URLEncoder
import java.util.UUID

import cats.Traverse
import cqrs.queries._
import cqrs.commands.{AddRecord, CreateMeter, MeterCreated, StoredEvent}
import play.api.libs.ws.WSClient
import play.api.routing.{Router => PlayRouter}
import cats.instances.option._
import cats.instances.future._
import endpoints.play.server.{JsonEntitiesFromCodec, Endpoints, OptionalResponses, PlayComponents}

import scala.concurrent.Future
import scala.util.Try

/**
  * Implementation of the public API based on our "commands" and "queries" microservices.
  */
class PublicServer(
  commandsBaseUrl: String,
  queriesBaseUrl: String,
  wsClient: WSClient,
  protected val playComponents: PlayComponents
) extends PublicEndpoints
    with Endpoints
    with JsonEntitiesFromCodec
    with OptionalResponses {

  import playComponents.executionContext

  private val commandsClient = new CommandsClient(commandsBaseUrl, wsClient)
  //#invocation
  private val queriesClient = new QueriesClient(queriesBaseUrl, wsClient)
  //#invocation

  val routes: PlayRouter.Routes =
    routesFromEndpoints(

      listMeters.implementedByAsync { _ =>
        //#invocation
        val metersList: Future[ResourceList] = queriesClient.query(FindAll)
        //#invocation
        metersList.map(_.value)
      },

      getMeter.implementedByAsync { id =>
        queriesClient.query(FindById(id, None)).map(_.value)
      },

      createMeter.implementedByAsync { createData =>
        //#microservice-endpoint-invocation
        val eventuallyMaybeEvent: Future[Option[StoredEvent]] =
          commandsClient.command(CreateMeter(createData.label))
        //#microservice-endpoint-invocation
        for {
          maybeEvent <- eventuallyMaybeEvent
          maybeMeter <- Traverse[Option].flatSequence(
            maybeEvent.collect {
              case StoredEvent(t, MeterCreated(id, _)) =>
                //#invocation-find-by-id
                val maybeMeter: Future[MaybeResource] = queriesClient.query(FindById(id, after = Some(t)))
                //#invocation-find-by-id
                maybeMeter.map(_.value)
            }
          )
          meter <- maybeMeter.fold[Future[Meter]](Future.failed(new NoSuchElementException))(Future.successful)
        } yield meter
      },

      addRecord.implementedByAsync { case (id, addData) =>
        for {
          maybeEvent <- commandsClient.command(AddRecord(id, addData.date, addData.value))
          findMeter = (evt: StoredEvent) => queriesClient.query(FindById(id, after = Some(evt.timestamp))).map(_.value)
          maybeMeter <- Traverse[Option].flatTraverse(maybeEvent)(findMeter)
          meter <- maybeMeter.fold[Future[Meter]](Future.failed(new NoSuchElementException))(Future.successful)
        } yield meter
      }

    )

  //#segment-uuid
  implicit lazy val uuidSegment: Segment[UUID] =
    new Segment[UUID] {
      def decode(segment: String): Option[UUID] = Try(UUID.fromString(segment)).toOption
      def encode(uuid: UUID): String = URLEncoder.encode(uuid.toString, utf8Name)
    }
  //#segment-uuid

  // These aliases are probably due to a limitation of circe
  implicit private def circeEncoderReq: io.circe.Encoder[QueryReq] = QueryReq.queryEncoder
  implicit private def circeDecoderResp: io.circe.Decoder[QueryResp] = QueryResp.queryDecoder

}


text:
package com.opengamma.maths.lowlevelapi.datatypes.primitive;

import java.util.Arrays;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.maths.lowlevelapi.functions.utilities.Max;

/**
 * Converts, or instantiates, a matrix to Compressed Sparse Row format (CSR). CSR is a near optimal method of storing sparse matrix data.
 * Only the non-zero components of the matrix are stored (note: there is no tolerance for testing zero to machine precision, zero is solely tested bitwise).
 * The CSR format requires three vectors:
 *  colIdx - contains column indexes of elements
 *  rowPtr - contains the row pointer information used to reassemble the colIdx references in the correct place within the matrix
 *  values - contains the nonzero values of the sparse matrix in row-major order
 *
 *  For an example call and output see the unit test.
 *
 *  A "normal" path to CSR form is via the {@link SparseCoordinateFormatMatrix} this formatting path is taken to allow access to the
 *  Compressed Sparse Column (CSC) format with equal ease.
 *  The final format chosen (CSR or CSC) should reflect the cache optimal access pattern of the calling function data.
 */

public class CompressedSparseRowFormatMatrix extends SparseMatrixType {

  private double[] _values;
  private int[] _colIdx;
  private int[] _rowPtr;
  private int _els;
  private int _rows;
  private int _cols;
  private int _maxEntriesInARow; // used to decide whether 16bit ints can be used as index later

  /* constructors */

  /**
   * Construct from DoubleMatrix2D type
   * @param m is a DoubleMatrix2D
   */
  public CompressedSparseRowFormatMatrix(DoubleMatrix2D m) {
    Validate.notNull(m);

    //get number of elements
    _els = m.getNumberOfElements();

    // tmp arrays, in case we get in a fully populated matrix, intelligent design upstream should ensure that this is overkill!
    double[] dataTmp = new double[_els];
    int[] colIndTmp = new int[_els];
    int[] rowPtrTmp = new int[_els + 1];

    // we need unwind the array m into coordinate form
    int localmaxEntriesInARow;
    _maxEntriesInARow = -1; // set max entries in a row negative, so that maximiser will work
    int ptr = 0;
    int i;
    for (i = 0; i < m.getNumberOfRows(); i++) {
      rowPtrTmp[i] = ptr;
      localmaxEntriesInARow = 0;
      for (int j = 0; j < m.getNumberOfColumns(); j++) {
        if (Double.doubleToLongBits(m.getEntry(i, j)) != 0L) {
          localmaxEntriesInARow++;
          colIndTmp[ptr] = j;
          dataTmp[ptr] = m.getEntry(i, j);
          ptr++;
        }
      }
      if (localmaxEntriesInARow > _maxEntriesInARow) { // is the number of entries on this row the largest?
        _maxEntriesInARow = localmaxEntriesInARow;
      }
    }
    rowPtrTmp[i] = ptr;

    // return correct 0 to correct length of the vector buffers
    _values = Arrays.copyOfRange(dataTmp, 0, ptr);
    _colIdx = Arrays.copyOfRange(colIndTmp, 0, ptr);
    _rowPtr = Arrays.copyOfRange(rowPtrTmp, 0, i + 1); // yes, the +1 is correct, it allows the computation of the number of elements in the final row!
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
  }

  /**
   * Construct from SparseCoordinateFormatMatrix type
   * @param m is a SparseCoordinateFormatMatrix
   */
  public CompressedSparseRowFormatMatrix(SparseCoordinateFormatMatrix m) {
    Validate.notNull(m);
    _els = m.getNumberOfElements();
    int[] rowPtrTmp = new int[_els > 1 ? _els : 2];
    int localmaxEntriesInARow;
    _maxEntriesInARow = -1; // set max entries in a row negative, so that maximiser will work
    int ptr = 0;
    int i;
    for (i = 0; i < m.getNumberOfRows(); i++) {
      rowPtrTmp[i] = ptr;
      localmaxEntriesInARow = 0;
      for (int j = 0; j < m.getNumberOfColumns(); j++) {
        if (Double.doubleToLongBits(m.getEntry(i, j)) != 0L) {
          localmaxEntriesInARow++;
          ptr++;
        }
      }
      if (localmaxEntriesInARow > _maxEntriesInARow) { // is the number of entries on this row the largest?
        _maxEntriesInARow = localmaxEntriesInARow;
      }
    }
    rowPtrTmp[i] = ptr;
    _values = Arrays.copyOfRange(m.getNonZeroEntries(), 0, ptr);
    _colIdx = Arrays.copyOfRange(m.getColumnCoordinates(), 0, ptr);
    _rowPtr = Arrays.copyOfRange(rowPtrTmp, 0, i + 1); // yes, the +1 is correct!
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
  }

  /**
   * Construct from a (double) array of arrays
   * @param m is a (double) array of arrays
   */
  public CompressedSparseRowFormatMatrix(double[][] m) {
    this(new DoubleMatrix2D(m));
  }

  /**
   * Construct from coordinate inputs
   * @param x x-coordinates of data points
   * @param y y-coordinates of data points
   * @param values value of data points
   */
  public CompressedSparseRowFormatMatrix(int[] x, int[] y, double[] values) {
    this(new SparseCoordinateFormatMatrix(x, y, values, (Max.value(y) + 1), (Max.value(x) + 1)));
  }

  /**
   * Construct from coordinate inputs
   * @param x x-coordinates of data points
   * @param y y-coordinates of data points
   * @param values value of data points
   * @param m the number of rows the CSR matrix should have
   * @param n the number of columns the CSR matrix should have
   */
  public CompressedSparseRowFormatMatrix(int[] x, int[] y, double[] values, int m, int n) {
    this(new SparseCoordinateFormatMatrix(x, y, values, m, n));
  }

  /* methods */

  /**
   *  Gets the column indexes that can be looked up by the row pointer
   *  @return _colIdx, the column indexes
   */
  public int[] getColumnIndex() {
    return _colIdx;
  }

  /**
   * Gets the row pointer (not actually a pointer, but would be in C)
   * @return _rowPtr, the row pointer
   */
  public int[] getRowPtr() {
    return _rowPtr;
  }

  /**
   * Gets the non-zero values in the matrix, i.e. the values that are worth storing
   * @return _values, the non-zero values
   */
  public double[] getNonZeroElements() {
    return _values;
  }

  /**
   * Gets the non-zero values in the matrix, i.e. the values that are worth storing.
   * Method is for unity with other matrix types and simply redirects to getNonZeroElements();
   * @return _values, the non-zero values
   */
  public double[] getData() {
    return getNonZeroElements();
  }

  /**
   * Gets the number of rows in the matrix (is not equal to count(unique(rowPtr)) as matrix could be singular/have row of zeros))
   * @return _rows, the number of rows corresponding to a full matrix representation of the compressed matrix
   */
  @Override
  public int getNumberOfRows() {
    return _rows;
  }

  /**
   * Gets the number of columns in the matrix (is not equal to count(unique(colIdx)) as matrix could be singular/have column of zeros))
   * @return _cols, the number of columns corresponding to a full matrix representation of the compressed matrix
   */
  @Override
  public int getNumberOfColumns() {
    return _cols;
  }

  /**
   * Gets the number of non-zero elements in the matrix
   * @return _values.length, the number of non-zero elements in the matrix
   */
  public int getNumberOfNonzeroElements() {
    return _values.length;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int getMaxNonZerosInSignificantDirection() {
    return _maxEntriesInARow;
  }

  /**
   * Converts matrix to a Full Matrix representation (undoes the sparse compression)
   * @return tmp, a DoubleMatrix2D
   */
  public DoubleMatrix2D toDenseMatrix() {
    return new DoubleMatrix2D(this.toArray());
  }

  /**
   * Converts matrix to a Full Matrix representation (undoes the sparse compression)
   * @return tmp, an array of arrays
   */
  @Override
  public double[][] toArray() {
    double[][] tmp = new double[_rows][_cols];
    for (int ir = 0; ir < _rows; ir++) {
      //translate an index and see if it exists, if it doesn't then return 0
      for (int i = _rowPtr[ir]; i <= _rowPtr[ir + 1] - 1; i++) { // loops through elements of correct row
        tmp[ir][_colIdx[i]] = _values[i];
      }
    }
    return tmp;
  }

  @Override
  public int getNumberOfElements() {
    return _els;
  }

  @Override
  public double[] getFullRow(int index) {
    double[] tmp = new double[_cols];
    for (int i = _rowPtr[index]; i <= _rowPtr[index + 1] - 1; i++) { // loops through elements of correct row
      tmp[_colIdx[i]] = _values[i];
    }
    return tmp;
  }

  @Override
  // column slicing CSR is a nightmare, implemented for completeness, but really not worth actually using unless desperate. Use COO or CSC instead.
  public double[] getFullColumn(int index) {
    double[] tmp = new double[_rows];
    for (int i = 0; i < _rows; i++) {
      tmp[i] = this.getEntry(i, index);
    }
    return tmp;
  }

  @Override
  public double[] getRowElements(int index) {
    double[] tmp = new double[_cols];
    int ptr = 0;
    for (int i = _rowPtr[index]; i <= _rowPtr[index + 1] - 1; i++) { // loops through elements of correct row
      tmp[ptr] = _values[i];
      ptr++;
    }
    return Arrays.copyOfRange(tmp, 0, ptr);
  }

  @Override
  // again, column slicing CSR is a bad idea and essentially requires multiple brute forces. Store the matrix differently if you are thinking about doing this a lot
  public double[] getColumnElements(int index) {
    double[] tmp = new double[_cols];
    double val;
    int ptr = 0;
    for (int i = 0; i < _cols; i++) {
      val = this.getEntry(i, index);
      if (Double.doubleToLongBits(val) != 0) {
        tmp[ptr] = val;
        ptr++;
      }

    }
    return Arrays.copyOfRange(tmp, 0, ptr);
  }

  @Override
  public int getNumberOfNonZeroElements() {
    return _values.length;
  }

  @Override
  public Double getEntry(int... indices) {
    //translate an index and see if it exists, if it doesn't then return 0
    for (int i = _rowPtr[indices[0]]; i <= _rowPtr[indices[0] + 1] - 1; i++) { // loops through elements of correct row
      // looks for col index
      if (_colIdx[i] == indices[1]) {
        return _values[i];
      }
    }
    return 0.0;
  }

  @Override
  public String toString() {
    return "\nvalues=" + Arrays.toString(_values) +
        "\ncolInd=" + Arrays.toString(_colIdx) +
        "\nrowPtr=" + Arrays.toString(_rowPtr) +
        "\nels=" + _els;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(_colIdx);
    result = prime * result + _cols;
    result = prime * result + _els;
    result = prime * result + Arrays.hashCode(_rowPtr);
    result = prime * result + _rows;
    result = prime * result + Arrays.hashCode(_values);
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    CompressedSparseRowFormatMatrix other = (CompressedSparseRowFormatMatrix) obj;
    if (_cols != other._cols) {
      return false;
    }
    if (_rows != other._rows) {
      return false;
    }
    if (!Arrays.equals(_colIdx, other._colIdx)) {
      return false;
    }
    if (!Arrays.equals(_rowPtr, other._rowPtr)) {
      return false;
    }
    if (!Arrays.equals(_values, other._values)) {
      return false;
    }
    return true;
  }

}


text:
require 'spec_helper'

describe Ilmotin::Clients::Hipchat do

  let :response do
    double("response")
  end

  let :"404" do
    resp = response
    resp.stub(:status).return("404")
    resp
  end

  subject do
    Ilmotin::Clients::Hipchat.new("12345-12345", { from: "from", room_id: "room_id" } )
  end

  it "should notify parse correct body for post" do
    subject.send(:parse_body, "Hello World").should ==
      { from: "from", room_id: "room_id", message: "Hello World", notify: 0 }
  end

  %w(from room_id).each do |variable|
    it "should initialize #{variable}" do
     subject.respond_to?(variable.to_sym).should == true
     subject.send(variable.to_sym).should == variable
    end
  end

end


text:
<?php

namespace Propel\Generator\Behavior\I18n;

use Propel\Generator\Exception\EngineException;
use Propel\Generator\Model\Behavior;
use Propel\Generator\Model\ForeignKey;
use Propel\Generator\Model\PropelTypes;
use Propel\Generator\Behavior\Validate\ValidateBehavior;

/**
 * Allows translation of text columns through transparent one-to-many
 * relationship.
 *
 * @author Francois Zaninotto
 */
class I18nBehavior extends Behavior
{
    const DEFAULT_LOCALE = 'en_US';

    // default parameters value
    protected $parameters = array(
        'i18n_table'        => '%TABLE%_i18n',
        'i18n_phpname'      => '%PHPNAME%I18n',
        'i18n_columns'      => '',
        'locale_column'     => 'locale',
        'locale_length'     => 5,
        'default_locale'    => null,
        'locale_alias'      => '',
    );

    protected $tableModificationOrder = 70;

    protected $objectBuilderModifier;

    protected $queryBuilderModifier;

    protected $i18nTable;

    public function modifyDatabase()
    {
        foreach ($this->getDatabase()->getTables() as $table) {
            if ($table->hasBehavior('i18n') && !$table->getBehavior('i18n')->getParameter('default_locale')) {
                $table->getBehavior('i18n')->addParameter(array(
                    'name'  => 'default_locale',
                    'value' => $this->getParameter('default_locale'),
                ));
            }
        }
    }

    public function getDefaultLocale()
    {
        if (!$defaultLocale = $this->getParameter('default_locale')) {
            $defaultLocale = self::DEFAULT_LOCALE;
        }

        return $defaultLocale;
    }

    public function getI18nTable()
    {
        return $this->i18nTable;
    }

    public function getI18nForeignKey()
    {
        foreach ($this->i18nTable->getForeignKeys() as $fk) {
            if ($fk->getForeignTableName() == $this->table->getName()) {
                return $fk;
            }
        }
    }

    public function getLocaleColumn()
    {
        return $this->getI18nTable()->getColumn($this->getLocaleColumnName());
    }

    public function getI18nColumns()
    {
        $columns = array();
        $i18nTable = $this->getI18nTable();
        if ($columnNames = $this->getI18nColumnNamesFromConfig()) {
            // Strategy 1: use the i18n_columns parameter
            foreach ($columnNames as $columnName) {
                $columns []= $i18nTable->getColumn($columnName);
            }
        } else {
            // strategy 2: use the columns of the i18n table
            // warning: does not work when database behaviors add columns to all tables
            // (such as timestampable behavior)
            foreach ($i18nTable->getColumns() as $column) {
                if (!$column->isPrimaryKey()) {
                    $columns []= $column;
                }
            }
        }

        return $columns;
    }

    public function replaceTokens($string)
    {
        $table = $this->getTable();

        return strtr($string, array(
            '%TABLE%'   => $table->getName(),
            '%PHPNAME%' => $table->getPhpName(),
        ));
    }

    public function getObjectBuilderModifier()
    {
        if (null === $this->objectBuilderModifier) {
            $this->objectBuilderModifier = new I18nBehaviorObjectBuilderModifier($this);
        }

        return $this->objectBuilderModifier;
    }

    public function getQueryBuilderModifier()
    {
        if (null === $this->queryBuilderModifier) {
            $this->queryBuilderModifier = new I18nBehaviorQueryBuilderModifier($this);
        }

        return $this->queryBuilderModifier;
    }

    public function staticAttributes($builder)
    {
        return $this->renderTemplate('staticAttributes', array(
            'defaultLocale' => $this->getDefaultLocale(),
        ));
    }

    public function modifyTable()
    {
        $this->addI18nTable();
        $this->relateI18nTableToMainTable();
        $this->addLocaleColumnToI18n();
        $this->moveI18nColumns();
    }

    protected function addI18nTable()
    {
        $table         = $this->getTable();
        $database      = $table->getDatabase();
        $i18nTableName = $this->getI18nTableName();

        if ($database->hasTable($i18nTableName)) {
            $this->i18nTable = $database->getTable($i18nTableName);
        } else {
            $this->i18nTable = $database->addTable(array(
                'name'      => $i18nTableName,
                'phpName'   => $this->getI18nTablePhpName(),
                'package'   => $table->getPackage(),
                'schema'    => $table->getSchema(),
                'namespace' => $table->getNamespace() ? '\\' . $table->getNamespace() : null,
                'skipSql'   => $table->isSkipSql()
            ));

            // every behavior adding a table should re-execute database behaviors
            foreach ($database->getBehaviors() as $behavior) {
                $behavior->modifyDatabase();
            }
        }
    }

    protected function relateI18nTableToMainTable()
    {
        $table     = $this->getTable();
        $i18nTable = $this->i18nTable;
        $pks       = $this->getTable()->getPrimaryKey();

        if (count($pks) > 1) {
            throw new EngineException('The i18n behavior does not support tables with composite primary keys');
        }

        foreach ($pks as $column) {
            if (!$i18nTable->hasColumn($column->getName())) {
                $column = clone $column;
                $column->setAutoIncrement(false);
                $i18nTable->addColumn($column);
            }
        }

        if (in_array($table->getName(), $i18nTable->getForeignTableNames())) {
            return;
        }

        $fk = new ForeignKey();
        $fk->setForeignTableCommonName($table->getCommonName());
        $fk->setForeignSchemaName($table->getSchema());
        $fk->setDefaultJoin('LEFT JOIN');
        $fk->setOnDelete(ForeignKey::CASCADE);
        $fk->setOnUpdate(ForeignKey::NONE);

        foreach ($pks as $column) {
            $fk->addReference($column->getName(), $column->getName());
        }

        $i18nTable->addForeignKey($fk);
    }

    protected function addLocaleColumnToI18n()
    {
        $localeColumnName = $this->getLocaleColumnName();

        if (! $this->i18nTable->hasColumn($localeColumnName)) {
            $this->i18nTable->addColumn(array(
                'name'       => $localeColumnName,
                'type'       => PropelTypes::VARCHAR,
                'size'       => $this->getParameter('locale_length') ? (int) $this->getParameter('locale_length') : 5,
                'default'    => $this->getDefaultLocale(),
                'primaryKey' => 'true',
            ));
        }
    }

    /**
     * Moves i18n columns from the main table to the i18n table
     */
    protected function moveI18nColumns()
    {
        $table     = $this->getTable();
        $i18nTable = $this->i18nTable;

        $i18nValidateParams = array();
        foreach ($this->getI18nColumnNamesFromConfig() as $columnName) {
            if (!$i18nTable->hasColumn($columnName)) {
                if (!$table->hasColumn($columnName)) {
                    throw new EngineException(sprintf('No column named %s found in table %s', $columnName, $table->getName()));
                }

                $column = $table->getColumn($columnName);
                // add the column
                $i18nColumn = $i18nTable->addColumn(clone $column);

                //validate behavior: move rules associated to the column
                if ($table->hasBehavior('validate')) {
                    $validateBehavior = $table->getBehavior('validate');
                    $params = $validateBehavior->getParametersFromColumnName($columnName);
                    $i18nValidateParams = array_merge($i18nValidateParams, $params);
                    $validateBehavior->removeParametersFromColumnName($columnName);
                }
                // FIXME: also move FKs, and indices on this column
            }

            if ($table->hasColumn($columnName)) {
                $table->removeColumn($columnName);
            }
        }

        //validate behavior
        if (count($i18nValidateParams) > 0) {
            $i18nVbehavior = new ValidateBehavior();
            $i18nVbehavior->setName('validate');
            $i18nVbehavior->setParameters($i18nValidateParams);
            $i18nTable->addBehavior($i18nVbehavior);

            //current table must have almost 1 validation rule
            $validate = $table->getBehavior('validate');
            $validate->addRuleOnPk();
        }
    }

    protected function getI18nTableName()
    {
        return $this->replaceTokens($this->getParameter('i18n_table'));
    }

    protected function getI18nTablePhpName()
    {
        return $this->replaceTokens($this->getParameter('i18n_phpname'));
    }

    protected function getLocaleColumnName()
    {
        return $this->replaceTokens($this->getParameter('locale_column'));
    }

    protected function getI18nColumnNamesFromConfig()
    {
        $columnNames = explode(',', $this->getParameter('i18n_columns'));
        foreach ($columnNames as $key => $columnName) {
            if ($columnName = trim($columnName)) {
                $columnNames[$key] = $columnName;
            } else {
                unset($columnNames[$key]);
            }
        }

        return $columnNames;
    }
}


text:
package ca.hedlund.jiss.blocks;

import java.util.Date;

import jakarta.xml.bind.annotation.XmlRootElement;

/**
 * Class representing a saved block of code.
 *
 *
 */
@XmlRootElement
public class Block {

	/**
	 * Mimetype
	 */
	private String mimetype;

	/**
	 * source
	 */
	private String source;

	/**
	 * date created
	 */
	private Date created;

	public Block() {
		super();
	}

	public Block(String mimetype, String source) {
		super();
		this.mimetype = mimetype;
		this.source = source;
	}

	public String getMimetype() {
		return mimetype;
	}

	public void setMimetype(String mimetype) {
		this.mimetype = mimetype;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public Date getCreated() {
		return this.created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}
}