text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Abc.Zebus.Util.Extensions;
using Moq;
using Moq.Language.Flow;

namespace Abc.Zebus.Testing.UnitTesting
{
    public static class MoqExtensions
    {
        public static void CaptureEnumerable<TMock, TArg, TArg0>(this Mock<TMock> mock, TArg0 arg0, Expression<Action<TMock, TArg0, IEnumerable<TArg>>> action, ICollection<TArg> target) where TMock : class
        {
            var mockParam = Expression.Parameter(typeof(TMock));
            var arg0Param = Expression.Constant(arg0);
            var enumerableParam = Expression.Call(typeof(It).GetMethod("IsAny").MakeGenericMethod(typeof(IEnumerable<TArg>)));
            var methodCall = (MethodCallExpression)action.Body;
            var methodExpression = Expression.Call(mockParam, methodCall.Method, arg0Param, enumerableParam);
            var expression = Expression.Lambda<Action<TMock>>(methodExpression, mockParam);

            mock.Setup(expression).Callback<TArg0, IEnumerable<TArg>>((x, items) => items.ForEach(target.Add));
        }

        public static ICallbackResult InSequence<TMock>(this ISetup<TMock> setup, SetupSequence sequence) where TMock : class
        {
            return setup.Callback(sequence.GetCallback(setup.ToString()));
        }
    }
}


text:
<?php

namespace HotfixBundle\Job;

/**
 * This hotfix allows to see the daemon status with the overriden job queue command.
 */
class Daemon extends \Oro\Bundle\CronBundle\Job\Daemon
{
    /**
     * {@inheritdoc}
     */
    public function getPid()
    {
        if (!$this->pid) {
            $this->pid = $this->findProcessPid(
                sprintf('%sconsole hotfix:jms-job-queue:run', realpath($this->rootDir).DIRECTORY_SEPARATOR)
            );
        }

        return $this->pid;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import emberInplaceEdit from 'ember-inplace-edit/components/ember-inplace-edit';

export default emberInplaceEdit;


text:
// Copyright 2015 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.syntax;

import static com.google.common.truth.Truth.assertThat;

import com.google.devtools.build.lib.events.Location;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * A test class for exceptions.
 */
@RunWith(JUnit4.class)
public class ExceptionTest {
  private static final ASTNode DUMMY_NODE = new Identifier("DUMMY");

  @Test
  public void testEmptyMessage() throws Exception {
    EvalExceptionWithStackTrace ex =
        new EvalExceptionWithStackTrace(new NullPointerException(), DUMMY_NODE);
    assertThat(ex)
        .hasMessageThat()
        .contains("Null Pointer: ExceptionTest.testEmptyMessage() in ExceptionTest.java:");
  }

  @Test
  public void testExceptionCause() throws Exception {
    IllegalArgumentException iae = new IllegalArgumentException("foo");
    EvalException ee = new EvalException(Location.BUILTIN, iae);

    runExceptionTest(iae, iae);
    runExceptionTest(ee, iae);
  }

  private void runExceptionTest(Exception toThrow, Exception expectedCause) {
    EvalExceptionWithStackTrace ex = new EvalExceptionWithStackTrace(toThrow, DUMMY_NODE);
    assertThat(ex).hasCauseThat().isEqualTo(expectedCause);
  }
}


text:
import json
import typing
from argparse import ArgumentParser
from collections import OrderedDict

from cauldron import cli
from cauldron import environ
from cauldron.cli import sync
from cauldron.environ import Response

NAME = 'version'
DESCRIPTION = 'Display Cauldron version information'

def populate(
        parser: ArgumentParser,
        raw_args: typing.List[str],
        assigned_args: dict
):
    """

    :param parser:
    :param raw_args:
    :param assigned_args:
    :return:
    """

    parser.add_argument(
        '--verbose',
        dest='verbose',
        default=False,
        action='store_true',
        help=cli.reformat(
            """
            Adds verbose version information about the Python environment
            in addition to the basic Cauldron version information.
            """
        )
    )

    parser.add_argument(
        '--json',
        dest='as_json',
        default=False,
        action='store_true',
        help=cli.reformat(
            """
            Returns the version information in JSON format
            """
        )
    )

def pretty_print(source: dict, depth: int = 0) -> str:
    """

    :param source:
    :param depth:
    :return:
    """

    out = []

    if isinstance(source, OrderedDict):
        entries = source.items()
    else:
        entries = sorted(source.items(), key=lambda x: x[0])

    def to_string_entry(key, value):
        return '{}{}: {}'.format(depth * '  ', key, value)

    def list_item(index, value):
        key = '  [{}]'.format(index)

        if isinstance(value, (list, tuple, dict)):
            return to_string_entry(
                key,
                '\n{}'.format(pretty_print(value, depth + 2))
            )
        else:
            return to_string_entry(key, value)

    for k, v in entries:
        if isinstance(v, dict):
            out.append('{}{}:'.format(depth * '  ', k))
            out.append(pretty_print(v, depth + 1))
        elif isinstance(v, (list, tuple)):
            out.append('{}{}:'.format(depth * '  ', k))
            out.extend([list_item(i, item) for i, item in enumerate(v)])
        else:
            out.append(to_string_entry(k, v))

    return '\n'.join(out)

def execute_remote(context: cli.CommandContext, **kwargs) -> Response:
    """..."""

    thread = sync.send_remote_command(
        command=context.name,
        raw_args=context.raw_args,
        asynchronous=False
    )

    thread.join()

    response = thread.responses[0]
    return context.response.consume(response)

def execute(
        context: cli.CommandContext,
        verbose: bool = False,
        as_json: bool = False
) -> Response:
    """

    :return:
    """

    response = context.response
    settings = environ.package_settings

    if verbose:
        data = environ.systems.get_system_data()
        data['cauldron'] = settings
    else:
        data = settings

    if as_json:
        output = json.dumps(data, indent=2)
    else:
        output = pretty_print(data)

    return response.notify(
        kind='SUCCESS',
        code='VERSION',
        data=data,
        output=output
    ).console(
        output,
        whitespace=1
    ).response


text:
         <button id="enable-wifi" hidden
             i18n-content="enableWifi"></button>
         <button id="disable-wifi" hidden
             i18n-content="disableWifi"></button>
         <button id="enable-cellular" hidden
             i18n-content="enableCellular"></button>
         <button id="disable-cellular" hidden
             i18n-content="disableCellular"></button>

           <input id="use-shared-proxies" type="checkbox"
               pref="settings.use_shared_proxies">

           <input id="enable-data-roaming"
               pref="cros.signed.data_roaming_enabled"
               metric="Options_Internet_DataRoaming" type="checkbox">


text:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PolyKinds         #-}

module Data.Vinyl.Named where

import           Data.Coerce                                                (coerce)
import           Data.Constraint
import           Data.Dynamic                                               (Dynamic, dynTypeRep, fromDynamic, toDyn)
import           Data.List.NonEmpty                                         (NonEmpty ((:|)))
import           Data.List.TypeLevel
import           Data.List.TypeLevel.Constraint
import           Data.Map.Strict                                            (Map)
import qualified Data.Map.Strict                                            as Map
import           Data.Proxy                                                 (Proxy (Proxy))
import           Data.Tagged.Functor                                        (TaggedFunctor (..), showSymbolTaggedFunctor)
import           Data.Tuple.TypeLevel
import           Data.Type.Equality                                         ((:~:) (Refl))
import           Data.Typeable                                              (TypeRep, Typeable, eqT, typeRep)
import           Data.TypeString
import qualified Data.Vector.Algorithms.Merge                               as Merge
import qualified Data.Vector.Generic                                        as G
import qualified Data.Vector.Hybrid                                         as Hybrid
import qualified Data.Vector.Unboxed                                        as U
import qualified Data.Vector.Vinyl.Default.NonEmpty.Monomorphic             as VV
import qualified Data.Vector.Vinyl.Default.NonEmpty.Monomorphic.Implication as VV
import qualified Data.Vector.Vinyl.Default.NonEmpty.Monomorphic.Internal    as VV
import           Data.Vector.Vinyl.Default.NonEmpty.Monomorphic.Join        (indexMany, recFullJoinIndicesImmutable, uniq)
import           Data.Vector.Vinyl.Default.Types                            (HasDefaultVector (..), VectorVal (..))
import           Data.Vinyl.Class.Implication                               (listAllOrd)
import           Data.Vinyl.Core                                            (Rec (..), RecApplicative (rpure), rtraverse)
import           Data.Vinyl.DictFun
import           Data.Vinyl.Functor                                         (Compose (..), Const (..), Identity (..))
import           Data.Vinyl.Functor                                         (Identity)
import           Data.Vinyl.TypeLevel                                       (RecAll)
import           GHC.Exts                                                   (Constraint)
import           GHC.Prim                                                   (Any)
import           GHC.TypeLits                                               (CmpSymbol, KnownSymbol, Symbol, symbolVal)
import           Test.QuickCheck.Arbitrary
import           Unsafe.Coerce                                              (unsafeCoerce)

type RelOpConstraints =
      (ConstrainFst TypeString :&: ConstrainSnd Typeable)
  :&: (ConstrainSnd HasDefaultVector :&: ConstrainSnd Ord :&: ConstrainSnd Show)

newtype UncurriedTagged (x :: (a,*)) =
  UncurriedTagged { getUncurriedTagged :: Snd x }

showSymbolTaggedRec ::
  ( ListAll as (ConstrainFst KnownSymbol)
  , ListAll as (ConstrainSnd Show)
  ) => Rec (TaggedFunctor Identity) as -> String
showSymbolTaggedRec RNil = ""
showSymbolTaggedRec (r :& rs) = showSymbolTaggedFunctor r ++ ", " ++ showSymbolTaggedRec rs

recToProxy :: Rec proxy rs -> Rec Proxy rs
recToProxy RNil = RNil
recToProxy (_ :& rs) = Proxy :& recToProxy rs

rtraverseIdentity :: Applicative f => Rec f rs -> f (Rec Identity rs)
rtraverseIdentity = rtraverse (fmap Identity)

type family PairsSnd (as :: [(k,v)]) :: [v] where
  PairsSnd '[] = '[]
  PairsSnd (a ': as) = Snd a ': PairsSnd as

type family Zip (ks :: [k]) (vs :: [v]) :: [(k,v)] where
  Zip '[] '[] = '[]
  Zip (k ': ks) (v ': vs) = ('(k,v) ': Zip ks vs)

------------------------------------
-- Vector related stuff
------------------------------------

type ListAllJoinConstraints rs =
  ( ListAll rs Typeable
  , ListAll rs Ord
  , ListAll rs HasDefaultVector
  , ListAll rs Show
  )
type JoinConstraints r =
  ( Typeable r
  , Ord r
  , HasDefaultVector r
  , Show r
  )

data HiddenVector where
  HiddenVector :: forall (a :: *).
    JoinConstraints a =>
    VectorVal a -> HiddenVector

instance Show HiddenVector where
  show (HiddenVector (VectorVal a)) = "HiddenVector (" ++ show (G.toList a) ++ ")"

data HiddenRec (f :: * -> *) where
  HiddenRec :: forall (rs :: [*]) (f :: * -> *).
    ListAllJoinConstraints rs =>
    Rec f rs -> HiddenRec f

data NonEmptyHiddenRec (f :: * -> *) where
  NonEmptyHiddenRec :: forall (r :: *) (rs :: [*]) (f :: * -> *).
    ListAllJoinConstraints (r ': rs) =>
    Rec f (r ': rs) -> NonEmptyHiddenRec f

-- data ConstrainedNonEmptyHiddenRec (f :: * -> *) (c :: * -> Constraint) where
--   ConstrainedNonEmptyHiddenRec ::
--     RecAll f (r ': rs) c => Rec f (r ': rs) -> ConstrainedNonEmptyHiddenRec f c

flattenIndexedHiddenVectors :: [(U.Vector Int, HiddenVector)] -> [HiddenVector]
flattenIndexedHiddenVectors = map go
  where
  go (ixs, HiddenVector (VectorVal v)) = HiddenVector (VectorVal (indexMany ixs v ))

-- This only works if `rs` does not contain duplicate names
indexedHiddenVectorMapsToRec ::
  ( ListAll rs (ConstrainFst TypeString)
  , ListAll rs (ConstrainSnd Typeable)
  , ListAll rs (ConstrainSnd HasDefaultVector)
  )
  => Rec proxy rs
  -> [(U.Vector Int, Map String HiddenVector)]
  -> Rec (TaggedFunctor VectorVal) rs
indexedHiddenVectorMapsToRec prec = go prec . mkMap
  where
  mkMap xs = -- Map.unionsWith (\_ _ -> error "indexedHiddenVectorMapsToRec: duplicate field")
    Map.unions $ map (\(ixs,m) -> fmap (\h -> (ixs,h)) m) xs
  go :: forall rs proxy.
        ( ListAll rs (ConstrainFst TypeString)
        , ListAll rs (ConstrainSnd Typeable)
        , ListAll rs (ConstrainSnd HasDefaultVector)
        )
     => Rec proxy rs
     -> Map String (U.Vector Int, HiddenVector)
     -> Rec (TaggedFunctor VectorVal) rs
  go RNil m = if Map.null m then RNil else error "indexedHiddenVectorMapsToRec: should be empty"
  go ((_ :: proxy r) :& rs) m = case lookupHelper keyStr m of
    ((i,HiddenVector (VectorVal v :: VectorVal a)), mnext) -> case (eqT :: Maybe (Snd r :~: a)) of
      Just Refl -> TaggedFunctor (VectorVal (indexMany i v)) :& go rs mnext
      Nothing   -> error ("indexedHiddenVectorMapsToRec: " ++ keyStr ++ " had type " ++ show (typeRep (Proxy :: Proxy a)))
    where keyStr = (typeString (Proxy :: Proxy (Fst r)))

-- unchecked, still needs to be written
lookupHelper :: String -> Map String a -> (a, Map String a)
lookupHelper name m = case Map.lookup name m of
  Nothing -> error ("lookupHelper: missing name " ++ name)
  Just a  -> (a, Map.delete name m)

-- This function is partial.
hiddenVectorMapToRec :: forall rs m proxy.
  ( ListAll rs (ConstrainSnd Typeable)
  , ListAll rs (ConstrainFst TypeString)
  )
  => Rec proxy rs
  -> Map String HiddenVector
  -> Rec (TaggedFunctor VectorVal) rs
hiddenVectorMapToRec RNil m = if Map.null m then RNil else error "hiddenVectorMapToRec: should be empty"
hiddenVectorMapToRec ((_ :: proxy r) :& rs) m = case Map.lookup keyStr m of
  Just (HiddenVector (v :: VectorVal a)) -> case (eqT :: Maybe (Snd r :~: a)) of
    Just Refl -> TaggedFunctor v :& hiddenVectorMapToRec rs (Map.delete keyStr m)
    Nothing   -> error ("hiddenVectorMapToRec: " ++ keyStr ++ " had type " ++ show (typeRep (Proxy :: Proxy a)))
  Nothing -> error ("hiddenVectorMapToRec: missing key " ++ keyStr)
  where keyStr = (typeString (Proxy :: Proxy (Fst r)))

recToHiddenVectorMap :: forall rs.
  ( ListAll rs RelOpConstraints
  )
  => Rec (TaggedFunctor VectorVal) rs
  -> Map String HiddenVector
recToHiddenVectorMap RNil = Map.empty
recToHiddenVectorMap (u@(TaggedFunctor v) :& rs) =
  Map.insert
    (typeString (proxyFst u))
    (HiddenVector v)
    (recToHiddenVectorMap rs)
  where
  proxyFst :: proxy a -> Proxy (Fst a)
  proxyFst _ = Proxy

hiddenVectorsToHiddenRec :: [HiddenVector] -> HiddenRec VectorVal
hiddenVectorsToHiddenRec dvs = case dvs of
  [] -> HiddenRec RNil
  HiddenVector v : dvsNext -> case hiddenVectorsToHiddenRec dvsNext of
    HiddenRec rec -> HiddenRec (v :& rec)

hiddenRecToHiddenVectors :: HiddenRec VectorVal -> [HiddenVector]
hiddenRecToHiddenVectors (HiddenRec h) = go h
  where
  go :: forall rs. ListAllJoinConstraints rs => Rec VectorVal rs -> [HiddenVector]
  go RNil = []
  go (r :& rs) = HiddenVector r : go rs

nonEmptyHiddenVectorsToHiddenRec :: NonEmpty HiddenVector -> NonEmptyHiddenRec VectorVal
nonEmptyHiddenVectorsToHiddenRec (HiddenVector a :| as) = case hiddenVectorsToHiddenRec as of
  HiddenRec rs -> NonEmptyHiddenRec (a :& rs)

hiddenRecToNonEmptyHiddenVectors :: NonEmptyHiddenRec VectorVal -> NonEmpty HiddenVector
hiddenRecToNonEmptyHiddenVectors (NonEmptyHiddenRec (r :& rs)) =
  HiddenVector r :| hiddenRecToHiddenVectors (HiddenRec rs)

uncheckedFullJoinIndices ::
     [(String,String)]
  -> Map String HiddenVector
  -> Map String HiddenVector
  -> Hybrid.Vector U.Vector U.Vector (Int,Int)
uncheckedFullJoinIndices matchedCols aMap bMap = r
  where
  aHRec = hiddenVectorsToHiddenRec (uncheckedLookupMany (map fst matchedCols) aMap)
  bHRec = hiddenVectorsToHiddenRec (uncheckedLookupMany (map snd matchedCols) bMap)
  r = uncheckedHiddenRecCoersion aHRec bHRec
      (\a b -> case a of
        RNil -> error "uncheckedFullJoinIndices: empty record"
        _ :& _ -> recFullJoinIndicesImmutable a b
      )

uncheckedLookupMany :: Ord k => [k] -> Map k v -> [v]
uncheckedLookupMany [] _ = []
uncheckedLookupMany (k : ks) m = case Map.lookup k m of
  Nothing -> error "uncheckedLookupMany: couldn't find key"
  Just v -> v : uncheckedLookupMany ks m

uncheckedHiddenRecCoersion :: forall f a.
     HiddenRec f
  -> HiddenRec f
  -> (forall rs. ListAllJoinConstraints rs => Rec f rs -> Rec f rs -> a)
  -> a
uncheckedHiddenRecCoersion (HiddenRec a) (HiddenRec b) f =
  case uncheckedListEqualitiy a b of
    Refl -> f a b

uncheckedListEqualitiy :: forall proxy1 proxy2 as bs.
  (ListAll as Typeable, ListAll bs Typeable)
  => Rec proxy1 as -> Rec proxy2 bs -> (as :~: bs)
uncheckedListEqualitiy RNil (_ :& _) = error "uncheckedListEqualitiy: mismatched length (left)"
uncheckedListEqualitiy (_ :& _) RNil = error "uncheckedListEqualitiy: mismatched length (right)"
uncheckedListEqualitiy RNil RNil = Refl
uncheckedListEqualitiy (a :& aNext) (b :& bNext) =
  case uncheckedListEqualitiy aNext bNext of
    Refl -> case uncheckedEqT a b of
      Refl -> Refl

uncheckedEqT :: forall proxy1 proxy2 a b. (Typeable a, Typeable b)
  => proxy1 a -> proxy2 b -> a :~: b
uncheckedEqT _ _ = case (eqT :: Maybe (a :~: b)) of
  Nothing -> error "uncheckedEqT: mismatched types"
  Just Refl -> Refl

removeDuplicates :: NonEmptyHiddenRec VectorVal -> NonEmptyHiddenRec VectorVal
removeDuplicates (NonEmptyHiddenRec rec) =
  case listAllOrd (Proxy :: Proxy Identity) rec (Sub Dict) of
    Sub Dict -> case VV.listAllVector rec of
      Sub Dict -> id
        $ NonEmptyHiddenRec
        $ VV.stripV
        $ uniq
        $ VV.modify Merge.sort
        $ VV.V rec

-- A convenience function
zipNamesExplicit :: forall f proxy ks vs.
  Rec proxy ks -> Rec f vs -> Rec (TaggedFunctor f) (Zip ks vs)
zipNamesExplicit RNil RNil = RNil
zipNamesExplicit ((_ :: proxy k) :& ks) ((r :: f v) :& rs) =
  (TaggedFunctor r :: TaggedFunctor f '(k, v)) :& zipNamesExplicit ks rs

zipNames :: forall f proxy ks vs. RecApplicative ks
  => proxy ks -> Rec f vs -> Rec (TaggedFunctor f) (Zip ks vs)
zipNames _ = zipNamesExplicit (rpure Proxy :: Rec Proxy ks)

class RecApplicativeConstrained (c :: k -> Constraint) (rs :: [k]) where
  rpureConstrained :: Proxy c -> (forall x. c x => f x) -> Rec f rs
instance RecApplicativeConstrained c '[] where
  rpureConstrained _ _ = RNil
instance (RecApplicativeConstrained c rs, c r) => RecApplicativeConstrained c (r ': rs) where
  rpureConstrained p s = s :& rpureConstrained p s

-- rpureConstrained :: RecApplicative rs => Proxy c -> (forall x. c x => f x) -> Rec f rs
-- rpureConstrained _ f = rpureConstrained' f (rpure (DictFun Dict))

rpureConstrained' :: (forall x. c x => f x) -> Rec (DictFun c) rs -> Rec f rs
rpureConstrained' _ RNil = RNil
rpureConstrained' f (DictFun :& rs) = f :& rpureConstrained' f rs

-- data NamedValue (a :: NamedType *) where
--   NamedValue :: val -> NamedValue ('NamedType key val)
-- data NamedProxy (a :: NamedType *) where
--   NamedProxy :: NamedProxy ('NamedType key val)


text:
<?php

namespace Moharrum\LaravelGeoIPWorldCities;

use Illuminate\Support\ServiceProvider;
use Moharrum\LaravelGeoIPWorldCities\Console\CreateCitiesSeederCommand;
use Moharrum\LaravelGeoIPWorldCities\Console\CreateCitiesMigrationCommand;

/**
 * @author Khalid Moharrum <khalid.moharram@gmail.com>
 */
class LaravelGeoIPWorldCitiesServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishConfig();
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->bind();

        $this->mergeConfig();

        $this->registerMigrationCommand();

        $this->registerSeederCommand();
    }

    /**
     * Publish config files.
     */
    private function publishConfig()
    {
        $this->publishes([
            __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php' => config_path('cities.php')
        ]);
    }

    /**
     * Bind the package to the IoC container.
     */
    private function bind()
    {
        $this->app->singleton('cities', function ($app) {
            return new City;
        });
    }

    /**
     * Merges user's and cities's configs.
     */
    private function mergeConfig()
    {
        $this->mergeConfigFrom(
            __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php',
            'cities'
        );
    }

    /**
     * Register the migration command.
     */
    private function registerMigrationCommand()
    {
        $this->app->singleton('command.cities.migration', function ($app) {
            return new CreateCitiesMigrationCommand;
        });

        $this->commands('command.cities.migration');
    }

    /**
     * Register the seeder command.
     */
    private function registerSeederCommand()
    {
        $this->app->singleton('command.cities.seeder', function ($app) {
            return new CreateCitiesSeederCommand;
        });

        $this->commands('command.cities.seeder');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['cities'];
    }
}


text:
package com.example.souzhoubian;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-10-16
 * Time: 下午1:46
 * To change this template use File | Settings | File Templates.
 */
public class SecondaryActivity extends Activity{

    String[] foodStrings = new String[]{"中餐厅","外国餐厅","快餐厅","休闲餐饮场所","咖啡厅","茶艺馆","冷饮店","糕饼店","甜品店"};
    String[] shoppingStrings=new String[]{"购物相关场所","商场","便民商店/便利店","家电电子卖场","超级市场","花鸟鱼虫市场","家居建材市场","综合市场","文化用品店","体育用品店","特色商业街","服装鞋帽皮具店","专卖店","特殊买卖场所","个人用品/化妆品店"};
    String[] lifeService=new  String[]{"生活服务场所","旅行社","信息咨询中心","售票处","邮局","物流速递","电讯营业厅","事务所","人才市场","自来水营业厅","电力营业厅","美容美发店","维修站点","摄影冲印店","洗浴推拿场所","洗衣店","中介机构","搬家公司","彩票彩券销售点","丧葬设施" };
    String[] sportLife=new String[]{"体育休闲服务场所","运动场馆","高尔夫相关","娱乐场所","度假疗养场所","休闲场所","影剧院"};
    String[] financeInsurance=new String[]{"金融保险服务机构","银行","银行相关","自动提款机","保险公司","证券公司","财务公司"};
    String[] healthCare=new String[]{"医疗保健服务场所","综合医院","专科医院","诊所","急救中心","疾病预防机构","医药保健相关","动物医疗场所"};
    String[] accommodationServices =new String[]{"住宿服务相关","宾馆酒店","旅馆招待所"};
    String[] scienceAndEducationCulturalServices =new String[]{"科教文化场所","博物馆","展览馆","会展中心","美术馆","图书馆","科技馆","天文馆","文化馆","档案馆","文艺团体","传媒机构","学校","科研机构","培训机构","驾校"};
    String[] transportationService=new String[]{"交通服务相关","飞机场","火车站","港口码头","长途汽车站","地铁站","轻轨站","公交车站","班车站","停车场","过境口岸"};
    String [] publicFacilities=new String[]{"公共设施","报刊亭","公用电话","公共厕所","紧急避难场所"};

    /**
     * Called when the activity is first created.
     */

    private ListView listView2;
    private Button button;
    private ImageButton  backButton;

    private ArrayList<HashMap<String, ?>> data = new ArrayList<HashMap<String, ?>>();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.secondary);

        String[] strings= new String[]{};
        String  twoLevelName =  getIntent().getStringExtra("name");
        TextView title= (TextView) findViewById(R.id.secondTitle);
        title.setText(twoLevelName);
        if(twoLevelName.equals("餐饮服务")){
            strings = foodStrings;
        }  else if(twoLevelName.equals("购物服务")){
            strings = shoppingStrings;
        }  else if(twoLevelName.equals("生活服务")){
            strings = lifeService;
        }  else if(twoLevelName.equals("体育休闲服务")){
            strings = sportLife;
        }  else if (twoLevelName.equals("金融保险服务")){
            strings =  financeInsurance ;
        }   else if (twoLevelName.equals("医疗保健服务")){
            strings =  healthCare ;
        }   else if (twoLevelName.equals("住宿服务")){
            strings =  accommodationServices ;
        }   else if (twoLevelName.equals("科教文化服务")){
            strings =  scienceAndEducationCulturalServices ;
        }    else if (twoLevelName.equals("交通设施服务")){
            strings =  transportationService ;
        }     else if (twoLevelName.equals("公共设施服务")){
            strings =  publicFacilities ;
        }
        listView(strings);
    }
    public void listView(String[] strings) {
        listView2 = (ListView) findViewById(R.id.listView2);

        for (int i = 0; i < strings.length; i++) {
            HashMap<String, Object> item = new HashMap<String, Object>();

            item.put("text", strings[i]) ;
            data.add(item);
        }
        SimpleAdapter adapter = new SimpleAdapter(this,
                data,
                R.layout.listview_item,
                new String[]{"text"},
                new int[]{R.id.firstTextView}){
            @Override
            public View getView( final int position, View convertView, ViewGroup parent) {
                View view =super.getView(position, convertView, parent);
//               final int i  = position;
                button=(Button)view.findViewById(R.id.step) ;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent=new Intent();
                        intent.putExtra("name",data.get(position).get("text").toString())  ;
                        intent.setClass(SecondaryActivity.this,MyActivity.class);
                        startActivity(intent);
                    }
                });
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent=new Intent();
                        intent.putExtra("cententName",data.get(position).get("text").toString())  ;

                        intent.setClass(SecondaryActivity.this,ThirdActivity.class);
                        startActivity(intent);

                    }
                });
                return view ;    //To change body of overridden methods use File | Settings | File Templates.
            }
        };
        listView2.setAdapter(adapter);
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent();
                intent.setClass(SecondaryActivity.this,MyActivity.class);
                startActivity(intent);
            }
        });

        backButton= (ImageButton) findViewById(R.id.restaurant_nav_back);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(SecondaryActivity.this,FirstActivity.class);
                startActivity(intent);
                SecondaryActivity.this.finish();
            }
        });

      }

}


text:
package ru.job4j.profession;

/**
 * Class Класс, описывающий профессию учителя.
 *
 * @author Kochanov Alexey
 * @version $ld$
 * @since 0.1
 */
public class Teacher extends Profession {
    /**
     * Название школы.
     */
    private String schoolName;
    /**
     * Название предмета.
     */
    private String subject;

    /**
     * Конструктор.
     * @param name - имя.
     * @param surname - фамилия.
     * @param age - возраст.
     * @param workExperience - опыт работы.
     * @param schoolName - название школы.
     * @param subject - название предмета.
     */
    public Teacher(String name, String surname, int age, int workExperience, String schoolName, String subject) {
        super(name, surname, age, workExperience);
        this.schoolName = schoolName;
        this.subject = subject;
    }

    /**
     * Метод геттер.
     * @return - возращает schoolName.
     */
    public String getSchoolName() {
        return schoolName;
    }

    /**
     * Метод геттер.
     * @return - возращает subject.
     */
    public String getSubject() {
        return  subject;
    }

    /**
     * Метод, в котором учитель учит ученика.
     * @param student - студент.
     * @return - возращает строку о том, что учитель учит ученика.
     */
    public String teaches(Student student) {
        return "Учитель " + getSurname() + " " + getName() + " учит ученика " + student.getSurname() + " " + student.getName();
    }

    /**
     * Метод, в котором учитель экзаменует ученика.
     * @param student - студент.
     * @return - возращает строку о том, что учитель экзаменует ученика.
     */
    public String examine(Student student) {
        return "Учитель " + getSurname() + " " + getName() + " экзаменует ученика " + student.getSurname() + " " + student.getName();
    }
}


text:
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Util;
using Sharpen;

namespace Couchbase.Lite
{
	public class LocalDocsTest : LiteTestCase
	{
		public const string Tag = "LocalDocs";

		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		public virtual void TestLocalDocs()
		{
			//create a document
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			documentProperties.Put("_id", "_local/doc1");
			documentProperties.Put("foo", 1);
			documentProperties.Put("bar", false);
			Body body = new Body(documentProperties);
			RevisionInternal rev1 = new RevisionInternal(body, database);
			Status status = new Status();
			rev1 = database.PutLocalRevision(rev1, null);
			Log.V(Tag, "Created " + rev1);
			NUnit.Framework.Assert.AreEqual("_local/doc1", rev1.GetDocId());
			NUnit.Framework.Assert.IsTrue(rev1.GetRevId().StartsWith("1-"));
			//read it back
			RevisionInternal readRev = database.GetLocalDocument(rev1.GetDocId(), null);
			NUnit.Framework.Assert.IsNotNull(readRev);
			IDictionary<string, object> readRevProps = readRev.GetProperties();
			NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), readRev.GetProperties().Get("_id"
				));
			NUnit.Framework.Assert.AreEqual(rev1.GetRevId(), readRev.GetProperties().Get("_rev"
				));
			NUnit.Framework.Assert.AreEqual(UserProperties(readRevProps), UserProperties(body
				.GetProperties()));
			//now update it
			documentProperties = readRev.GetProperties();
			documentProperties.Put("status", "updated!");
			body = new Body(documentProperties);
			RevisionInternal rev2 = new RevisionInternal(body, database);
			RevisionInternal rev2input = rev2;
			rev2 = database.PutLocalRevision(rev2, rev1.GetRevId());
			Log.V(Tag, "Updated " + rev1);
			NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
			NUnit.Framework.Assert.IsTrue(rev2.GetRevId().StartsWith("2-"));
			//read it back
			readRev = database.GetLocalDocument(rev2.GetDocId(), null);
			NUnit.Framework.Assert.IsNotNull(readRev);
			NUnit.Framework.Assert.AreEqual(UserProperties(readRev.GetProperties()), UserProperties
				(body.GetProperties()));
			// Try to update the first rev, which should fail:
			bool gotException = false;
			try
			{
				database.PutLocalRevision(rev2input, rev1.GetRevId());
			}
			catch (CouchbaseLiteException e)
			{
				NUnit.Framework.Assert.AreEqual(Status.Conflict, e.GetCBLStatus().GetCode());
				gotException = true;
			}
			NUnit.Framework.Assert.IsTrue(gotException);
			// Delete it:
			RevisionInternal revD = new RevisionInternal(rev2.GetDocId(), null, true, database
				);
			gotException = false;
			try
			{
				RevisionInternal revResult = database.PutLocalRevision(revD, null);
				NUnit.Framework.Assert.IsNull(revResult);
			}
			catch (CouchbaseLiteException e)
			{
				NUnit.Framework.Assert.AreEqual(Status.Conflict, e.GetCBLStatus().GetCode());
				gotException = true;
			}
			NUnit.Framework.Assert.IsTrue(gotException);
			revD = database.PutLocalRevision(revD, rev2.GetRevId());
			// Delete nonexistent doc:
			gotException = false;
			RevisionInternal revFake = new RevisionInternal("_local/fake", null, true, database
				);
			try
			{
				database.PutLocalRevision(revFake, null);
			}
			catch (CouchbaseLiteException e)
			{
				NUnit.Framework.Assert.AreEqual(Status.NotFound, e.GetCBLStatus().GetCode());
				gotException = true;
			}
			NUnit.Framework.Assert.IsTrue(gotException);
			// Read it back (should fail):
			readRev = database.GetLocalDocument(revD.GetDocId(), null);
			NUnit.Framework.Assert.IsNull(readRev);
		}
	}
}


text:
.. Copyright 2015 tsuru authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.

++++++++++++++++++++
tsuru.conf reference
++++++++++++++++++++

tsuru uses a configuration file in `YAML <http://www.yaml.org/>`_ format. This
document describes what each option means, and how it should look.

Notation
========

tsuru uses a colon to represent nesting in YAML. So, whenever this document says
something like ``key1:key2``, it refers to the value of the ``key2`` that is
nested in the block that is the value of ``key1``. For example,
``database:url`` means:

.. highlight:: yaml

::

    database:
      url: <value>

tsuru configuration
===================

This section describes tsuru's core configuration. Other sections will include
configuration of optional components, and finally, a full sample file.

HTTP server
-----------

tsuru provides a REST API, that supports HTTP and HTTP/TLS (a.k.a. HTTPS). Here
are the options that affect how tsuru's API behaves:

listen
++++++

``listen`` defines in which address tsuru webserver will listen. It has the
form <host>:<port>. You may omit the host (example: ``:8080``). This setting
has no default value.

use-tls
+++++++

``use-tls`` indicates whether tsuru should use TLS or not. This setting is
optional, and defaults to "false".

tls:cert-file
+++++++++++++

``tls:cert-file`` is the path to the X.509 certificate file configured to serve
the domain.  This setting is optional, unless ``use-tls`` is true.

tls:key-file
++++++++++++

``tls:key-file`` is the path to private key file configured to serve the
domain. This setting is optional, unless ``use-tls`` is true.

server:read-timeout
+++++++++++++++++++

``server:read-timeout`` is the timeout of reading requests in the server. This
is the maximum duration of any request to the tsuru server.

This is useful to avoid leaking connections, in case clients drop the
connection before end sending the request. The default value is 0, meaning no
timeout.

server:write-timeout
++++++++++++++++++++

``server:write-timeout`` is the timeout of writing responses in the server.

This is useful to avoid leaking connections, in case clients drop the
connection before reading the response from tsuru. The default value is 0,
meaning no timeout.

disable-index-page
++++++++++++++++++

tsuru API serves an index page with some basic instructions on how to use the
current target. It's possible to disable this page by setting the
``disable-index-page`` flag to true. It's also possible to customize which
template will be used in the index page, see the next configuration entry for
more details.

This setting is optional, and defaults to ``false``.

index-page-template
+++++++++++++++++++

``index-page-template`` is the template that will be used for the index page.
It must use the `Go template syntax <http://golang.org/pkg/text/template/>`_,
and tsuru will provide the following variables in the context of the template:

    - ``tsuruTarget``: the target URL of the tsuru API serving the index page
    - ``userCreate``: a boolean indicating whether user registration is enabled
      or disabled
    - ``nativeLogin``: a boolean indicating whether the API is configured to
      use the native authentication scheme
    - ``keysEnabled``: a boolean indicating whether the API is configured to
      manage SSH keys

It will also include a function used for querying configuration values, named
``getConfig``. Here is an example of the function usage:

.. highlight:: html

::

        {{if getConfig "use-tls"}}

we're safe

        {{else}}

we're not safe

        {{end}}

This setting is optional. When ``index-page-template`` is not defined, tsuru
will use the `default template
<https://github.com/tsuru/tsuru/blob/master/api/index_templates.go>`_.

Database access
---------------

tsuru uses MongoDB as a database manager to store information like users,
machines, containers, etc. You need to describe how tsuru will connect to your
database server. Therefore, it's necessary to provide a `MongoDB connection
string <https://docs.mongodb.org/manual/reference/connection-string/>`_.
Database related options are listed below:

database:url
++++++++++++

``database:url`` is the database connection string. It is a mandatory setting
and it has no default value. Examples of strings include basic ``127.0.0.1`` and
more advanced ``mongodb://user:password@127.0.0.1:27017/database``. Please refer
to `MongoDB documentation
<http://docs.mongodb.org/manual/reference/connection-string/>`_ for more details
and examples of connection strings.

database:name
+++++++++++++

``database:name`` is the name of the database that tsuru uses. It is a
mandatory setting and has no default value. An example of value is "tsuru".

database:logdb-url
++++++++++++++++++

This setting is optional. If ``database:logdb-url`` is specified, tsuru will use
it as the connection string to the MongoDB server responsible for storing
application logs. If this value is not set, tsuru will use ``database:url``
instead.

This setting is useful because tsuru may have to process a very large number of
log messages depending on the number of units deployed and applications
behavior. Every log message will trigger a insertion in MongoDB and this may
negatively impact the database performance. Other measures will be implemented
in the future to improve this, but for now, having the ability to use an
exclusive database server for logs will help mitigate the negative impact of log
writing.

database:logdb-name
+++++++++++++++++++

This setting is optional. If ``database:logdb-name`` is specified, tsuru will
use it as the database name for storing application logs. If this value is not
set, tsuru will use ``database:name`` instead.

Email configuration
-------------------

tsuru sends email to users when they request password recovery. In order to send
those emails, tsuru needs to be configured with some SMTP settings. Omitting
these settings won't break tsuru, but users will not be able to reset their
password.

smtp:server
+++++++++++

The SMTP server to connect to. It must be in the form <host>:<port>. Example:
"smtp.gmail.com:587".

smtp:user
+++++++++

The user to authenticate with the SMTP sever. Currently, tsuru requires
authenticated sessions.

smtp:password
+++++++++++++

The password for authentication within the SMTP server.

Repository configuration
------------------------

tsuru optionally uses `Gandalf <https://github.com/tsuru/gandalf>`_ to manage
git repositories. Gandalf exposes a REST API for repositories management and
tsuru needs information about the Gandalf HTTP server endpoint.

repo-manager
++++++++++++

``repo-manager`` represents the repository manager that tsuru-server should use.
For backward compatibility reasons, the default value is "gandalf". Users can
disable repository and SSH key management by setting "repo-manager" to "none".
For more details, please refer to the :doc:`repository management page
</managing/repositories>` in the documentation.

git:api-server
++++++++++++++

``git:api-server`` is the address of the Gandalf API. It should define the
entire address, including protocol and port. Examples of value:
``http://localhost:9090`` and ``https://gandalf.tsuru.io:9595``.

Authentication configuration
----------------------------

tsuru has support for ``native`` and ``oauth`` authentication schemes.

The default scheme is ``native`` and it supports the creation of users in
tsuru's internal database. It hashes passwords brcypt. Tokens are generated
during authentication and are hashed using SHA512.

The ``auth`` section also controls whether user registration is on or off. When
user registration is off, only admin users are able to create new users.

auth:scheme
+++++++++++

The authentication scheme to be used. The default value is ``native``, the other
supported value is ``oauth``.

auth:user-registration
++++++++++++++++++++++

This flag indicates whether user registration is enabled. This setting is
optional, and defaults to false.

auth:hash-cost
++++++++++++++

Required only with ``native`` chosen as ``auth:scheme``.

This number indicates how many CPU time you're willing to give to hashing
calculation. It is an absolute number, between 4 and 31, where 4 is faster and
less secure, while 31 is very secure and *very* slow.

auth:token-expire-days
++++++++++++++++++++++

Required only with ``native`` chosen as ``auth:scheme``.

Whenever a user logs in, tsuru generates a token for him/her, and the user may
store the token. ``auth:token-expire-days`` setting defines the amount of days
that the token will be valid. This setting is optional, and defaults to "7".

auth:max-simultaneous-sessions
++++++++++++++++++++++++++++++

tsuru can limit the number of simultaneous sessions per user. This setting is
optional, and defaults to "unlimited".

auth:oauth
++++++++++

Every config entry inside ``auth:oauth`` are used when the ``auth:scheme`` is
set to "oauth". Please check `rfc6749 <http://tools.ietf.org/html/rfc6749>`_ for
more details.

auth:oauth:client-id
++++++++++++++++++++

The client id provided by your OAuth server.

auth:oauth:client-secret
++++++++++++++++++++++++

The client secret provided by your OAuth server.

auth:oauth:scope
++++++++++++++++

The scope for your authentication request.

auth:oauth:auth-url
+++++++++++++++++++

The URL used in the authorization step of the OAuth flow. tsuru CLI will receive
this URL and trigger the opening a browser on this URL with the necessary
parameters.

During the authorization step, tsuru CLI will start a server locally and set the
callback to http://localhost:<port>, if ``auth:oauth:callback-port`` is set
tsuru CLI will use its value as <port>. If ``auth:oauth:callback-port`` isn't
present tsuru CLI will automatically choose an open port.

The callback URL should be registered on your OAuth server.

If the chosen server requires the callback URL to match the same host and port
as the registered one you should register "http://localhost:<chosen port>" and
set the ``auth:oauth:callback-port`` accordingly.

If the chosen server is more lenient and allows a different port to be used you
should register simply "http://localhost" and leave ``auth:oauth:callback-port``
empty.

auth:oauth:token-url
++++++++++++++++++++

The URL used in the exchange token step of the OAuth flow.

auth:oauth:info-url
+++++++++++++++++++

The URL used to fetch information about the authenticated user. tsuru expects a
json response containing a field called ``email``.

tsuru will also make call this URL on every request to the API to make sure the
token is still valid and hasn't been revoked.

auth:oauth:collection
+++++++++++++++++++++

The database collection used to store valid access tokens. Defaults to
"oauth_tokens".

auth:oauth:callback-port
++++++++++++++++++++++++

The port used in the callback URL during the authorization step. Check docs for
``auth:oauth:auth-url`` for more details.

.. _config_queue:

Queue configuration
-------------------

tsuru uses a work queue for asynchronous tasks.

``queue:*`` groups configuration settings for a MongoDB server that will be used
as storage for delayed execution of queued jobs.

This queue is used to manage creation and destruction of IaaS machines, but
tsuru may start using it in more places in the future.

It's not mandatory to configure the queue, however creating and removing
machines using a IaaS provider will not be possible.

queue:mongo-url
+++++++++++++++

Connection url for MongoDB server used to store task information.

queue:mongo-database
++++++++++++++++++++

Database name used in MongoDB. This value will take precedence over any database
name already specified in the connection url.

pubsub
++++++

``pubsub`` configuration is optional and depends on a redis server instance.
It's used only for following application logs (running ``tsuru app-log -f``). If
this is not configured tsuru will fail when running ``tsuru app-log -f``.

Previously the configuration for this redis server was inside ``redis-queue:*``
keys shown below. Using these keys is deprecated and tsuru will start ignoring
them before 1.0 release.

pubsub:redis-host
+++++++++++++++++

``pubsub:redis-host`` is the host of the Redis server to be used for pub/sub.
This settings is optional and defaults to "localhost".

pubsub:redis-port
+++++++++++++++++

``pubsub:redis-port`` is the port of the Redis server to be used for pub/sub.
This settings is optional and defaults to 6379.

pubsub:redis-password
+++++++++++++++++++++

``pubsub:redis-password`` is the password of the Redis server to be used for
pub/sub. This settings is optional and defaults to "", indicating that the Redis
server is not authenticated.

pubsub:redis-db
+++++++++++++++

``pubsub:redis-db`` is the database number of the Redis server to be used for
pub/sub. This settings is optional and defaults to 3.

pubsub:pool-max-idle-conn
+++++++++++++++++++++++++

``pubsub:pool-max-idle-conn`` is the maximum number of idle connections to
redis. Defaults to 20.

pubsub:pool-idle-timeout
++++++++++++++++++++++++

``pubsub:pool-idle-timeout`` is the number of seconds idle connections will
remain in connection pool to redis. Defaults to 300.

redis-queue:host
++++++++++++++++

Deprecated. See ``pubsub:redis-host``.

redis-queue:port
++++++++++++++++

Deprecated. See ``pubsub:redis-port``.

redis-queue:password
++++++++++++++++++++

Deprecated. See ``pubsub:redis-password``.

redis-queue:db
++++++++++++++

Deprecated. See ``pubsub:redis-db``.

.. _config_admin_user:

Admin users
-----------

tsuru has a very simple way to identify admin users: an admin user is a user
that is the member of the admin team, and the admin team is defined in the
configuration file, using the ``admin-team`` setting.

.. _config_admin_team:

admin-team
++++++++++

``admin-team`` is the name of the administration team for the current tsuru
installation. All members of the administration team is able to use the
``tsuru-admin`` command.

Quota management
----------------

tsuru can, optionally, manage quotas. Currently, there are two available
quotas: apps per user and units per app.

tsuru administrators can control the default quota for new users and new apps
in the configuration file, and use ``tsuru-admin`` command to change quotas for
users or apps. Quota management is disabled by default, to enable it, just set
the desired quota to a positive integer.

quota:units-per-app
+++++++++++++++++++

``quota:units-per-app`` is the default value for units per-app quota. All new
apps will have at most the number of units specified by this setting. This
setting is optional, and defaults to "unlimited".

quota:apps-per-user
+++++++++++++++++++

``quota:apps-per-user`` is the default value for apps per-user quota. All new
users will have at most the number of apps specified by this setting. This
setting is optional, and defaults to "unlimited".

.. _config_logging:

Logging
-------

Tsuru supports three logging flavors, that can be enabled or disabled
altogether. The default behavior of tsuru is to send all logs to syslog, but it
can also send logs to the standard error stream or a file. It's is possible to
use any combination of the three flavors at any time in tsuru configuration
(e.g.: write logs both to stderr and syslog, or a file and stderr, or to all of
the flavors simultaneously).

There's also the possibility to enable or disable debugging log, via the debug
flag.

debug
+++++

``false`` is the default value, so you won't see any
noises on logs, to turn it on set it to true, e.g.: ``debug: true``

log:file
++++++++

Use this to specify a path to a log file. If no file is specified, tsuru-server
won't write logs to any file.

log:disable-syslog
++++++++++++++++++

``log:disable-syslog`` indicates whether tsuru-server should disable the use of
syslog. ``false`` is the default value. If it's ``true``, tsuru-server won't
send any logs to syslog.

log:syslog-tag
++++++++++++++

``log:syslog-tag`` is the tag that will be attached to every log line. The
default value is "tsr".

log:use-stderr
++++++++++++++

``log:use-stderr`` indicates whether tsuru-server should write logs to standard
error stream. The default value is ``false``.

.. _config_routers:

Routers
-------

As of 0.10.0, all your router configuration should live under entries with the
format ``routers:<router name>``.

routers:<router name>:type (type: hipache, galeb, vulcand)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Indicates the type of this router configuration. The standard router supported
by tsuru is `hipache <https://github.com/hipache/hipache>`_. There is also
experimental support for `galeb <http://galeb.io/>`_ and `vulcand
<https://docs.vulcand.io/>`_).

Depending on the type, there are some specific configuration options available.

routers:<router name>:domain (type: hipache, galeb, vulcand)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The domain of the server running your router. Applications created with
tsuru will have a address of ``http://<app-name>.<domain>``

routers:<router name>:redis-server (type: hipache)
++++++++++++++++++++++++++++++++++++++++++++++++++

Redis server used by Hipache router. This same server (or a redis slave of it),
must be configured in your hipache.conf file.

routers:<router name>:api-url (type: galeb, vulcand)
++++++++++++++++++++++++++++++++++++++++++++++++++++

The URL for the Galeb or vulcand manager API.

routers:<router name>:username (type: galeb)
++++++++++++++++++++++++++++++++++++++++++++

Galeb manager username.

routers:<router name>:password (type: galeb)
++++++++++++++++++++++++++++++++++++++++++++

Galeb manager password.

routers:<router name>:environment (type: galeb)
+++++++++++++++++++++++++++++++++++++++++++++++

Galeb manager environment used to create virtual hosts and backend pools.

routers:<router name>:farm-type (type: galeb)
+++++++++++++++++++++++++++++++++++++++++++++

Galeb manager farm type used to create virtual hosts and backend pools.

routers:<router name>:plan (type: galeb)
++++++++++++++++++++++++++++++++++++++++

Galeb manager plan used to create virtual hosts and backend pools.

routers:<router name>:project (type: galeb)
+++++++++++++++++++++++++++++++++++++++++++

Galeb manager project used to create virtual hosts, backend pools and pools.

routers:<router name>:load-balance-policy (type: galeb)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++

Galeb manager load balancing policy used to create backend pools.

routers:<router name>:rule-type (type: galeb)
+++++++++++++++++++++++++++++++++++++++++++++

Galeb manager rule type used to create rules.

Hipache
-------

hipache:redis-server
++++++++++++++++++++

Redis server used by Hipache router. This same server (or a redis slave of it),
must be configured in your hipache.conf file.

This setting is deprecated in favor of ``routers:<router name>:type = hipache``
and ``routers:<router name>:redis-server``.

hipache:domain
++++++++++++++

The domain of the server running your hipache server. Applications created with
tsuru will have a address of ``http://<app-name>.<hipache:domain>``.

This setting is deprecated in favor of ``routers:<router name>:type = hipache``
and ``routers:<router name>:domain``

Defining the provisioner
------------------------

tsuru has extensible support for provisioners. A provisioner is a Go type that
satisfies the `provision.Provisioner` interface. By default, tsuru will use
``DockerProvisioner`` (identified by the string "docker"), and now that's the
only supported provisioner (Ubuntu Juju was supported in the past but its
support has been removed from tsuru).

provisioner
+++++++++++

``provisioner`` is the string the name of the provisioner that will be used by
tsuru. This setting is optional and defaults to "docker".

Docker provisioner configuration
--------------------------------

docker:collection
+++++++++++++++++

Database collection name used to store containers information.

docker:registry
+++++++++++++++

For tsuru to work with multiple docker nodes, you will need a docker-registry.
This should be in the form of ``hostname:port``, the scheme cannot be present.

docker:registry-max-try
+++++++++++++++++++++++

Number of times tsuru will try to send a image to registry.

.. _config_bs:

docker:bs:image
+++++++++++++++

``docker:bs:image`` is the name of the Docker image to be used to create `bs
<https://github.com/tsuru/bs>`_ containers. The default value is "tsuru/bs",
which represents `the official image hosted at Docker Hub
<https://registry.hub.docker.com/u/tsuru/bs/>`_, maintained by the tsuru team.

docker:bs:reporter-interval
+++++++++++++++++++++++++++

``docker:bs:reporter-interval`` is the interval between status reporting from
bs to the tsuru API. The default value is 60 seconds.

docker:bs:socket
++++++++++++++++

``docker:bs:socket`` is the path to the Unix socket in the Docker host. This
should be configured so bs can connect to Docker via socket instead of TCP.
This is an optional setting, when omitted, bs will talk to the Dcoker API using
the TCP endpoint.

docker:bs:syslog-port
+++++++++++++++++++++

``docker:bs:syslog-port`` is the port in the Docker node that will be used by
the bs container for collecting logs. The default value is 1514.

.. _config_registry_auth:

docker:registry-auth:username
+++++++++++++++++++++++++++++

The username used for registry authentication. This setting is optional, for
registries with authentication disabled, it can be omitted.

docker:registry-auth:password
+++++++++++++++++++++++++++++

The password used for registry authentication. This setting is optional, for
registries with authentication disabled, it can be omitted.

docker:registry-auth:email
++++++++++++++++++++++++++

The email used for registry authentication. This setting is optional, for
registries with authentication disabled, it can be omitted.

docker:repository-namespace
+++++++++++++++++++++++++++

Docker repository namespace to be used for application and platform images. Images
will be tagged in docker as <docker:repository-namespace>/<platform-name> and
<docker:repository-namespace>/<app-name>

docker:max-workers
++++++++++++++++++

Maximum amount of threads to be created when starting new containers, so tsuru
doesn't start too much threads in the process of starting 1000 units, for
instance. Defaults to 0 which means unlimited.

.. _config_docker_router:

docker:router
+++++++++++++

Default router to be used to distribute requests to units. This should be the
name of a router configured under the ``routers:<name>`` key, see :ref:`routers
<config_routers>`.

For backward compatibility reasons, the value ``hipache`` is also supported, and
it will use either configuration available under ``router:hipache:*`` or
``hipache:*``, in this order.

Note that as of 0.10.0, routers may be associated to plans, if when creating an
application the chosen plan has a router value it will be used instead of the
value set in ``docker:router``.

The router defined in ``docker:router`` will only be used if the chosen plan
doesn't specify one.

docker:deploy-cmd
+++++++++++++++++

The command that will be called in your platform when a new deploy happens. The
default value for platforms supported in tsuru's basebuilder repository is
``/var/lib/tsuru/deploy``.

docker:security-opts
++++++++++++++++++++

This setting describes a list of security options that will be passed to
containers. This setting must be a list, and has no default value. If one wants
to specify just one value, it's still needed to use the list notation:

.. highlight: yaml

::

    docker:
      ...
      security-opts:
        - apparmor:PROFILE

For more details on the available options, please refer to the Docker
documentation: <https://docs.docker.com/reference/run/#security-configuration>.

docker:segregate
++++++++++++++++

Deprecated. As of tsuru 0.11.1, using segregate scheduler is the default
setting. See :doc:`/managing/segregate-scheduler` for details.

.. _config_scheduler_memory:

docker:scheduler:total-memory-metadata
++++++++++++++++++++++++++++++++++++++

This value describes which metadata key will describe the total amount of
memory, in bytes, available to a docker node.

docker:scheduler:max-used-memory
++++++++++++++++++++++++++++++++

This should be a value between 0.0 and 1.0 which describes which fraction of the
total amount of memory available to a server should be reserved for app units.

The amount of memory available is found based on the node metadata described by
``docker:scheduler:total-memory-metadata`` config setting.

If this value is set, tsuru will try to find a node with enough unreserved
memory to fit the creation of new units, based on how much memory is required by
the plan used to create the application. If no node with enough unreserved
memory is found, tsuru will ignore memory restrictions and let the scheduler
choose any node.

This setting, along with ``docker:scheduler:total-memory-metadata``, are also
used by node auto scaling. See :doc:`node auto scaling
</advanced_topics/node_scaling>` for more details.

.. _config_cluster_storage:

docker:cluster:storage
++++++++++++++++++++++

This setting has been removed. You shouldn't define it anymore, the only storage
available for the docker cluster is now ``mongodb``.

docker:cluster:mongo-url
++++++++++++++++++++++++

Connection URL to the mongodb server used to store information about the docker
cluster.

docker:cluster:mongo-database
+++++++++++++++++++++++++++++

Database name to be used to store information about the docker cluster.

docker:run-cmd:bin
++++++++++++++++++

The command that will be called on the application image to start the
application. The default value for platforms supported in tsuru's basebuilder
repository is ``/var/lib/tsuru/start``.

docker:run-cmd:port
+++++++++++++++++++

The tcp port that will be exported by the container to the node network. The
default value expected by platforms defined in tsuru's basebuilder repository is
``8888``.

docker:user
+++++++++++

The user tsuru will use to start the container. The value expected for
basebuilder platforms is ``ubuntu``.

docker:ssh:user
+++++++++++++++

Deprecated. You should set ``docker:user`` instead.

.. _config_healing:

docker:healing:heal-nodes
+++++++++++++++++++++++++

Boolean value that indicates whether tsuru should try to heal nodes that have
failed a specified number of times. Healing nodes is only available if the node
was created by tsuru itself using the IaaS configuration. Defaults to ``false``.

docker:healing:active-monitoring-interval
+++++++++++++++++++++++++++++++++++++++++

Number of seconds between calls to <server>/_ping in each one of the docker
nodes. If this value is 0 or unset tsuru will never call the ping URL. Defaults
to 0.

docker:healing:disabled-time
++++++++++++++++++++++++++++

Number of seconds tsuru disables a node after a failure. This setting is only
valid if ``heal-nodes`` is set to ``true``. Defaults to 30 seconds.

docker:healing:max-failures
+++++++++++++++++++++++++++

Number of consecutive failures a node should have before triggering a healing
operation. Only valid if ``heal-nodes`` is set to ``true``. Defaults to 5.

docker:healing:wait-new-time
++++++++++++++++++++++++++++

Number of seconds tsuru should wait for the creation of a new node during the
healing process. Only valid if ``heal-nodes`` is set to ``true``. Defaults to
300 seconds (5 minutes).

docker:healing:heal-containers-timeout
++++++++++++++++++++++++++++++++++++++

Number of seconds a container should be unresponsive before triggering the
recreation of the container. A container is deemed unresponsive if it doesn't
call the set unit status URL (/apps/{app}/units/{unit}) with a ``started``
status. If this value is 0 or unset tsuru will never try to heal unresponsive
containers. Defaults to 0.

docker:healing:events_collection
++++++++++++++++++++++++++++++++

Collection name in mongodb used to store information about triggered healing
events. Defaults to ``healing_events``.

docker:healthcheck:max-time
+++++++++++++++++++++++++++

Maximum time in seconds to wait for deployment time health check to be
successful. Defaults to 120 seconds.

.. _config_image_history_size:

docker:image-history-size
+++++++++++++++++++++++++

Number of images available for rollback using ``tsuru app-deploy-rollback``.
tsuru will try to delete older images, but it may not be able to due to it being
used as a layer to a newer image. tsuru will keep trying to remove these old
images until they are not used as layers anymore. Defaults to 10 images.

.. _config_docker_auto_scale:

docker:auto-scale:enabled
+++++++++++++++++++++++++

Enable node auto scaling. See :doc:`node auto scaling
</advanced_topics/node_scaling>` for more details. Defaults to false.

docker:auto-scale:wait-new-time
+++++++++++++++++++++++++++++++

Number of seconds tsuru should wait for the creation of a new node during the
scaling up process. Defaults to 300 seconds (5 minutes).

docker:auto-scale:group-by-metadata
+++++++++++++++++++++++++++++++++++

Name of the metadata present in nodes that will be used for grouping nodes into
clusters. See :doc:`node auto scaling </advanced_topics/node_scaling>` for more
details. Defaults to empty (all nodes belong the the same cluster).

docker:auto-scale:metadata-filter
+++++++++++++++++++++++++++++++++

Value of the metadata specified by `docker:auto-scale:group-by-metadata`. If
this is set, tsuru will only run auto scale algorithms for nodes in the cluster
defined by this value.

docker:auto-scale:max-container-count
+++++++++++++++++++++++++++++++++++++

Maximum number of containers per node, for count based scaling. See :doc:`node
auto scaling </advanced_topics/node_scaling>` for more details.

docker:auto-scale:prevent-rebalance
+++++++++++++++++++++++++++++++++++

Prevent rebalancing from happening when adding new nodes, or if a rebalance is
needed. See :doc:`node auto scaling </advanced_topics/node_scaling>` for more
details.

docker:auto-scale:run-interval
++++++++++++++++++++++++++++++

Number of seconds between two periodic runs of the auto scaling algorithm.
Defaults to 3600 seconds (1 hour).

docker:auto-scale:scale-down-ratio
++++++++++++++++++++++++++++++++++

Ratio used when scaling down. Must be greater than 1.0. See :doc:`node auto
scaling </advanced_topics/node_scaling>` for more details. Defaults to 1.33.

.. _iaas_configuration:

IaaS configuration
==================

tsuru uses IaaS configuration to automatically create new docker nodes and
adding them to your cluster when using ``docker-node-add`` command. See
:doc:`adding nodes</installing/adding-nodes>` for more details about how to use
this command.

.. attention::

    You should configure :ref:`queue <config_queue>` to be able to use IaaS.

General settings
----------------

iaas:default
++++++++++++

The default IaaS tsuru will use when calling ``docker-node-add`` without
specifying ``iaas=<iaas_name>`` as a metadata. Defaults to ``ec2``.

iaas:node-protocol
++++++++++++++++++

Which protocol to use when accessing the docker api in the created node.
Defaults to ``http``.

iaas:node-port
++++++++++++++

In which port the docker API will be accessible in the created node. Defaults to
``2375``.

iaas:collection
+++++++++++++++

Collection name on database containing information about created machines.
Defaults to ``iaas_machines``.

EC2 IaaS
--------

iaas:ec2:key-id
+++++++++++++++

Your AWS key id.

iaas:ec2:secret-key
+++++++++++++++++++

Your AWS secret key.

iaas:ec2:user-data
++++++++++++++++++

A url for which the response body will be sent to ec2 as user-data.
Defaults to a script which will run `tsuru now installation
<https://github.com/tsuru/now>`_.

iaas:ec2:wait-timeout
+++++++++++++++++++++

Number of seconds to wait for the machine to be created. Defaults to 300 (5
minutes).

CloudStack IaaS
---------------

iaas:cloudstack:api-key
+++++++++++++++++++++++

Your api key.

iaas:cloudstack:secret-key
++++++++++++++++++++++++++

Your secret key.

iaas:cloudstack:url
+++++++++++++++++++

The url for the cloudstack api.

iaas:cloudstack:user-data
+++++++++++++++++++++++++

A url for which the response body will be sent to cloudstack as user-data.
Defaults to a script which will run `tsuru now installation
<https://github.com/tsuru/now>`_.

iaas:cloudstack:wait-timeout
++++++++++++++++++++++++++++

Number of seconds to wait for the machine to be created. Defaults to 300 (5
minutes).

.. _config_custom_iaas:

Custom IaaS
-----------

You can define a custom IaaS based on an existing provider. Any configuration
keys with the format ``iaas:custom:<name>`` will create a new IaaS with
``name``.

iaas:custom:<name>:provider
+++++++++++++++++++++++++++

The base provider name, it can be one of the supported providers: ``cloudstack``
or ``ec2``.

iaas:custom:<name>:<any_other_option>
+++++++++++++++++++++++++++++++++++++

This will overwrite the value of ``iaas:<provider>:<any_other_option>`` for this
IaaS. As an example, having the configuration below would allow you to call
``tsuru-admin docker-node-add iaas=region1_cloudstack ...``:

.. highlight:: yaml

::

    iaas:
        custom:
            region1_cloudstack:
                provider: cloudstack
                url: http://region1.url/
                secret-key: mysecretkey
        cloudstack:
            api-key: myapikey

Sample file
===========

Here is a complete example:

.. highlight:: yaml

::

    listen: "0.0.0.0:8080"
    debug: true
    host: http://<machine-public-addr>:8080 # This port must be the same as in the "listen" conf
    admin-team: admin
    auth:
        user-registration: true
        scheme: native
    database:
        url: <your-mongodb-server>:27017
        name: tsurudb
    pubsub:
        redis-host: <your-redis-server>
        redis-port: 6379
    queue:
        mongo-url: <your-mongodb-server>:27017
        mongo-database: queuedb
    git:
        api-server: http://<your-gandalf-server>:8000
    provisioner: docker
    docker:
        router: hipache
        collection: docker_containers
        repository-namespace: tsuru
        deploy-cmd: /var/lib/tsuru/deploy
        cluster:
            storage: mongodb
            mongo-url: <your-mongodb-server>:27017
            mongo-database: cluster
        run-cmd:
            bin: /var/lib/tsuru/start
            port: "8888"
    routers:
        hipache:
            type: hipache
            domain: <your-hipache-server-ip>.xip.io
            redis-server: <your-redis-server-with-port>


text:
volunteer_venice
================

Volunteer Venice


text:
import sys

from setuptools import setup
from setuptools import find_packages

if sys.version_info[0] == 3:
    LONG_DESCRIPTION = open('README.rst', encoding='utf-8').read()
else:
    LONG_DESCRIPTION = open('README.rst').read()

if sys.version_info[0] == 3:
    REQUIREMENTS = open('requirements.txt', encoding='utf-8').readlines()
else:
    REQUIREMENTS = open('requirements.txt').readlines()

REQUIREMENTS = [req.rstrip() for req in REQUIREMENTS]

setup(
    name='prettyplotlib',
    version='0.1.5',
    author='Olga B. Botvinnik',
    author_email='olga.botvinnik@gmail.com',
    packages=find_packages(),
    license='MIT License',
    url='http://olgabot.github.io/prettyplotlib',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Topic :: Scientific/Engineering'
    ],
    description='Painlessly create beautiful default `matplotlib` plots.',
    long_description=LONG_DESCRIPTION,
    install_requires=REQUIREMENTS
)


text:
package roboticshours;

import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * A class to handle encryption operations for this project.
 * This class utilizes AES symmetric encryption and the SHA-256 hash algorithm.
 *
 * Personal note: This class is my first foray into the weird, weird world of Java's crypto platform.
 *
 * @author Alan
 */
public class Encryptor{

    private static Cipher cipher;
    private static MessageDigest sha;
    private static SecretKeySpec keySpec;
    private static byte[] hashedCredentials;

    static{
       try{
            cipher = Cipher.getInstance("AES");
            sha = MessageDigest.getInstance("SHA-256");
        }
        catch(NoSuchAlgorithmException | NoSuchPaddingException e){
            System.out.println("Apparently AES or SHA-256 don't exist.");
        }
    } //Ensures instantiation of Cipher and MessageDigest BEFORE method execution.

    /**
     * Creates a {@link SecretKeySpec} in order to initialize the {@link Cipher} object for crypto.
     * This method stores the preKey array in the instance variable hashedCredentials,
     * hashes the preKey array using 1024 rounds of SHA-256,
     * and takes the first 16 bytes of the hashed array to create a {@link SecretKeySpec}.
     * @param preKey a byte array used to create the keySpec
     */
    public static void makeKey(byte[] preKey){
        hashedCredentials = preKey; //Stores a copy of the pre-key byte array
        byte[] key = hash(preKey, "XpmynaaIhf3boZhsr47BRbVOsJNLpOTO2ZfpkjghRoHM1fmwo12bQQyfT4STV3vx", 1024); //Hashes the pre-key with a static random hash 1024 times for good measure
        key = Arrays.copyOf(key, 16); //Takes the first 16 bytes from the key material
        keySpec = new SecretKeySpec(key, "AES"); //Creates AES key spec from credentials' bytes after 2 rounds (hopefully) of 1024x salted hash
    }

    /**
     * @return  a byte array representation of the key material.
     */
    public static byte[] getKey(){
        return hashedCredentials;
    }

    /**
     *  Sets the Cipher to encryption mode.
     */
    public static void preEncrypt(){
        try {
            cipher.init(Cipher.ENCRYPT_MODE, keySpec); //Initializes AES cipher to encrypt using hashed key
        } catch (InvalidKeyException e) {
            System.out.println(e + "Location: preEncrypt");
        }
    }

    /**
     *  Sets the Cipher to decryption mode using keySpec
     */
    public static void preDecrypt(){
        try {
            cipher.init(Cipher.DECRYPT_MODE, keySpec); //Initializes AES cipher to encrypt using hashed key
        } catch (InvalidKeyException e) {
            System.out.println(e + "Location: preDecrypt");
        }
    }

    /**
     * Encrypts a byte array.
     * This method sets the Cipher to encrypt mode before encrypting.
     *
     * @param b The byte array to be encrypted
     * @return  The encrypted byte array
     * @throws IllegalBlockSizeException    Thrown if the provided data does not match the block size of AES (16)
     * @throws BadPaddingException          Thrown if the padding on the provided data is incorrect. (Check the key)
     */
    public static byte[] encrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException{
        preEncrypt();
        return cipher.doFinal(b);
    }

    /**
     * Encrypts a byte array.
     * This method sets the Cipher to decrypt mode before decrypting.
     *
     * @param b The byte array to be decrypted
     * @return  The decrypted byte array
     * @throws IllegalBlockSizeException    Thrown if the provided data does not match the block size of AES (16)
     * @throws BadPaddingException          Thrown if the padding on the provided data is incorrect. (Check the key)
     */
    public static byte[] decrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException{
        preDecrypt();
        return cipher.doFinal(b);
    }

    //TODO
    //Note to self: Pick a hash method and stick with it. Don't leave unimplemented methods.

    /**
     * Hashes a byte array with a static random salt for a given number of iterations.
     *
     * @param b             The byte array to be hashed
     * @param iterations    The number of rounds to hash the byte array
     * @return              The hashed byte array
     */
    public static byte[] hash(byte[] b, int iterations){

        byte[] salt = "usOLwyhs8n1A5uenhr9RUZDBQCcOcvPhZv2PTHLOdeOs3V8cIEMZFdW8ihMO8Vfm".getBytes(); //Fixed salt

        for(int i = 0; i < iterations; i++){
            byte[] temp = new byte[b.length + salt.length]; //Makes a new array.
            System.arraycopy(b, 0, temp, 0, b.length);      //Copies b to the temporary array.
            System.arraycopy(salt, 0, temp, b.length, salt.length); //Appends the salt to the temporary array.
            b = sha.digest(temp);   //Sets the byte array to the SHA digest of the array with appended salt.
        }

        return b;
    }

    /**
     * Hashes a byte array with a provided salt for a given number of iterations.
     * This method will most likely not be used.
     * @param b             The byte array to be hashed
     * @param salt          The provided salt. It is recommended that this be random.
     * @param iterations    The number of rounds to hash the byte array
     * @return              The hashed byte array
     */
    public static byte[] hash(byte[] b, String salt, int iterations){

        byte[] saltBytes = salt.getBytes();

        for(int i = 0; i < iterations; i++){
            byte[] temp = new byte[b.length + saltBytes.length];
            System.arraycopy(b, 0, temp, 0, b.length);
            System.arraycopy(saltBytes, 0, temp, b.length, saltBytes.length);
            b = sha.digest(temp);
        }

        return b;
    }

    /*public static byte[] hash(byte[] b, long seed, int iterations){

        //Generate a new salt every time
        char[] salt = null;

        for(int i = 0; i < iterations; i++){
            byte[] temp = new byte[b.length + salt.length];
            System.arraycopy(b, 0, temp, 0, b.length);
            System.arraycopy(salt, 0, temp, b.length, salt.length);
            b = temp;
        }

        return b;
    } //If there is extra time, implement new salts each hash using a seeded PSRNG whose IV is generated by a PSRNG and stored in the user's file.
    */

    /**
     * Converts a char array to a byte array.
     * Literally just goes through each index of the char array and
     * casts each char as a byte before storing it in the byte array.
     * @param c The char array to be converted
     * @return  A converted byte array
     */
    public static byte[] charToByte(char[] c){
        byte[] b = new byte[c.length];
        for(int i = 0; i < c.length; i++){
            b[i] = (byte)c[i];
            c[i] = (char)0;
        }
        return b;
    }
    /**
     * Converts a byte array to a char array.
     * Literally just goes through each index of the byte array and
     * casts each byte as a char before storing it in the char array.
     * @param b The byte array to be converted
     * @return  A converted char array
     */
    public static char[] byteToChar (byte[] b){
        char[] c = new char[b.length];  //Create a new char array that's the same size as the byte array
        for(int i = 0; i < b.length; i++){
            c[i] = (char)b[i];  //Set each index of the char array to the char representation of the byte array.
            b[i] = (byte)0;     //Clear the byte array.
        }
        return c;
    }
}


text:
/* 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 org.camunda.bpm.integrationtest.deployment.callbacks;

import org.junit.Assert;

import org.camunda.bpm.integrationtest.util.AbstractFoxPlatformIntegrationTest;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Daniel Meyer
 *
 */
@RunWith(Arquillian.class)
public class PostDeployFailureTest_OTHERS extends AbstractFoxPlatformIntegrationTest {

  @Deployment(name="fail")
  public static WebArchive createDeployment1() {
   return PostDeployFailureTest_JBOSS.createDeployment1();
  }

  @Deployment(name="checker")
  public static WebArchive createDeployment2() {
    return initWebArchiveDeployment("checker.war");
  }

  @Test
  @OperateOnDeployment("checker")
  public void test() {

    // make sure the deployment of the first app was rolled back

    long count = processEngine.getRepositoryService()
      .createDeploymentQuery()
      .count();

    Assert.assertEquals(1, count);

  }

}


text:
if str(variables.get("DOCKER_ENABLED")).lower() == 'true':
    #Be aware, that the prefix command is internally split by spaces. So paths with spaces won't work.
    # Prepare Docker parameters
    containerName = variables.get("DOCKER_IMAGE")
    dockerRunCommand =  'docker run '
    dockerParameters = '--rm '
    # Prepare ProActive home volume
    paHomeHost = variables.get("PA_SCHEDULER_HOME")
    paHomeContainer = variables.get("PA_SCHEDULER_HOME")
    proActiveHomeVolume = '-v '+paHomeHost +':'+paHomeContainer+' '
    # Prepare working directory (For Dataspaces and serialized task file)
    workspaceHost = localspace
    workspaceContainer = localspace
    workspaceVolume = '-v '+localspace +':'+localspace+' '
    # Prepare container working directory
    containerWorkingDirectory = '-w '+workspaceContainer+' '
    # Save pre execution command into magic variable 'preJavaHomeCmd', which is picked up by the node
    preJavaHomeCmd = dockerRunCommand + dockerParameters + proActiveHomeVolume + workspaceVolume + containerWorkingDirectory + containerName
else:
    print("Fork environment disabled")


text:
var config = require('./config'),
    compression = require('compression'),
    express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    request = require('request');

/**
 * The main export; initialises a new express application.
 * @returns {Object} The express application.
 */
function main() {
    var app = express();

    // configure the view engine
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'hbs');

    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(compression());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());

    // setup the www redirect
    app.set('trust proxy', true);
    app.use(function(req, res, next) {
        if (req.headers.host.slice(0, 4) === 'www.') {
            var newHost = req.headers.host.slice(4);
            return res.redirect(301, req.protocol + '://' + newHost + req.originalUrl);
        }

        next();
    });

    // setup the api routes
    app.use('/Platform/Destiny/*?', function(req, res) {
        var options = {
            url: 'https://www.bungie.net' + req.originalUrl,
            headers: {
                'Content-Type': 'application/json',
                'X-API-KEY': config.api.key
            }
        };

        req.pipe(request(options)).pipe(res);
    });

    // setup the app route
    switch (config.env) {
        case 'production':
            console.log('*** [production] environment ***');

            // serve the index with no-caching
            app.get('/', function(req, res) {
                res.sendFile(path.join(__dirname, '../dist/index.html'))
            });

            // serve the assets with caching, and register the SPA handler
            serveConfig();
            serveStatic('../dist/', config.contentMaxAge);
            app.use('/js/**/*.html', function(req, res) {
                send404(req, res, 'Unable to load Angular view separately.');
            });
            serveSpaHandler('../dist/index.html');
            break;
        default:
            console.log('*** [dev] environment ***');
            app.use(logger('dev'));

            // serve the assets and register the SPA handler
            serveConfig();
            serveStatic('../client/');
            serveStatic('../');
            serveSpaHandler('../client/index.html');
            break;
    };

    // configure error handling
    app.use(function(err, req, res, next) {
        res.status(err.status || 500).render('error', {
            message: err.message,
            error: config.env === 'dev' ? err : {}
        });
    });

    /**
     * Register the configuration renderer.
     */
    function serveConfig() {
        app.get('/js/app.config.js', function(req, res) {
            res.render('config', config);
        });
    }

    /**
     * Registers the SPA handler.
     * @param {string} relativePath The path handling the requests.
     */
    function serveSpaHandler(relativePath) {
        var staticPath = path.join(__dirname, relativePath);
        app.get('*', function(req, res) {
            res.sendFile(staticPath);
        })
    }

    /**
     * Registers the static content with a expiration header.
     * @param {String} relativeRoot The relative path to the static folder.
     * @param {String|Number} maxAge The max age of the content
     */
    function serveStatic(relativeRoot, maxAge) {
        var root = path.join(__dirname, relativeRoot);

        app.use(express.static(root, {
            maxAge: maxAge || 0
        }));
    }

    /**
     * Returns a 404 to the response object.
     * @param {Object} req The request being made.
     * @param {Object} res The response.
     * @param {String} description The reason for the 404.
     */
    function send404(req, res, description) {
        var data = {
            status: 404,
            message: 'Not Found',
            description: description,
            url: req.originalUrl
        };

        res.status(404)
            .send(data)
            .end();
    }

    return app;
}

module.exports = main;


text:
package org.apache.cassandra.db;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;

import static junit.framework.Assert.assertEquals;

public class HintedHandOffTest extends SchemaLoader
{

    public static final String TABLE4 = "Keyspace4";
    public static final String STANDARD1_CF = "Standard1";
    public static final String COLUMN1 = "column1";

    // Test compaction of hints column family. It shouldn't remove all columns on compaction.
    @Test
    public void testCompactionOfHintsCF() throws Exception
    {
        // prepare hints column family
        Table systemTable = Table.open("system");
        ColumnFamilyStore hintStore = systemTable.getColumnFamilyStore(SystemTable.HINTS_CF);
        hintStore.clearUnsafe();
        hintStore.metadata.gcGraceSeconds(36000); // 10 hours
        hintStore.setCompactionStrategyClass(SizeTieredCompactionStrategy.class.getCanonicalName());
        hintStore.disableAutoCompaction();

        // insert 1 hint
        RowMutation rm = new RowMutation(TABLE4, ByteBufferUtil.bytes(1));
        rm.add(new QueryPath(STANDARD1_CF,
                             null,
                             ByteBufferUtil.bytes(String.valueOf(COLUMN1))),
               ByteBufferUtil.EMPTY_BYTE_BUFFER,
               System.currentTimeMillis());

        RowMutation.hintFor(rm, UUID.randomUUID()).apply();

        // flush data to disk
        hintStore.forceBlockingFlush();
        assertEquals(1, hintStore.getSSTables().size());

        // submit compaction
        FBUtilities.waitOnFuture(HintedHandOffManager.instance.compact());
        while (CompactionManager.instance.getPendingTasks() > 0 || CompactionManager.instance.getActiveCompactions() > 0)
            TimeUnit.SECONDS.sleep(1);

        // single row should not be removed because of gc_grace_seconds
        // is 10 hours and there are no any tombstones in sstable
        assertEquals(1, hintStore.getSSTables().size());
    }
}


text:
module Control where

import SudokuCore
import Solver
import qualified Grader
import Sequence
import Digger
import Warehouse

data Instruction = MakeSolutions Int
                 | MakePuzzles
                 | GradePuzzles

run :: Warehouse -> Instruction -> Warehouse
run wh (MakeSolutions amount) =
  let (sols, newRest) = takeSolutions amount $ getRestSolutions wh
  in insertRestSolutions newRest $ insertSolutions sols wh
run wh MakePuzzles =
  let puzzles = map (\grid ->
                      (,) grid $ makePuzzles grid) $ getSolutions wh
  in insertPuzzles puzzles wh
run wh GradePuzzles =
  let graded = map gradePuzzle $ getPuzzles wh
  in insertGrades graded wh

makePuzzles :: Grid -> [Puzzle]
makePuzzles grid = map newPuzzle $ dig grid mirrored

newPuzzle :: Grid -> Puzzle
newPuzzle grid = Puzzle { puzzle = grid, grade = Nothing}

gradePuzzle :: Puzzle -> Puzzle
gradePuzzle old =
  Puzzle {puzzle = puzzle old
         , grade = Grader.grade $ puzzle old}


text:
#include "qplatformmenu.h"

#include <qpa/qplatformtheme.h>
#include <private/qguiapplication_p.h>

QT_BEGIN_NAMESPACE

QPlatformMenuItem *QPlatformMenu::createMenuItem() const
{
    return QGuiApplicationPrivate::platformTheme()->createPlatformMenuItem();
}

QT_END_NAMESPACE


text:
var timeouts = {
    keydown: null
}

var entryForm = {
    form: function(){return $("#entry_form");},
    previewImage: function(){return $("#preview");},
    isModeCreate: function () {
        return (entryForm.form().data('mode') === 'create');
    },
    fields: {
        url: function(){return $('input#entry_url');},
        title: function(){return $('input#entry_title');},
        tags: function(){return $('input#entry_tags');},
        categories: function(){return $('input[name="entry[category]"]');},
        notificationSpan: function(){return $('#metainfo-notification');}
    }
}

var application = {
    loaderHtml: 'Loading...',
    getMetaInfo: function($urlElement){
        entryForm.fields.notificationSpan().html(application.loaderHtml);
        const url = $urlElement.data('metainfo-url');

        $.ajax({
            url: url,
            dataType: 'json',
            data: {
                url: $urlElement.val(),
                edit_id: entryForm.form().data('edit-id')
            },
            success: function(data){
                entryForm.fields.notificationSpan().html('');

                if (entryForm.fields.title().val() == '') {
                    entryForm.fields.title().val(data.title);
                }

                if (data.image_url) {
                    var previewImage = $('')
                        .attr('src', data.image_url)
                        .addClass('card-img-top');
                    entryForm.previewImage().html(previewImage);
                }

                var id = entryForm.fields.categories().filter('[value=' + data.category + ']').attr('id');
                if (id) {
                    $('[for=' + id + ']').trigger('click');
                }
                entryForm.fields.tags().focus();

                $urlElement.parent().removeClass('has-error');
                if (data.url_duplicate) {
                    $urlElement.parent().addClass('has-error');
                    entryForm.fields.notificationSpan().html('URL already taken');
                }
            },
            error: function() {
                entryForm.fields.notificationSpan().html('error retrieving URL meta data');
            }
        });
    },
    getMetaInfoDelayed: function(){
        var $element = $(this);
        clearTimeout(timeouts.keydown);
        timeouts.keydown = setTimeout(function(){application.getMetaInfo($element)}, 500);
    },
    registerEvents: function($domElement) {
        if (entryForm.isModeCreate()) {
            entryForm.fields.url()
                .on('input', application.getMetaInfoDelayed)
                .trigger('input');
        }

        entryForm.form().keydown(function(event) {
            if (event.ctrlKey && event.keyCode == 13) {
                entryForm.form().submit();
            }
        });

        var $tagInput = entryForm.fields.tags();
        if ($tagInput.length > 0) {
            new Awesomplete($tagInput[0],{
                filter: function(text, input) {
                    return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
                },
                replace: function(text) {
                    var before = this.input.value.match(/^.+,\s*|/)[0];
                    this.input.value = before + text + ", ";
                }
            });
        }

        $domElement.find('.visit-link').mousedown(function(e){
            $.ajax($(this).data('link'), {type: 'POST'});
        });

        $domElement.find('.deferred-image').imageloader();
    }
}

// all JS is already loading defered
// therefore document.ready und window.load already happened
// and won't be triggered again

application.registerEvents($(document));


text:
{{'Element' | i18next}} {{'Remove' | i18next}}

			{{'Id' | i18next}}
			<input name="id" type="text" maxlength="128" class="form-control"
				ng-model="node.id">

			{{'CSS Class' | i18next}}
			<input name="cssClass" type="text" maxlength="128" class="form-control"
				ng-model="node.cssclass">

{{'Image' | i18next}} {{'Remove' | i18next}}

			{{'Caption' | i18next}}
			<input name="field-caption" type="text" maxlength="128" class="form-control"
				ng-model="element.caption">


text:
namespace gpopt
{
// type definition of corresponding dynamic pointer array
class COrderSpec;
typedef CDynamicPtrArray<COrderSpec, CleanupRelease> COrderSpecArray;

using namespace gpos;

// fwd declaration
class CColRefSet;

//---------------------------------------------------------------------------
//	@class:
//		COrderSpec
//
//	@doc:
//		Array of Order Expressions
//
//---------------------------------------------------------------------------
class COrderSpec : public CPropSpec
{
public:
	enum ENullTreatment
	{
		EntAuto,  // default behavior, as implemented by operator

		EntFirst,
		EntLast,

		EntSentinel
	};

private:
	//---------------------------------------------------------------------------
	//	@class:
	//		COrderExpression
	//
	//	@doc:
	//		Spec of sort order component consisting of
	//
	//			1. sort operator's mdid
	//			2. column reference
	//			3. definition of NULL treatment
	//
	//---------------------------------------------------------------------------
	class COrderExpression
	{
	private:
		// MD id of sort operator
		gpmd::IMDId *m_mdid;

		// sort column
		const CColRef *m_pcr;

		// null treatment
		ENullTreatment m_ent;

		// private copy ctor
		COrderExpression(const COrderExpression &);

	public:
		// ctor
		COrderExpression(gpmd::IMDId *mdid, const CColRef *colref,
						 ENullTreatment ent);

		// dtor
		virtual ~COrderExpression();

		// accessor of sort operator midid
		gpmd::IMDId *
		GetMdIdSortOp() const
		{
			return m_mdid;
		}

		// accessor of sort column
		const CColRef *
		Pcr() const
		{
			return m_pcr;
		}

		// accessor of null treatment
		ENullTreatment
		Ent() const
		{
			return m_ent;
		}

		// check if order specs match
		BOOL Matches(const COrderExpression *poe) const;

		// print
		IOstream &OsPrint(IOstream &os) const;

#ifdef GPOS_DEBUG
		// debug print for interactive debugging sessions only
		void DbgPrint() const;
#endif	// GPOS_DEBUG

	};	// class COrderExpression

	// array of order expressions
	typedef CDynamicPtrArray<COrderExpression, CleanupDelete>
		COrderExpressionArray;

	// memory pool
	CMemoryPool *m_mp;

	// components of order spec
	COrderExpressionArray *m_pdrgpoe;

	// private copy ctor
	COrderSpec(const COrderSpec &);

	// extract columns from order spec into the given column set
	void ExtractCols(CColRefSet *pcrs) const;

public:
	// ctor
	explicit COrderSpec(CMemoryPool *mp);

	// dtor
	virtual ~COrderSpec();

	// number of sort expressions
	ULONG
	UlSortColumns() const
	{
		return m_pdrgpoe->Size();
	}

	// accessor of sort operator of the n-th component
	IMDId *
	GetMdIdSortOp(ULONG ul) const
	{
		COrderExpression *poe = (*m_pdrgpoe)[ul];
		return poe->GetMdIdSortOp();
	}

	// accessor of sort column of the n-th component
	const CColRef *
	Pcr(ULONG ul) const
	{
		COrderExpression *poe = (*m_pdrgpoe)[ul];
		return poe->Pcr();
	}

	// accessor of null treatment of the n-th component
	ENullTreatment
	Ent(ULONG ul) const
	{
		COrderExpression *poe = (*m_pdrgpoe)[ul];
		return poe->Ent();
	}

	// check if order spec has no columns
	BOOL
	IsEmpty() const
	{
		return UlSortColumns() == 0;
	}

	// append new component
	void Append(gpmd::IMDId *mdid, const CColRef *colref, ENullTreatment ent);

	// extract colref set of order columns
	virtual CColRefSet *PcrsUsed(CMemoryPool *mp) const;

	// property type
	virtual EPropSpecType
	Epst() const
	{
		return EpstOrder;
	}

	// check if order specs match
	BOOL Matches(const COrderSpec *pos) const;

	// check if order specs satisfies req'd spec
	BOOL FSatisfies(const COrderSpec *pos) const;

	// append enforcers to dynamic array for the given plan properties
	virtual void AppendEnforcers(CMemoryPool *mp, CExpressionHandle &exprhdl,
								 CReqdPropPlan *prpp,
								 CExpressionArray *pdrgpexpr,
								 CExpression *pexpr);

	// hash function
	virtual ULONG HashValue() const;

	// return a copy of the order spec with remapped columns
	virtual COrderSpec *PosCopyWithRemappedColumns(
		CMemoryPool *mp, UlongToColRefMap *colref_mapping, BOOL must_exist);

	// return a copy of the order spec after excluding the given columns
	virtual COrderSpec *PosExcludeColumns(CMemoryPool *mp, CColRefSet *pcrs);

	// print
	virtual IOstream &OsPrint(IOstream &os) const;

	// matching function over order spec arrays
	static BOOL Equals(const COrderSpecArray *pdrgposFirst,
					   const COrderSpecArray *pdrgposSecond);

	// combine hash values of a maximum number of entries
	static ULONG HashValue(const COrderSpecArray *pdrgpos, ULONG ulMaxSize);

	// print array of order spec objects
	static IOstream &OsPrint(IOstream &os, const COrderSpecArray *pdrgpos);

	// extract colref set of order columns used by elements of order spec array
	static CColRefSet *GetColRefSet(CMemoryPool *mp, COrderSpecArray *pdrgpos);

	// filter out array of order specs from order expressions using the passed columns
	static COrderSpecArray *PdrgposExclude(CMemoryPool *mp,
										   COrderSpecArray *pdrgpos,
										   CColRefSet *pcrsToExclude);

};	// class COrderSpec

}  // namespace gpopt

#endif	// !GPOPT_COrderSpec_H

// EOF