text:
<title>Berkeley DB: DB_ENV->txn_recover</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">

DB_ENV->txn_recover

<tt>

#include <db.h>

int
DB_ENV->txn_recover(DB_ENV *dbenv, DB_PREPLIST preplist[],
    long count, long *retp, u_int32_t flags);

Description: DB_ENV->txn_recover

Database environment recovery restores transactions that were prepared,
but not yet resolved at the time of the system shut down or crash, to
their state prior to the shut down or crash, including any locks
previously held.  The DB_ENV->txn_recover method returns a list of those
prepared transactions.

The DB_ENV->txn_recover method should only be called after the environment has
been recovered.

Multiple threads of control may call DB_ENV->txn_recover, but only one
thread of control may resolve each returned transaction, that is, only
one thread of control may call DB_TXN->commit or DB_TXN->abort
on each returned transaction.  Callers of DB_ENV->txn_recover must call
DB_TXN->discard to discard each transaction they do not resolve.

On return from DB_ENV->txn_recover, the preplist parameter will
be filled in with a list of transactions that must be resolved by the
application (committed, aborted or discarded).  The preplist
parameter is a structure of type DB_PREPLIST; the following DB_PREPLIST
fields will be filled in:

DB_TXN * txn;

The transaction handle for the transaction.

u_int8_t gid[DB_XIDDATASIZE];

The global transaction ID for the transaction.  The global transaction
ID is the one specified when the transaction was prepared.  The
application is responsible for ensuring uniqueness among global
transaction IDs.

The DB_ENV->txn_recover method
returns a non-zero error value on failure
and 0 on success.

Parameters

 count

The count parameter specifies the number of available entries
in the passed-in preplist array.  The retp parameter
returns the number of entries DB_ENV->txn_recover has filled in, in the
array.

 flags

The flags parameter must be set to one of the following values:

DB_FIRST

Begin returning a list of prepared, but not yet resolved transactions.
Specifying this flag begins a new pass over all prepared, but not yet
completed transactions, regardless of whether they have already been returned
in previous calls to DB_ENV->txn_recover.
Calls to DB_ENV->txn_recover from different threads of control should not
be intermixed in the same environment.

DB_NEXT

Continue returning a list of prepared, but not yet resolved transactions,
starting where the last call to DB_ENV->txn_recover left off.

 preplist

The preplist parameter references memory into which
 the list of transactions to be resolved by the application is copied.

Class
DB_ENV, DB_TXN

See Also
Transaction Subsystem and Related Methods
</tt>

Copyright (c) 1996,2008 Oracle.  All rights reserved.


text:
package com.example.android.project1movies.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

/**
 * A solution to project 1 of the Android Nanodegree by Udacity, as
 * described in
 * https://docs.google.com/document/d/1ZlN1fUsCSKuInLECcJkslIqvpKlP7jWL2TP9m6UiA6I/pub?embedded=true
 *
 * @author Laurie White
 * @version 5 August 2015
 */
public class MainActivity extends AppCompatActivity {

    private final String LOG_TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new MovieFragment())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

redpajama_set_name: RedPajamaGithub


text:
+(function () {

  'use strict';

  angular
    .module('DashboardApplication')
    .controller('CommentController', ['CommentRest', 'NewsRest', CommentController]);

  function CommentController(CommentRest, NewsRest) {

    var vm = this;
    vm.getComments = getComments;

    function getCategories() {
      NewsRest.getList().then(function (response) {

      })
    }
    getCategories();

    function getComments() {
      CommentRest.one(vm.newsId).get().then(function (response) {
        vm.comments = response.data;
      })
    }

  }
})();


text: <!DOCTYPE html>


text:
package ch.usi.inf.l3.sana.robustj.errors

import ch.usi.inf.l3.sana
import sana.tiny.errors.ErrorCode
import sana.arrooj

trait ErrorCodes extends arrooj.errors.ErrorCodes {
  case object THROWING_NON_THROWABLE extends ErrorCode {
    val message: String =
      "The thrown expression must be of type java.lang.Throwable"
  }

  case object CATCHING_NON_THROWABLE extends ErrorCode {
    val message: String =
      "Catch parameter must be of type java.lang.Throwable"
  }

  case object NON_THROWABLE_IN_THROWS_CLAUSE extends ErrorCode {
    val message: String =
      "Incompatible types"
  }

  case object NO_CATCH_FOUND extends ErrorCode {
    val message: String =
      "``try'' statements should catch at least one exception"
  }

  case object UNREPORTED_EXCEPTION extends ErrorCode {
    val message: String =
      "Unreported exceptionforeach"
  }

  case object HANDLING_NON_THROWN_EXCEPTION extends ErrorCode {
    val message: String =
      "Exception is never thrown"
  }
}

object ErrorCodes extends ErrorCodes


text:
A collection of utilities

[![Build Status](https://travis-ci.org/crolfe/utils.svg?branch=master)](https://travis-ci.org/crolfe/utils)


text:
package com.thaiopensource.xml.dtd.om;

public class IncludedSection extends TopLevel
{

  private final Flag flag;
  private final TopLevel [] contents;

  public IncludedSection (final Flag flag, final TopLevel [] contents)
  {
    this.flag = flag;
    this.contents = contents;
  }

  @Override
  public int getType ()
  {
    return INCLUDED_SECTION;
  }

  public Flag getFlag ()
  {
    return flag;
  }

  public TopLevel [] getContents ()
  {
    final TopLevel [] tem = new TopLevel [contents.length];
    System.arraycopy (contents, 0, tem, 0, contents.length);
    return tem;
  }

  @Override
  public void accept (final TopLevelVisitor visitor) throws Exception
  {
    visitor.includedSection (flag, getContents ());
  }

}


text:
{-# LANGUAGE BangPatterns             #-}
{-# LANGUAGE CPP                      #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE RankNTypes               #-}

module Data.HashTable.Test.Common
  ( FixedTableType
  , dummyTable
  , forceType
  , tests
  ) where

------------------------------------------------------------------------------
#if !MIN_VERSION_base(4,8,0)
import           Control.Applicative                  (pure, (<$>))
#endif
import           Control.Applicative                  ((<|>))
import           Control.Monad                        (foldM_, liftM, when)
import qualified Control.Monad                        as Monad
import           Data.IORef
import           Data.List                            hiding (delete, insert,
                                                       lookup)
import           Data.Vector                          (Vector)
import qualified Data.Vector                          as V
import qualified Data.Vector.Mutable                  as MV
import           Prelude                              hiding (lookup, mapM_)
import           System.Random.MWC
import           System.Timeout
import           Test.Framework
import           Test.Framework.Providers.HUnit
import           Test.Framework.Providers.QuickCheck2
import           Test.HUnit                           (assertEqual,
                                                       assertFailure)
import           Test.QuickCheck                      (arbitrary, choose,
                                                       sample')
import           Test.QuickCheck.Monadic              (PropertyM, assert,
                                                       forAllM, monadicIO, pre,
                                                       run)
------------------------------------------------------------------------------
import qualified Data.HashTable.Class                 as C
import           Data.HashTable.Internal.Utils        (unsafeIOToST)
import           Data.HashTable.IO

#ifndef PORTABLE
import           Control.Concurrent
import           Foreign                              (Ptr, free, malloc, poke)
import           Foreign.C.Types                      (CInt (..))
#endif

------------------------------------------------------------------------------
type FixedTableType h = forall k v . IOHashTable h k v
type HashTest = forall h . C.HashTable h => String -> FixedTableType h -> Test
data SomeTest = SomeTest HashTest

------------------------------------------------------------------------------
announce :: Show a => String -> a -> IO ()
#ifdef DEBUG
announce nm x = do
    putStrLn "\n============================="
    putStrLn $ concat [ "starting "
                      , nm
                      , " with "
                      , show x
                      ]
    putStrLn "============================="
#else
announce _ _ = return ()
#endif

------------------------------------------------------------------------------
announceQ :: Show a => String -> a -> PropertyM IO ()
announceQ nm x = run $ announce nm x

------------------------------------------------------------------------------
assertEq :: (Eq a, Show a) =>
            String -> a -> a -> PropertyM IO ()
assertEq s expected got =
    when (expected /= got) $ do
      fail $ s ++ ": expected '" ++ show expected ++ "', got '"
               ++ show got ++ "'"

------------------------------------------------------------------------------
forceType :: forall m h k1 k2 v1 v2 . (Monad m, C.HashTable h) =>
             IOHashTable h k1 v1 -> IOHashTable h k2 v2 -> m ()
forceType _ _ = return ()

------------------------------------------------------------------------------
dummyTable :: forall k v h . C.HashTable h => IOHashTable h k v
dummyTable = undefined

------------------------------------------------------------------------------
tests :: C.HashTable h => String -> FixedTableType h -> Test
tests prefix dummyArg = testGroup prefix $ map f ts
  where
    f (SomeTest ht) = ht prefix dummyArg

    ts = [ SomeTest testFromListToList
         , SomeTest testInsert
         , SomeTest testInsert2
         , SomeTest testNewAndInsert
         , SomeTest testGrowTable
         , SomeTest testDelete
         , SomeTest testNastyFullLookup
         , SomeTest testForwardSearch3
         , SomeTest testMutate
         , SomeTest testMutateGrow
         ]

------------------------------------------------------------------------------
testFromListToList :: HashTest
testFromListToList prefix dummyArg =
    testProperty (prefix ++ "/fromListToList") $
                 monadicIO $ do
                     rng <- initializeRNG
                     forAllM arbitrary $ prop rng

  where
    prop :: GenIO -> [(Int, Int)] -> PropertyM IO ()
    prop rng origL = do
        let l = V.toList $ shuffleVector rng $ V.fromList $ dedupe origL
        announceQ "fromListToList" l
        ht <- run $ fromList l
        l' <- run $ toList ht
        assertEq "fromList . toList == id" (sort l) (sort l')
        forceType dummyArg ht

------------------------------------------------------------------------------
testInsert :: HashTest
testInsert prefix dummyArg =
    testProperty (prefix ++ "/insert") $
                 monadicIO $ do
                     rng <- initializeRNG
                     forAllM arbitrary $ prop rng

  where
    prop :: GenIO -> ([(Int, Int)], (Int,Int)) -> PropertyM IO ()
    prop rng o@(origL, (k,v)) = do
        announceQ "insert" o
        let l = V.toList $ shuffleVector rng $ V.fromList $ remove k $ dedupe origL
        assert $ all (\t -> fst t /= k) l

        ht <- run $ fromList l
        nothing <- run $ lookup ht k
        assertEq ("lookup " ++ show k) Nothing nothing

        run $ insert ht k v
        r <- run $ lookup ht k
        assertEq ("lookup2 " ++ show k) (Just v) r

        forceType dummyArg ht

------------------------------------------------------------------------------
testInsert2 :: HashTest
testInsert2 prefix dummyArg =
    testProperty (prefix ++ "/insert2") $
                 monadicIO $ do
                     rng <- initializeRNG
                     forAllM arbitrary $ prop rng

  where
    prop :: GenIO -> ([(Int, Int)], (Int,Int,Int)) -> PropertyM IO ()
    prop rng o@(origL, (k,v,v2)) = do
        announceQ "insert2" o
        let l = V.toList $ shuffleVector rng $ V.fromList $ dedupe origL
        ht   <- run $ fromList l

        run $ insert ht k v
        r <- run $ lookup ht k
        assertEq ("lookup1 " ++ show k) (Just v) r

        run $ insert ht k v2
        r' <- run $ lookup ht k
        assertEq ("lookup2 " ++ show k) (Just v2) r'

        forceType dummyArg ht

------------------------------------------------------------------------------
testNewAndInsert :: HashTest
testNewAndInsert prefix dummyArg =
    testProperty (prefix ++ "/newAndInsert") $
                 monadicIO $ forAllM arbitrary prop

  where
    prop :: (Int,Int,Int) -> PropertyM IO ()
    prop o@(k,v,v2) = do
        announceQ "newAndInsert" o
        ht <- run new

        nothing <- run $ lookup ht k
        assertEq ("lookup " ++ show k) Nothing nothing

        run $ insert ht k v
        r <- run $ lookup ht k
        assertEq ("lookup2 " ++ show k) (Just v) r

        run $ insert ht k v2
        r' <- run $ lookup ht k
        assertEq ("lookup3 " ++ show k) (Just v2) r'

        ctRef <- run $ newIORef (0::Int)
        run $ mapM_ (const $ modifyIORef ctRef (+1)) ht

        ct <- run $ readIORef ctRef
        assertEq "count = 1" 1 ct

        ct' <- run $ foldM (\i _ -> return $! i+1) (0::Int) ht
        assertEq "count2 = 1" 1 ct'

        forceType dummyArg ht

------------------------------------------------------------------------------
testGrowTable :: HashTest
testGrowTable prefix dummyArg =
    testProperty (prefix ++ "/growTable") $
                 monadicIO $ forAllM generator prop

  where
    generator = choose (32,2048)

    go n = new >>= go' (0::Int)
      where
        go' !i !ht | i >= n = return ht
                   | otherwise = do
            insert ht i i
            go' (i+1) ht

    f (!m,!s) (!k,!v) = return $! (max m k, v `seq` s+1)

    prop :: Int -> PropertyM IO ()
    prop n = do
        announceQ "growTable" n
        ht <- run $ go n
        i <- liftM head $ run $ sample' $ choose (0,n-1)

        v <- run $ lookup ht i
        assertEq ("lookup " ++ show i) (Just i) v

        ct <- run $ foldM f (0::Int, 0::Int) ht
        assertEq "max + count" (n-1,n) ct
        forceType dummyArg ht

------------------------------------------------------------------------------
testDelete :: HashTest
testDelete prefix dummyArg =
    testProperty (prefix ++ "/delete") $
                 monadicIO $ forAllM generator prop

  where
    generator = choose (32,2048)

    go n = new >>= go' (0::Int)
      where
        go' !i !ht | i >= n = return ht
                   | otherwise = do
            insert ht i i

            case i of
              3  -> do
                       delete ht 2
                       delete ht 3
                       insert ht 2 2

              _  -> if i `mod` 2 == 0
                      then do
                        delete ht i
                        insert ht i i
                      else return ()

            go' (i+1) ht

    f (!m,!s) (!k,!v) = return $! (max m k, v `seq` s+1)

    prop :: Int -> PropertyM IO ()
    prop n = do
        announceQ "delete" n

        ht <- run $ go n

        i <- liftM head $ run $ sample' $ choose (4,n-1)
        v <- run $ lookup ht i
        assertEq ("lookup " ++ show i) (Just i) v

        v3 <- run $ lookup ht 3
        assertEq ("lookup 3") Nothing v3

        ct <- run $ foldM f (0::Int, 0::Int) ht
        assertEq "max + count" (n-1,n-1) ct
        forceType dummyArg ht

------------------------------------------------------------------------------
testMutate :: HashTest
testMutate prefix dummyArg = testProperty (prefix ++ "/mutate") $
                             monadicIO $ forAllM arbitrary prop
  where
    prop :: ([(Int, Int)],  [(Int, [Int])]) -> PropertyM IO ()
    prop o@(seedList, testList) = do
      announceQ "mutate" o
      ht <- run $ fromList seedList
      Monad.mapM_ (testOne ht) testList

    upd n v = (fmap (+ n) v <|> pure n, ())

    testOne ht (k, values) = do
        pre . not . null $ values
        run $ mutate ht k (const (Nothing, ()))
        out1 <- run $ lookup ht k
        assertEq ("mutate deletes " ++ show k) Nothing out1
        out2 <- run $ do
            Monad.mapM_ (mutate ht k . upd) values
            (Just v) <- lookup ht k
            return $! v
        let s = sum values
        assertEq "mutate inserts correctly folded list value" s out2
        forceType dummyArg ht

testMutateGrow :: HashTest
testMutateGrow prefix dummyArg = testCase (prefix ++ "/mutateGrow") go
  where
    go = do
        tbl <- new
        forceType tbl dummyArg
        timeout_ 3000000 $ do
            let inputs = [0..128 :: Int]
            Monad.mapM_ (mutIns tbl) inputs
            l <- sort <$> toList tbl
            let expected = map (\i -> (i, i)) inputs
            assertEqual "mutate-grow" expected l
    mutIns tbl i = mutate tbl i (const (Just i, ()))

------------------------------------------------------------------------------
data Action = Lookup Int
            | Insert Int
            | Delete Int
            deriving Show

timeout_ :: Int -> IO a -> IO ()
#ifdef PORTABLE
timeout_ t m = timeout t m >>= maybe (assertFailure "timeout")
                                     (const $ return ())
#else

foreign import ccall safe "suicide"
  c_suicide :: Ptr CInt -> CInt -> IO ()

-- Foreign thread can get blocked here, stalling progress. We'll make damned
-- sure we bomb out.
timeout_ t m = do
    ptr <- malloc
    poke ptr 1
    forkOS $ suicide ptr
    threadDelay 1000
    r <- timeout t m
    poke ptr 0
    maybe (assertFailure "timeout")
          (const $ return ())
          r
  where
    suicide ptr = do
        c_suicide ptr $ toEnum t
        free ptr
#endif

applyAction :: forall h . C.HashTable h =>
               IOHashTable h Int () -> Action -> IO ()
applyAction tbl (Lookup key) = lookup tbl key >> return ()
applyAction tbl (Insert key) = insert tbl key ()
applyAction tbl (Delete key) = delete tbl key

testForwardSearch3 :: HashTest
testForwardSearch3 prefix dummyArg = testCase (prefix ++ "/forwardSearch3") go
  where
    go = do
        tbl <- new
        forceType tbl dummyArg
        timeout_ 3000000 $
            foldM_ (\t k -> applyAction t k >> return t) tbl testData

    testData =
      [ Insert 65
      , Insert 66
      , Insert 67
      , Insert 74
      , Insert 75
      , Insert 76
      , Insert 77
      , Insert 79
      , Insert 80
      , Insert 81
      , Insert 82
      , Insert 83
      , Insert 84
      , Delete 81
      , Delete 82
      , Insert 85
      , Insert 86
      , Insert 87
      , Insert 88
      , Insert 89
      , Insert 90
      , Insert 78
      , Insert 93
      , Insert 94
      , Insert 95
      , Insert 96
      , Insert 97
      , Insert 92
      , Delete 93
      , Delete 94
      , Delete 95
      , Delete 96
      , Insert 99
      , Insert 100
      , Insert 101
      , Insert 102
      , Insert 103
      , Insert 104
      , Insert 98
      , Insert 91
      , Insert 108
      , Insert 109
      , Insert 110
      , Insert 111
      ]

testNastyFullLookup :: HashTest
testNastyFullLookup prefix dummyArg = testCase (prefix ++ "/nastyFullLookup") go
  where
    go = do
        tbl <- new
        forceType tbl dummyArg
        timeout_ 3000000 $
            foldM_ (\t k -> applyAction t k >> return t) tbl testData

    testData =
      [ Insert 28
      , Insert 27
      , Insert 30
      , Insert 31
      , Insert 32
      , Insert 33
      , Insert 34
      , Insert 29
      , Insert 36
      , Insert 37
      , Delete 34
      , Delete 29
      , Insert 38
      , Insert 39
      , Insert 40
      , Insert 35
      , Delete 39
      , Insert 42
      , Insert 43
      , Delete 40
      , Delete 35
      , Insert 44
      , Insert 45
      , Insert 41
      , Insert 48
      , Insert 47
      , Insert 50
      , Insert 51
      , Insert 52
      , Insert 49
      , Insert 54
      , Insert 53
      , Insert 56
      , Insert 55
      , Insert 58
      , Insert 57
      , Insert 60
      , Insert 59
      , Delete 60
      , Insert 62
      , Insert 61
      , Insert 63
      , Insert 46
      , Lookup 66
      ]

------------------------------------------------------------------------------
initializeRNG :: PropertyM IO GenIO
initializeRNG = run createSystemRandom

------------------------------------------------------------------------------
dedupe :: (Ord k, Ord v, Eq k) => [(k,v)] -> [(k,v)]
dedupe l = go0 $ sort l
  where
    go0 []     = []
    go0 (x:xs) = go id x xs

    go !dl !lastOne [] = (dl . (lastOne:)) []

    go !dl !lastOne@(!lx,_) ((x,v):xs) =
        if lx == x
          then go dl lastOne xs
          else go (dl . (lastOne:)) (x,v) xs

------------------------------------------------------------------------------
-- assumption: list is sorted.
remove :: (Ord k, Eq k) => k -> [(k,v)] -> [(k,v)]
remove m l = go id l
  where
    go !dl [] = dl []
    go !dl ll@((k,v):xs) =
        case compare k m of
             LT -> go (dl . ((k,v):)) xs
             EQ -> go dl xs
             GT -> dl ll

------------------------------------------------------------------------------
shuffleVector :: GenIO -> Vector k -> Vector k
shuffleVector rng v = if V.null v then v else V.modify go v
  where
    !n = V.length v

    go mv = f (n-1)
      where
        -- note: inclusive
        pickOne b = unsafeIOToST $ uniformR (0,b) rng

        swap = MV.unsafeSwap mv

        f 0  = return ()
        f !k = do
            idx <- pickOne k
            swap k idx
            f (k-1)


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 com.facebook.presto.decoder.dummy;

import com.facebook.presto.decoder.DecoderColumnHandle;
import com.facebook.presto.decoder.FieldValueProvider;
import com.facebook.presto.decoder.RowDecoder;
import com.google.common.collect.ImmutableMap;

import java.util.Map;
import java.util.Optional;

/**
 * The row decoder for the 'dummy' format. For an unstructured row format (bag
 * of bytes), a specific decoder for a topic must exist. To start developing
 * such a decoder, it is beneficial to be able to configure an arbitrary topic
 * to be available through presto without any decoding at all (not even line
 * parsing) and examine the internal rows that are exposed by Presto. By adding
 * a table name to the catalog configuration file and not having and specific
 * topic description JSON file (or by omitting the 'dataFormat' field in the
 * table description file), this decoder should be selected by the appropriate
 * connector.
 */
public class DummyRowDecoder
        implements RowDecoder
{
    public static final String NAME = "dummy";
    private static final Optional<Map<DecoderColumnHandle, FieldValueProvider>> ALL_NULLS = Optional.of(ImmutableMap.of());

    @Override
    public Optional<Map<DecoderColumnHandle, FieldValueProvider>> decodeRow(byte[] data,
            Map<String, String> dataMap)
    {
        return ALL_NULLS;
    }
}


text:
<?php

namespace refiche\FileBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use refiche\UserBundle\Entity\User;
use refiche\UserBundle\Entity\Classe;
use refiche\FileBundle\Entity\Matiere;
use refiche\FileBundle\Form\MatiereType;

class MatieresController extends Controller
{
    public function listeAction()
    {
        // Récupération des matières en passant par la classe
        $user = $this->getUser();
        $classe = $user->getClasse();

        if (!empty($classe)) {
            $matieres = $classe->getMatieres();
        }

        return $this->render('reficheFileBundle:Matieres:listeMatieres.html.twig', array('matieres' => $matieres) );
    }

    // METHODE TEMPORAIRE CF reficheUserBundle:nouveauMembre
    public function ajouterMatiereAction()
    {
        if ( $this->get('security.context')->isGranted('ROLE_SUPER_ADMIN') )
        {
            $matiere = new Matiere;
            $form = $this->createForm(new MatiereType, $matiere);

            $request = $this->get('request');
            if ($request->getMethod() == 'POST') {
                $form->bind($request);

                if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($matiere);
                $em->flush();

                return $this->redirect($this->generateUrl('refiche_app_bureau'));
                }
            }
        }

        return $this->render('reficheUserBundle:NouveauMembre:ajouter.html.twig', array( 'form' => $form->createView(), 'titre' => 'Nouvelle matière' ));
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
  withRouter,
  routerPropTypes,
} from 'react-router-dom';

import Waypoint from 'react-waypoint';

import WatchesList from '../components/WatchesList';
import LoadingSpinner from '../components/LoadingSpinner';

import { loadWatches } from '../actions/watches';

const mapStateToProps = state => ({
  loading: state.watchesLoading,
  watches: state.watches,
});

@withRouter
@connect(mapStateToProps)
export default class Watches extends Component {
  static propTypes = {
    ...routerPropTypes,
    loading: PropTypes.bool.isRequired,
    watches: PropTypes.arrayOf(PropTypes.object).isRequired,
    dispatch: PropTypes.func.isRequired,
  };

  componentWillMount() {
    this.props.dispatch(loadWatches());
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.match.params.type !== nextProps.match.params.type) {
      this.props.dispatch(loadWatches());
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.loading !== nextProps.loading) {
      return true;
    }

    if (this.props.watches.length !== nextProps.watches.length) {
      return true;
    }

    for (let i = 0; i < this.props.watches.length; i += 1) {
      if (this.props.watches[i].keyId !== nextProps.watches[i].keyId) {
        return true;
      }
    }

    return false;
  }

  loadMoreWatches = () => {
    const limit = 2 * this.props.watches.length;
    this.props.dispatch(loadWatches({ query: { limit } }));
  }

  render() {
    const { watches, loading } = this.props;
    return (
      <div>
        <WatchesList
          watches={watches}
        />
        <LoadingSpinner loading={loading} />
        <Waypoint
          topOffset="70%"
          bottomOffset="-25%"
          onEnter={this.loadMoreWatches}
        />
      </div>
    );
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/kid14/Documents/Move-Alarm/Move-and-Move-Alarm/MAMTv1/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-vi/values-vi.xml -->
    <eat-comment/>
    <string msgid="4600421777120114993" name="abc_action_bar_home_description">"Điều hướng về trang chủ"</string>
    <string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string>
    <string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string>
    <string msgid="1594238315039666878" name="abc_action_bar_up_description">"Điều hướng lên trên"</string>
    <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Thêm tùy chọn"</string>
    <string msgid="4076576682505996667" name="abc_action_mode_done">"Xong"</string>
    <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Xem tất cả"</string>
    <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Chọn một ứng dụng"</string>
    <string msgid="7723749260725869598" name="abc_search_hint">"Tìm kiếm…"</string>
    <string msgid="3691816814315814921" name="abc_searchview_description_clear">"Xóa truy vấn"</string>
    <string msgid="2550479030709304392" name="abc_searchview_description_query">"Tìm kiếm truy vấn"</string>
    <string msgid="8264924765203268293" name="abc_searchview_description_search">"Tìm kiếm"</string>
    <string msgid="8928215447528550784" name="abc_searchview_description_submit">"Gửi truy vấn"</string>
    <string msgid="893419373245838918" name="abc_searchview_description_voice">"Tìm kiếm bằng giọng nói"</string>
    <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Chia sẻ với"</string>
    <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Chia sẻ với %s"</string>
    <string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Thu gọn"</string>
    <!-- From: file:/C:/Users/kid14/Documents/Move-Alarm/Move-and-Move-Alarm/MAMTv1/app/build/intermediates/exploded-aar/com.facebook.android/facebook-android-sdk/4.6.0/res/values-vi/values-vi.xml -->
    <eat-comment/>
    <string name="com_facebook_image_download_unknown_error">Lỗi bất ngờ khi tải ảnh xuống.</string>
    <string name="com_facebook_internet_permission_error_message">Đăng nhập WebView yêu cầu INTERNET cho phép</string>
    <string name="com_facebook_internet_permission_error_title">Lỗi AndroidManifest</string>
    <string name="com_facebook_like_button_liked">Đã thích</string>
    <string name="com_facebook_like_button_not_liked">Thích</string>
    <string name="com_facebook_loading">Đang tải...</string>
    <string name="com_facebook_loginview_cancel_action">Hủy</string>
    <string name="com_facebook_loginview_log_in_button">Đăng nhập</string>
    <string name="com_facebook_loginview_log_in_button_long">Đăng nhập bằng Facebook</string>
    <string name="com_facebook_loginview_log_out_action">Đăng xuất</string>
    <string name="com_facebook_loginview_log_out_button">Đăng xuất</string>
    <string name="com_facebook_loginview_logged_in_as">Đã đăng nhập với tư cách là: %1$s</string>
    <string name="com_facebook_loginview_logged_in_using_facebook">Đã đăng nhập bằng Facebook</string>
    <string name="com_facebook_send_button_text">Gửi</string>
    <string name="com_facebook_share_button_text">Chia sẻ</string>
    <string name="com_facebook_tooltip_default">Mới! Bạn đang có quyền kiểm soát - hãy chọn thông tin bạn muốn chia sẻ với các ứng dụng.</string>
    <string name="messenger_send_button_text">Gửi</string>
    <!-- From: file:/C:/Users/kid14/Documents/Move-Alarm/Move-and-Move-Alarm/MAMTv1/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-vi/values-vi.xml -->
    <eat-comment/>
    <string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string>
</resources>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.fop.fo.flow.table.GridUnit (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.fo.flow.table.GridUnit

Packages that use GridUnit

org.apache.fop.fo.flow.table

Uses of GridUnit in org.apache.fop.fo.flow.table

Subclasses of GridUnit in org.apache.fop.fo.flow.table

 class
EmptyGridUnit

          GridUnit subclass for empty grid units.

 class
PrimaryGridUnit

          This class represents a primary grid unit of a spanned cell.

Methods in org.apache.fop.fo.flow.table that return GridUnit

 GridUnit
EffRow.getGridUnit(int column)

          Returns the grid unit at a given position.

 GridUnit
EffRow.safelyGetGridUnit(int column)

          Returns the grid unit at a given position.

Methods in org.apache.fop.fo.flow.table with parameters of type GridUnit

 void
PrimaryGridUnit.addRow(GridUnit[] row)

          Add a row.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
package models

case class SearchPreview( size: Long, eventList: Seq[Event] )


text:
package com.artemis.managers;

import com.artemis.*;
import com.artemis.annotations.Wire;
import com.artemis.component.*;
import com.artemis.components.SerializationTag;
import com.artemis.io.JsonArtemisSerializer;
import com.artemis.io.SaveFileFormat;
import com.artemis.utils.IntBag;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.util.Arrays;

import static com.artemis.utils.SerializationUtil.save;
import static org.junit.Assert.*;

@Wire(failOnNull = false)
public class JsonWorldSerializationManagerTest {
	private WorldSerializationManager wsm;
	private AspectSubscriptionManager subscriptions;
	private TagManager tags;
	private GroupManager groups;
	private World world;
	private EntitySubscription allEntities;

	private ComponentMapper<SerializationTag> serializationTagMapper;
	private JsonArtemisSerializer backend;

	@Before
	public void setup() {
		setupWorld();

		EntityEdit ee = world.createEntity().edit();
		ee.create(ComponentX.class).text = "hello";
		ee.create(ComponentY.class).text = "whatever";
		ee.create(ReusedComponent.class);

		EntityEdit ee2 = world.createEntity().edit();
		ee2.create(ComponentX.class).text = "hello 2";
		ee2.create(NameComponent.class).name = "do i work?";
		ee2.create(ComponentY.class).text = "whatever 2";
		ee2.create(ReusedComponent.class);

		EntityEdit ee3 = world.createEntity().edit();
		ee3.create(ComponentX.class).text = "hello 3";
		ee3.create(ComponentY.class).text = "whatever 3";
		ee3.create(ReusedComponent.class);
		ee3.create(SerializationTag.class).tag = "whatever";

		world.process();
		assertEquals(3, allEntities.getEntities().size());
	}

	private void setupWorld() {
		world = new World(new WorldConfiguration()
				.setSystem(GroupManager.class)
				.setSystem(TagManager.class)
				.setSystem(WorldSerializationManager.class));

		world.inject(this);
		backend = new JsonArtemisSerializer(world);
		backend.prettyPrint(true);
		wsm.setSerializer(backend);

		allEntities = subscriptions.get(Aspect.all());
	}

	@Test /* https://github.com/junkdog/artemis-odb/issues/452 */
	public void save_compact_json() throws Exception {
		backend.prettyPrint(false);
		save(allEntities, wsm);
	}

	@Test
	public void serializer_save_load_std_format_new_world() throws Exception {
		String json = save(allEntities, wsm);

		deleteAll();
		assertEquals(0, allEntities.getEntities().size());

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));

		setupWorld();

		allEntities = subscriptions.get(Aspect.all());

		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);

		world.process();
		assertEquals(3, allEntities.getEntities().size());

		String json2 = save(allEntities, wsm);

		deleteAll();
		assertEquals(0, allEntities.getEntities().size());
	}

	@Test
	public void serializer_save_to_file_and_load_std_format_new_world() throws Exception {
		String json = save(allEntities, wsm);
		PrintWriter writer = new PrintWriter("save_temp.json", "UTF-8");
		writer.append(json);
		writer.close();

		deleteAll();
		assertEquals(0, allEntities.getEntities().size());

		File file = new File("save_temp.json");
		InputStream is = new FileInputStream(file);
		setupWorld();

		allEntities = subscriptions.get(Aspect.all());

		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		file.delete();

		world.process();
		assertEquals(3, allEntities.getEntities().size());

		String json2 = save(allEntities, wsm);

		deleteAll();
		assertEquals(0, allEntities.getEntities().size());

	}

	@Test
	public void serializer_save_load_with_keys() throws Exception {
		setKeys();

		String json = save(allEntities, wsm);

		deleteAll();

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());
		assertEquals(2, load.keys().size());
		assertKeys(load);
	}

	@Test
	public void serializer_save_load_with_tags() throws Exception {
		setTags();

		String json = save(allEntities, wsm);

		deleteAll();

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());
		assertTags();
	}

	@Test
	public void serializer_save_load_with_groups() throws Exception {
		setGroups();

		String json = save(allEntities, wsm);

		deleteAll();

		assertEquals(0, groups.getEntities("group1").size());
		assertEquals(0, groups.getEntities("group2").size());

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());
		assertGroups();
	}

	@Test
	public void serializer_save_load_with_groups_and_tags() throws Exception {
		setTags();
		setGroups();

		String json = save(allEntities, wsm);

		deleteAll();

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());

		assertTags();
		assertGroups();
	}

	@Test
	public void serializer_save_load_with_groups_and_tags_and_keys() throws Exception {
		setKeys();
		setTags();
		setGroups();

		String json = save(allEntities, wsm);

		deleteAll();

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());

		assertTags();
		assertGroups();
		assertKeys(load);
	}

	@Test
	public void save_load_entity_references() throws Exception {
		setTags();

		EntityEdit ee1 = world.createEntity().edit();
		EntityHolder holder = ee1.create(EntityHolder.class);
		holder.entity = tags.getEntity("tag1");
		holder.entityId = tags.getEntity("tag3").getId();

		tags.register("entity-holder", ee1.getEntity());
		int entityHolderId = ee1.getEntity().getId();

		world.process();

		String json = save(allEntities, wsm);

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		wsm.load(is, SaveFileFormat.class);

		world.process();

		Entity entityHolder = tags.getEntity("entity-holder");
		EntityHolder holder2 = entityHolder.getComponent(EntityHolder.class);
		assertNotEquals(entityHolder.getId(), entityHolderId);
		assertNotNull(holder2.entity);
		assertNotEquals(holder.entity, holder2.entity);
		assertNotEquals(holder.entityId, holder2.entityId);
	}

	@Test
	public void save_load_entity_reference_with_null() throws Exception {
		EntityEdit ee1 = world.createEntity().edit();
		EntityHolder holder = ee1.create(EntityHolder.class);
		holder.entity = null;
		holder.entityId = -1;

		EntityEdit ee2 = world.createEntity().edit();
		EntityHolder holder2 = ee2.create(EntityHolder.class);
		holder2.entity = ee2.getEntity();
		holder2.entityId = ee2.getEntityId();

		tags.register("ee1", ee1.getEntity());
		int entityHolderId = ee1.getEntity().getId();

		tags.register("ee2", ee2.getEntity());
		int entityHolderId2 = ee2.getEntity().getId();

		world.process();

		String json = save(allEntities, wsm);

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		wsm.load(is, SaveFileFormat.class);

		world.process();

		Entity entityHolder1 = tags.getEntity("ee1");
		EntityHolder holder1b = entityHolder1.getComponent(EntityHolder.class);
		assertNotEquals(entityHolder1.getId(), entityHolderId);
		assertNull(holder1b.entity);
		assertEquals(-1, holder1b.entityId);

		Entity entityHolder2 = tags.getEntity("ee2");
		EntityHolder holder2b = entityHolder2.getComponent(EntityHolder.class);
		assertNotEquals(entityHolder1.getId(), entityHolderId2);
		assertNotNull(holder2b.entity);
		assertNotEquals(holder.entity, holder2b.entity);
		assertNotEquals(holder.entityId, holder2b.entityId);
	}

	@Test
	public void save_load_bag_entity_references() throws Exception {
		setTags();

		EntityEdit ee1 = world.createEntity().edit();
		EntityBagHolder holder = ee1.create(EntityBagHolder.class);
		holder.entities.add(tags.getEntity("tag1"));
		holder.entities.add(tags.getEntity("tag3"));

		tags.register("entity-holder", ee1.getEntity());
		int entityHolderId = ee1.getEntity().getId();

		world.process();

		String json = save(allEntities, wsm);

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		wsm.load(is, SaveFileFormat.class);

		world.process();

		Entity entityHolder = tags.getEntity("entity-holder");
		EntityBagHolder holder2 = entityHolder.getComponent(EntityBagHolder.class);
		assertNotEquals(entityHolder.getId(), entityHolderId);
		assertNotNull(holder2.entities);
		assertEquals(2, holder2.entities.size());
		assertEquals(tags.getEntity("tag1"), holder2.entities.get(0));
		assertEquals(tags.getEntity("tag3"), holder2.entities.get(1));
	}

	@Test
	public void save_excludes_default_value_components() throws Exception {
		setTags();

		EntityEdit ee1 = world.createEntity().edit();
		ee1.create(ComponentX.class);
		ee1.create(ComponentY.class);
		ee1.create(ReusedComponent.class);
		ee1.create(SerializationTag.class).tag = "one";
		EntityEdit ee2 = world.createEntity().edit();
		ee2.create(ComponentX.class);
		ee2.create(ComponentY.class).text = "only me";
		ee2.create(ReusedComponent.class);
		ee2.create(SerializationTag.class).tag = "two";

		world.process();

		String json = save(allEntities, wsm);

		deleteAll();

		ByteArrayInputStream is = new ByteArrayInputStream(
				json.getBytes("UTF-8"));
		SaveFileFormat l = wsm.load(is, SaveFileFormat.class);

		world.process();

		assertEquals(5, allEntities.getEntities().size());
		assertEquals(tags.getEntity("tag3").getCompositionId(), l.get("one").getCompositionId());
		assertEquals(l.get("one").getCompositionId(), l.get("two").getCompositionId());
	}

	@Test
	public void save_load_intbag_entity_references() throws Exception {
		setTags();

		EntityEdit ee1 = world.createEntity().edit();
		EntityIntBagHolder holder = ee1.create(EntityIntBagHolder.class);
		holder.entities.add(tags.getEntity("tag1").getId());
		holder.entities.add(tags.getEntity("tag3").getId());

		tags.register("entity-holder", ee1.getEntity());
		int entityHolderId = ee1.getEntity().getId();

		world.process();

		String json = save(allEntities, wsm);

		ByteArrayInputStream is = new ByteArrayInputStream(
			json.getBytes("UTF-8"));
		wsm.load(is, SaveFileFormat.class);

		world.process();

		Entity entityHolder = tags.getEntity("entity-holder");
		EntityIntBagHolder holder2 = entityHolder.getComponent(EntityIntBagHolder.class);
		assertNotEquals(entityHolder.getId(), entityHolderId);
		assertNotNull(holder2.entities);
		assertEquals(2, holder2.entities.size());
		assertEquals(tags.getEntity("tag1"), world.getEntity(holder2.entities.get(0)));
		assertEquals(tags.getEntity("tag3"), world.getEntity(holder2.entities.get(1)));
	}

	@Test
	public void loaded_entities_id_order_matches_json_layout() throws Exception {
		String json = save(allEntities, wsm);

		world.delete(2);
		world.process();

		deleteAll();

		assertEquals(0, allEntities.getEntities().size());

		ByteArrayInputStream is = new ByteArrayInputStream(
			json.getBytes("UTF-8"));

		SaveFileFormat load = wsm.load(is, SaveFileFormat.class);
		world.process();

		assertEquals(3, allEntities.getEntities().size());

		// this would be out of order in 1.2.1 and earlier, due
		// to entityId 2 being deleted before 0 and 1.
		IntBag sorted = new IntBag();
		sorted.addAll(load.entities);
		Arrays.sort(sorted.getData(), 0, sorted.size());
		assertEquals(sorted, load.entities);
	}

	@Test
	public void implicitly_saved_entities_includes_archetypes() {
		setupWorld();

		EntityEdit ee = world.createEntity().edit();
		ee.create(Size.class);
		int id1 = ee.getEntityId();

		EntityEdit ee2 = world.createEntity().edit();
		ee2.create(EntityHolder.class).entityId = id1;
		int id2 = ee2.getEntityId();

		world.process();

		IntBag toSave = new IntBag();
		toSave.add(id2);
		SaveFileFormat save = new SaveFileFormat(toSave);
		ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
		wsm.save(baos, save);

		// only saving 2nd entity, need to make sure the archetype for
		// id1 is pulled in too
		assertEquals(2, save.archetypes.compositionIdMapper.size());
	}

	private void setTags() {
		IntBag entities = allEntities.getEntities();
		tags.register("tag1", world.getEntity(entities.get(0)));
		tags.register("tag3", world.getEntity(entities.get(2)));
	}

	private void setKeys() {
		IntBag entities = allEntities.getEntities();
		serializationTagMapper.create(entities.get(0)).tag = "key1";
		serializationTagMapper.create(entities.get(2)).tag = "key3";
	}

	private void assertTags() {
		IntBag entities = allEntities.getEntities();
		assertNotNull(entities.toString(), tags.getEntity("tag1"));
		assertNotNull(entities.toString(), tags.getEntity("tag3"));
	}

	private void assertKeys(SaveFileFormat loaded) {
		IntBag entities = allEntities.getEntities();
		assertNotNull(entities.toString(), loaded.get("key1"));
		assertNotNull(entities.toString(), loaded.get("key3"));
	}

	private void assertGroups() {
		assertEquals(2, groups.getEntities("group1").size());
		assertEquals(1, groups.getEntities("group2").size());
	}

	private void setGroups() {
		IntBag entities = allEntities.getEntities();
		groups.add(world.getEntity(entities.get(0)), "group1");
		groups.add(world.getEntity(entities.get(0)), "group2");
		groups.add(world.getEntity(entities.get(2)), "group1");
	}

	private int deleteAll() {
		IntBag entities = allEntities.getEntities();
		int size = entities.size();
		for (int i = 0; size > i; i++) {
			world.delete(entities.get(i));
		}

		world.process();
		return size;
	}
}


text:
import Ember from 'ember';
const { getOwner } = Ember;
import ActiveArrayProxy from 'ui/utils/active-array-proxy';
import C from 'ui/utils/constants';

export default Ember.Service.extend({
  access: Ember.inject.service(),
  'tab-session': Ember.inject.service('tab-session'),
  prefs: Ember.inject.service(),
  k8sSvc: Ember.inject.service('k8s'),
  swarmSvc: Ember.inject.service('swarm'),
  mesosSvc: Ember.inject.service('mesos'),

  current: null,
  all: null,
  active: function() {
    return ActiveArrayProxy.create({
      sourceContent: this.get('all')||[]
    });
  }.property('all.[]'),

  getAll: function() {
    var opt = {
      url: 'projects',  // This is called in authenticated/route before schemas are loaded
      forceReload: true,
    };

    if ( !this.get('access.enabled') )
    {
      opt.filter = {all: 'true'};
    }

    return this.get('userStore').find('project', null, opt);
  },

  refreshAll: function() {
    this.getAll().then((all) => {
      this.set('all', all);
      this.selectDefault();
    });
  },

  selectDefault: function(desired) {
    var self = this;
    var tabSession = this.get('tab-session');

    // The one specifically asked for
    return this._activeProjectFromId(desired).then(select)
    .catch(() => {
      // Try the project ID in the session
      return this._activeProjectFromId(tabSession.get(C.TABSESSION.PROJECT)).then(select)
      .catch(() => {
        // Then the default project ID from the prefs
        return this._activeProjectFromId(this.get('prefs').get(C.PREFS.PROJECT_DEFAULT)).then(select)
        .catch(() => {
          // Then the first active project you're a member of
          var project = this.get('active.firstObject');
          if ( project )
          {
            return select(project, true);
          }
          else if ( this.get('access.admin') )
          {
            // Then if you're an admin the first active of any kind
            return this.getAll().then((all) => {
              var firstActive = all.filterBy('state','active')[0];
              if ( firstActive )
              {
                return select(firstActive, true);
              }
              else
              {
                return fail();
              }
            }).catch(() => {
              return fail();
            });
          }
          else
          {
            return fail();
          }
        });
      });
    });

    function select(project, overwriteDefault) {
      if ( project )
      {
        tabSession.set(C.TABSESSION.PROJECT, project.get('id'));

        // If there is no default project, set it
        var def = self.get('prefs').get(C.PREFS.PROJECT_DEFAULT);
        if ( !def || overwriteDefault === true )
        {
          self.get('prefs').set(C.PREFS.PROJECT_DEFAULT, project.get('id'));
        }

        return self.setCurrent(project);
      }
      else
      {
        tabSession.set(C.TABSESSION.PROJECT, undefined);
        return self.setCurrent(null);
      }
    }

    function fail() {
      // Then cry
      select(null);
      return Ember.RSVP.reject();
    }
  },

  setCurrent: function(project) {
    this.set('current', project);
    if ( project ) {
      this.set('store.baseUrl', `${this.get('app.apiEndpoint')}/projects/${project.get('id')}`);
    } else {
      this.set('store.baseUrl', this.get('app.apiEndpoint'));
    }
    return Ember.RSVP.resolve(project);
  },

  _activeProjectFromId: function(projectId) {
    return new Ember.RSVP.Promise((resolve, reject) => {
      if ( !projectId )
      {
        reject();
        return;
      }

      this.get('userStore').find('project', projectId, {url: 'projects/'+encodeURIComponent(projectId)}).then((project) => {
        if ( project.get('state') === 'active' )
        {
          resolve(project);
        }
        else
        {
          reject();
        }
      }).catch(() => {
        reject();
      });
    });
  },

  orchestrationState: null,
  updateOrchestrationState() {
    let hash = {
      hasKubernetes: false,
      hasSwarm: false,
      hasMesos: false,
      kubernetesReady: false,
      swarmReady: false,
      mesosReady: false,
    };

    let promises = [];

    if ( this.get('current') )
    {
      if ( this.get('current.kubernetes') )
      {
        hash.hasKubernetes = true;
        promises.push(this.get('k8sSvc').isReady().then((ready) => {
          hash.kubernetesReady = ready;
        }));
      }

      if ( this.get('current.swarm') )
      {
        hash.hasSwarm = true;
        promises.push(this.get('swarmSvc').isReady().then((ready) => {
          hash.swarmReady = ready;
        }));
      }

      if ( this.get('current.mesos') )
      {
        hash.hasMesos = true;
        promises.push(this.get('mesosSvc').isReady().then((ready) => {
          hash.mesosReady = ready;
        }));
      }
    }

    return Ember.RSVP.all(promises).then(() => {
      this.set('orchestrationState', hash);
      return Ember.RSVP.resolve(hash);
    });
  },

  orchestrationStateShouldChange: function() {
    Ember.run.once(this, 'updateOrchestrationState', true);
  }.observes('current.{id,kubernetes,swarm,mesos}'),

  isReady: function() {
    var state = this.get('orchestrationState');

    if ( !state )
    {
      return false;
    }

    return (
      (!state.hasKubernetes || state.kubernetesReady) &&
      (!state.hasSwarm || state.swarmReady) &&
      (!state.hasMesos || state.mesosReady)
    );
  }.property('orchestrationState'), // The state object is always completely replaced, so this is ok

  checkForWaiting(hosts,machines) {
    let router = getOwner(this).get('router');

    let hasHosts = false;
    if ( this.get('current.mesos') )
    {
      hasHosts = (hosts && hosts.filterBy('state','active').get('length') >= 2);
    }
    else
    {
      hasHosts = (hosts && hosts.get('length') > 0) || (machines && machines.get('length') > 0);
    }

    if ( !hasHosts )
    {
      router.transitionTo('authenticated.project.waiting', this.get('current.id'));
    }

    return this.updateOrchestrationState().then(() => {
      if ( !this.get('isReady') )
      {
        router.transitionTo('authenticated.project.waiting', this.get('current.id'));
      }
    });
  }
});


text:
{% extends "v9/layoutv9.html" %}

{% set title = "Which licences do you want to be able to view?" %}

{% block page_title %}
    {{title}} - GOV.UK
{% endblock %}

{% block content %}

      BETA
      This is an BETA prototype, details may be missing whilst we build the service. Your feedback will help us improve this service.

  Back

{% block wendy_next_page %}
<form action="/v11/online_licence/wendy_reg/3_select_licences" method="post" class="form" id="password_reset" data-parsley-validate data-parsley-errors-messages-disabled>
{% endblock %}
{% block new_wendy_next_page %}
<form action="/v11/online_licence/new_wendy_reg/select_licences" method="post" class="form" id="password_reset" data-parsley-validate data-parsley-errors-messages-disabled>
{% endblock %}
{% block john_next_page %}
<form action="/v11/online_licence/john_reg/3_select_licences" method="post" class="form" id="password_reset" data-parsley-validate data-parsley-errors-messages-disabled>
{% endblock %}
{% if data.incorrectLicenceNo == "1" %}

            Some information doesn't match our records

Check your licence number(s)

{% endif %}
{% if data.nodata == "1" %}

            Some information doesn't match our records

Check your licence number(s)

{% endif %}

    We need more information

Enter your licence number(s)

              Which licences do you want to be able to view?

{% block john_licence_no_label %}
              <fieldset>
                Your licence number

                  If you have more than one licence, choose any of your numbers.

                Enter your licence number.
              </fieldset>
  {% endblock %}

  {% block wendy_licence_no_label %}
                <fieldset>
                  Enter your licence number(s)

You can separate your licence numbers using spaces, commas, or by entering them on different lines.

                  Enter your licence number(s).
                </fieldset>
    {% endblock %}

          {% block wendy_licence_no_input %}

          <textarea class="form-control form-control-3-4" name="licence_no" id="licence_no" rows="5" value="{{data.licence_no}}" required ></textarea>

          {% endblock %}

          {% block john_licence_no_input %}

          <input type="licence_no" class="form-control" name="licence_no" id="licence_no" value="{{data.licence_no}}" required />

        {% endblock %}

        {% block john_postcode %}

              <fieldset>
                Your postcode

                  This is the postcode you registered as the licence holder.

                Enter your postcode.
              </fieldset>

          <input   type="text" class="form-control" name="postcode" id="postcode"  value="{{data.postcode}}" required/>

{% endblock %}
          <input onclick="$('#incorrectLicenceNo').hide()" type="submit" value="Continue" class="button" role="button"/>

      </form>

                Don't have this information?

Please email water_abstractiondigital@environment-agency.gov.uk.

Our team will reply to you within 2 working days.

{% endblock %}


text:
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix

# load data
###############################

from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets("data/MNIST/", one_hot=True)

print("Size of:")
print("- Training-set:\t\t{}".format(len(data.train.labels)))
print("- Test-set:\t\t{}".format(len(data.test.labels)))
print("- Validation-set:\t{}".format(len(data.validation.labels)))

data.test.cls = np.array([label.argmax() for label in data.test.labels])

# Data dimensions
###############################

# We know that MNIST images are 28 pixels in each dimension.
img_size = 28

# Images are stored in one-dimensional arrays of this length.
img_size_flat = img_size * img_size

# Tuple with height and width of images used to reshape arrays.
img_shape = (img_size, img_size)

# Number of classes, one class for each of 10 digits.
num_classes = 10

# Hyperparameters
###############################
# step size of Gradient Descent Optimizer
learning_rate = \
	0.05
	#0.5

batch_size = \
	300
	#100

# build model graph
###############################
x = tf.placeholder(tf.float32, [None, img_size_flat])
y_true = tf.placeholder(tf.float32, [None, num_classes])
y_true_cls = tf.placeholder(tf.int64, [None])

weights = tf.Variable(tf.zeros([img_size_flat, num_classes]))
biases = tf.Variable(tf.zeros([num_classes]))
logits = tf.matmul(x, weights) + biases

y_pred = tf.nn.softmax(logits)
y_pred_cls = tf.argmax(y_pred, dimension=1)

cross_entropy = \
	tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_true)
#tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,labels=y_true)
cost = tf.reduce_mean(cross_entropy)

optimizer = \
	tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
	#tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
	#tf.train.AdagradOptimizer(learning_rate=learning_rate).minimize(cost)

correct_prediction = tf.equal(y_pred_cls, y_true_cls)

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Create TensorFlow session
###############################
session = tf.Session()
session.run(tf.global_variables_initializer())

feed_dict_test = {x: data.test.images,
                  y_true: data.test.labels,
                  y_true_cls: data.test.cls}

def optimize(num_iterations):
    for i in range(num_iterations):
        # Get a batch of training examples.
        # x_batch now holds a batch of images and
        # y_true_batch are the true labels for those images.
        x_batch, y_true_batch = data.train.next_batch(batch_size)

        # Put the batch into a dict with the proper names
        # for placeholder variables in the TensorFlow graph.
        # Note that the placeholder for y_true_cls is not set
        # because it is not used during training.
        feed_dict_train = {x: x_batch,
                           y_true: y_true_batch}

        # Run the optimizer using this batch of training data.
        # TensorFlow assigns the variables in feed_dict_train
        # to the placeholder variables and then runs the optimizer.
        session.run(optimizer, feed_dict=feed_dict_train)

def print_accuracy():
    # Use TensorFlow to compute the accuracy.
    acc = session.run(accuracy, feed_dict=feed_dict_test)

    # Print the accuracy.
    print("Accuracy on test-set: {0:.1%}".format(acc))

def print_confusion_matrix():
    # Get the true classifications for the test-set.
    cls_true = data.test.cls

    # Get the predicted classifications for the test-set.
    cls_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)

    # Get the confusion matrix using sklearn.
    cm = confusion_matrix(y_true=cls_true,
                          y_pred=cls_pred)

    # Print the confusion matrix as text.
    print(cm)

# run tests
###############################

# Performance after 1 optimization iteration
optimize(num_iterations=1)
print_accuracy()
#print_confusion_matrix()

# Performance after 10 optimization iteration
optimize(num_iterations=9)
print_accuracy()
print_confusion_matrix()

# Performance after 1000 optimization iterations
optimize(num_iterations=990)
print_accuracy()
print_confusion_matrix()

#
session.close()


text:
/*
 * $Id$
 */

#if !defined(XERCESC_INCLUDE_GUARD_BINFILEINPUTSTREAM_HPP)
#define XERCESC_INCLUDE_GUARD_BINFILEINPUTSTREAM_HPP

#include <xercesc/util/BinInputStream.hpp>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLUTIL_EXPORT BinFileInputStream : public BinInputStream
{
public :
    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    BinFileInputStream
    (
        const   XMLCh* const    fileName
        , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
    );

    BinFileInputStream
    (
        const   char* const     fileName
        , MemoryManager* const  manager = XMLPlatformUtils::fgMemoryManager
    );

    BinFileInputStream
    (
        const   FileHandle      toUse
        , MemoryManager* const  manager = XMLPlatformUtils::fgMemoryManager
    );

    virtual ~BinFileInputStream();

    // -----------------------------------------------------------------------
    //  Getter methods
    // -----------------------------------------------------------------------
    bool getIsOpen() const;
    XMLFilePos getSize() const;
    void reset();

    // -----------------------------------------------------------------------
    //  Implementation of the input stream interface
    // -----------------------------------------------------------------------
    virtual XMLFilePos curPos() const;

    virtual XMLSize_t readBytes
    (
                XMLByte* const      toFill
        , const XMLSize_t           maxToRead
    );

    virtual const XMLCh* getContentType() const;

private :
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    BinFileInputStream(const BinFileInputStream&);
    BinFileInputStream& operator=(const BinFileInputStream&);

    // -----------------------------------------------------------------------
    //  Private data members
    //
    //  fSource
    //      The source file that we represent. The FileHandle type is defined
    //      per platform.
    // -----------------------------------------------------------------------
    FileHandle              fSource;
    MemoryManager* const    fMemoryManager;
};

// ---------------------------------------------------------------------------
//  BinFileInputStream: Getter methods
// ---------------------------------------------------------------------------
inline bool BinFileInputStream::getIsOpen() const
{
    return (fSource != (FileHandle) XERCES_Invalid_File_Handle);
}

XERCES_CPP_NAMESPACE_END

#endif


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.jdbi.v3.core;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

import org.jdbi.v3.core.junit5.H2DatabaseExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import static org.assertj.core.api.Assertions.assertThat;

public class TestJsr310 {

    @RegisterExtension
    public H2DatabaseExtension h2Extension = H2DatabaseExtension.instance().withInitializer(h -> h.execute("create table stuff (ts timestamp, d date)"));

    // Don't use nanoseconds - they'll get truncated off
    Clock fixed = Clock.fixed(Instant.ofEpochSecond(123456789), ZoneOffset.UTC);

    @Test
    public void instant() {
        Handle h = h2Extension.getSharedHandle();

        Instant i = Instant.now(fixed);
        h.execute("insert into stuff(ts) values (?)", i);
        assertThat(h.createQuery("select ts from stuff").mapTo(Instant.class).one()).isEqualTo(i);
    }

    @Test
    public void localDate() {
        Handle h = h2Extension.getSharedHandle();

        LocalDate d = LocalDate.now(fixed);
        h.execute("insert into stuff(d) values (?)", d);
        assertThat(h.createQuery("select d from stuff").mapTo(LocalDate.class).one()).isEqualTo(d);
    }

    @Test
    public void localDateTime() {
        Handle h = h2Extension.getSharedHandle();

        LocalDateTime d = LocalDateTime.now(fixed);
        h.execute("insert into stuff(ts) values (?)", d);
        assertThat(h.createQuery("select ts from stuff").mapTo(LocalDateTime.class).one()).isEqualTo(d);
    }

    @Test
    public void offsetDateTime() {
        Handle h = h2Extension.getSharedHandle();

        OffsetDateTime dt = OffsetDateTime.now(fixed);
        h.execute("insert into stuff(ts) values (?)", dt);
        assertThat(h.createQuery("select ts from stuff").mapTo(OffsetDateTime.class).one()).isEqualTo(dt);
    }

    @Test
    public void offsetDateTimeLosesOffset() {
        Handle h = h2Extension.getSharedHandle();

        OffsetDateTime dt = OffsetDateTime.now(fixed).withOffsetSameInstant(ZoneOffset.ofHours(-7));
        h.execute("insert into stuff(ts) values (?)", dt);
        assertThat(h.createQuery("select ts from stuff").mapTo(OffsetDateTime.class).one().isEqual(dt)).isTrue();
    }

    @Test
    public void zonedDateTime() {
        Handle h = h2Extension.getSharedHandle();

        ZonedDateTime dt = ZonedDateTime.now(fixed);
        h.execute("insert into stuff(ts) values (?)", dt);
        assertThat(h.createQuery("select ts from stuff").mapTo(ZonedDateTime.class).one()).isEqualTo(dt);
    }

    @Test
    public void zonedDateTimeLosesZone() {
        Handle h = h2Extension.getSharedHandle();

        ZonedDateTime dt = ZonedDateTime.now(fixed).withZoneSameInstant(ZoneId.of("America/Denver"));
        h.execute("insert into stuff(ts) values (?)", dt);
        assertThat(h.createQuery("select ts from stuff").mapTo(ZonedDateTime.class).one().isEqual(dt)).isTrue();
    }

    @Test
    public void localTime() {
        Handle h = h2Extension.getSharedHandle();

        h.execute("create table schedule (start_time time, end_time time)");
        LocalTime start = LocalTime.of(8, 30, 0);
        LocalTime end = LocalTime.of(10, 30, 0);
        h.execute("insert into schedule (start_time, end_time) values (?,?)", start, end);
        assertThat(h.createQuery("select start_time from schedule").mapTo(LocalTime.class).one()).isEqualTo(start);
        assertThat(h.createQuery("select end_time from schedule").mapTo(LocalTime.class).one()).isEqualTo(end);
    }
}


text:
namespace g{namespace Fuse{namespace Triggers{struct WhileVisible;}}}
namespace g{namespace Fuse{struct Node;}}
namespace g{namespace Uno{struct EventArgs;}}

namespace g{
namespace Fuse{
namespace Triggers{

// public sealed class WhileVisible :1710
// {
::g::Fuse::Triggers::Trigger_type* WhileVisible_typeof();
void WhileVisible__ctor_3_fn(WhileVisible* __this);
void WhileVisible__New1_fn(WhileVisible** __retval);
void WhileVisible__OnIsVisibleChanged_fn(WhileVisible* __this, uObject* sender, ::g::Uno::EventArgs* args);
void WhileVisible__OnRooted_fn(WhileVisible* __this, ::g::Fuse::Node* parentNode);
void WhileVisible__OnUnrooted_fn(WhileVisible* __this, ::g::Fuse::Node* parentNode);

struct WhileVisible : ::g::Fuse::Triggers::WhileTrigger
{
    void ctor_3();
    void OnIsVisibleChanged(uObject* sender, ::g::Uno::EventArgs* args);
    static WhileVisible* New1();
};
// }

}}} // ::g::Fuse::Triggers


text:
<?php

namespace Bit3\GitPhp\Command;

/**
 * Show command builder.
 *
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
 */
class ShowCommandBuilder implements CommandBuilderInterface
{
    use CommandBuilderTrait;

    /**
     * {@inheritDoc}
     */
    protected function initializeProcessBuilder()
    {
        $this->arguments[] = 'show';
    }

    /**
     * Add the  option to the command line.
     *
     * @param null|string $format The format.
     *
     * @return ShowCommandBuilder
     */
    public function pretty($format = null)
    {
        $this->arguments[] = '--pretty' . ($format ? '=' . $format : '');
        return $this;
    }

    /**
     * Add the format option to the command line.
     *
     * @param null|string $format The format.
     *
     * @return ShowCommandBuilder
     */
    public function format($format)
    {
        $this->arguments[] = '--format=' . $format;
        return $this;
    }

    /**
     * Add the abbrev-commit option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function abbrevCommit()
    {
        $this->arguments[] = '--abbrev-commit';
        return $this;
    }

    /**
     * Add the no-abbrev-commit option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function noAbbrevCommit()
    {
        $this->arguments[] = '--no-abbrev-commit';
        return $this;
    }

    /**
     * Add the oneline option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function oneline()
    {
        $this->arguments[] = '--oneline';
        return $this;
    }

    /**
     * Add the encoding option to the command line.
     *
     * @param string $encoding The encoding.
     *
     * @return ShowCommandBuilder
     */
    public function encoding($encoding)
    {
        $this->arguments[] = '--encoding=' . $encoding;
        return $this;
    }

    /**
     * Add the notes option to the command line.
     *
     * @param null|string $ref The ref name.
     *
     * @return ShowCommandBuilder
     */
    public function notes($ref = null)
    {
        $this->arguments[] = '--notes' . ($ref ? '=' . $ref : '');
        return $this;
    }

    /**
     * Add the no-notes option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function noNotes()
    {
        $this->arguments[] = '--no-notes';
        return $this;
    }

    /**
     * Add the show-notes option to the command line.
     *
     * @param null|string $ref The ref name.
     *
     * @return ShowCommandBuilder
     */
    public function showNotes($ref = null)
    {
        $this->arguments[] = '--show-notes' . ($ref ? '=' . $ref : '');
        return $this;
    }

    /**
     * Add the standard-notes option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function standardNotes()
    {
        $this->arguments[] = '--standard-notes';
        return $this;
    }

    /**
     * Add the no-standard-notes option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function noStandardNotes()
    {
        $this->arguments[] = '--no-standard-notes';
        return $this;
    }

    /**
     * Add the show-signature option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function showSignature()
    {
        $this->arguments[] = '--show-signature';
        return $this;
    }

    /**
     * Add the no-patch option to the command line.
     *
     * @return ShowCommandBuilder
     */
    public function noPatch()
    {
        $this->arguments[] = '--no-patch';
        return $this;
    }

    /**
     * Build the command and execute it.
     *
     * @param string $object Name of the object to show.
     *
     * @return string
     *
     * @SuppressWarnings(PHPMD.ShortVariableName)
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.CamelCaseParameterName)
     */
    public function execute($object)
    {
        $this->arguments[] = $object;
        return $this->run();
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">

	<title>04-component</title>

vue 2.0

		<compontent :is="com"></compontent>

<button @click="next">next component</button>


text:
var async = require('async');
var serviceValidator = require('../../../lib/service-validator');

exports = module.exports = (function(){

  return {

    /**
     * Utility to populate a list of services using the provided storage
     * @param services
     * @param storage
     * @param callback
     */

    populate: function(services, storage, callback){

      if (!services || !services.length) {
        return callback('services not provided');
      }

      function addService(service, cb) {
        var errors = serviceValidator.validate(service);
        if (errors.length === 0){
          storage.addService(service, cb);
        } else {
          cb(errors);
        }
      }

      storage.flush_database(function() {
        async.eachSeries(services, addService, function (err) {
          if (err) {
            return callback(err);
          }
          callback();
        });
      });
    }
  };

})();


text:
If you want to make pkgs install and patches, you can have some troubles, since each features need to be idempotent:
you need to cleanup, and do not assume that some pkgs are present at beginn of your feature, and assume that you remove the pkg

Basically,  we use 2 REPOS for test packages:

1) contains lower version of pkgs:  Devel_Galaxy_BuildRepo  **disabled by default**
2) contains patches with higher version of pkgs: Test channel **enabled, and created by core-feature.**

### typical WORKFLOW for patches test

0) enable the BuildRepo
1) downgrade pkg(install) /Remove pkg
3) schedule taskomatic run, and wait for finish. ( to retrieve patches avaibles)
4) make test with patch (install it etc)
5) cleanup: remove pkg/patches and disable the buildRepo

### Examples:

Take a look on this feature: features/trad_check_patches_install.feature``


text:
package com.opengamma.analytics.financial.equity.variance.pricing;

import java.util.Arrays;

import com.opengamma.util.ArgumentChecker;

/**
 * Dividend payment (per share) at time $\tau_i$ of the form $\alpha_i + \beta_iS_{\tau_{i^-}}$  where $S_{\tau_{i^-}}$ is the stock price immediately before the
 * dividend payment.
 */
public class AffineDividends {

  private final double[] _tau;
  private final double[] _alpha;
  private final double[] _beta;
  private final int _n;

  public static AffineDividends noDividends() {
    final double[] z = new double[0];
    return new AffineDividends(z, z, z);
  }

  public AffineDividends(final double[] tau, final double[] alpha, final double[] beta) {
    ArgumentChecker.notNull(tau, "null tau");
    ArgumentChecker.notNull(alpha, "null alpha");
    ArgumentChecker.notNull(beta, "null beta");
    _n = tau.length;
    ArgumentChecker.isTrue(_n == alpha.length, "alpha wrong length");
    ArgumentChecker.isTrue(_n == beta.length, "beta wrong length");

    if (_n > 0) {
      ArgumentChecker.isTrue(tau[0] >= 0.0, "first dividend at negative time. Please remove from list");
      ArgumentChecker.isTrue(alpha[0] >= 0.0, "first cash dividend is negative.");
      ArgumentChecker.isTrue(beta[0] >= 0.0 && beta[0] < 1.0, "Proportional dividend must be between 0.0 (inclusive) and 1.0 (exclusive). Value is {}", beta[0]);
      for (int i = 1; i < _n; i++) {
        ArgumentChecker.isTrue(tau[i] > tau[i - 1], "Dividends not increasing. {}th dividend is {}, and {}th is {}", i, tau[i], i - 1, tau[i - 1]);
        ArgumentChecker.isTrue(alpha[i] >= 0.0, "Cash dividend is negative. alpha[{}] = {}", i, alpha[i]);
        ArgumentChecker.isTrue(beta[i] >= 0.0 && beta[i] < 1.0, "Proportional dividend must be between 0.0 (inclusive) and 1.0 (exclusive). beta[{}] = {}", i, beta[i]);
      }
    }
    _tau = tau;
    _alpha = alpha;
    _beta = beta;
  }

  /**
   * Gets the dividend times
   * @return the tau
   */
  public double[] getTau() {
    final double[] tau = Arrays.copyOf(_tau, _n);
    return tau;
  }

  /**
   * Gets the cash dividends.
   * @return the alpha
   */
  public double[] getAlpha() {
    final double[] alpha = Arrays.copyOf(_alpha, _n);
    return alpha;
  }

  /**
   * Gets the proportional dividends.
   * @return the beta
   */
  public double[] getBeta() {
    final double[] beta = Arrays.copyOf(_beta, _n);
    return beta;
  }

  /**
   * Gets the dividend times
   * @param index the index of the dividend
   * @return the tau
   */
  public double getTau(final int index) {
    return _tau[index];
  }

  /**
   * Gets the cash dividends.
   * @param index the index of the dividend
   * @return the alpha
   */
  public double getAlpha(final int index) {
    return _alpha[index];
  }

  /**
   * Gets the proportional dividends.
   * @param index the index of the dividend
   * @return the beta
   */
  public double getBeta(final int index) {
    return _beta[index];
  }

  /**
   * Gets the number of dividends.
   * @return the number of dividends
   */
  public int getNumberOfDividends() {
    return _n;
  }

  /**
   * Change one of the dividend times
   * @param value The new value of the dividend time, tau
   * @param index The index of the new dividend time
   * @return A new AffineDividends with the changed tau
   */
  public AffineDividends withTau(final double value, final int index) {
    ArgumentChecker.isTrue(value >= 0.0, "negative tau");
    ArgumentChecker.isTrue(index >= 0 && index < _n, "index out of range");
    final double[] tau = Arrays.copyOf(_tau, _n);
    tau[index] = value;
    return new AffineDividends(tau, _alpha, _beta);
  }

  /**
   * Change one of the alpha values
   * @param value The new value of alpha
   * @param index The index of the new alpha
   * @return A new AffineDividends with the changed alpha
   */
  public AffineDividends withAlpha(final double value, final int index) {
    ArgumentChecker.isTrue(value >= 0.0, "negative alpha");
    ArgumentChecker.isTrue(index >= 0 && index < _n, "index out of range");
    final double[] alpha = Arrays.copyOf(_alpha, _n);
    alpha[index] = value;
    return new AffineDividends(_tau, alpha, _beta);
  }

  /**
   * Change one of the beta values
   * @param value The new value of beta
   * @param index The index of the new beta
   * @return A new AffineDividends with the changed beta
   */
  public AffineDividends withBeta(final double value, final int index) {
    ArgumentChecker.isTrue(value >= 0.0, "negative beta");
    ArgumentChecker.isTrue(index >= 0 && index < _n, "index out of range");
    final double[] beta = Arrays.copyOf(_beta, _n);
    beta[index] = value;
    return new AffineDividends(_tau, _alpha, beta);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(_alpha);
    result = prime * result + Arrays.hashCode(_beta);
    result = prime * result + Arrays.hashCode(_tau);
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof AffineDividends)) {
      return false;
    }
    final AffineDividends other = (AffineDividends) obj;
    if (!Arrays.equals(_alpha, other._alpha)) {
      return false;
    }
    if (!Arrays.equals(_beta, other._beta)) {
      return false;
    }
    if (!Arrays.equals(_tau, other._tau)) {
      return false;
    }
    return true;
  }

}


text:
package alluxio.client.file.options;

import alluxio.Constants;
import alluxio.annotation.PublicApi;
import alluxio.security.authorization.Permission;
import alluxio.thrift.CompleteUfsFileTOptions;

import com.google.common.base.Objects;

import java.io.IOException;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * Options for completing a UFS file. Currently we do not allow users to set arbitrary owner and
 * group options. The owner and group will be set to the user login.
 */
@PublicApi
@NotThreadSafe
public final class CompleteUfsFileOptions {
  /** The ufs file permission, including owner, group and mode. */
  private Permission mPermission;

  /**
   * Creates a default {@link CompleteUfsFileOptions} with owner, group from login module and
   * default file mode.
   *
   * @return the default {@link CompleteUfsFileOptions}
   * @throws IOException if failed to set owner from login module
   */
  public static CompleteUfsFileOptions defaults() throws IOException {
    return new CompleteUfsFileOptions();
  }

  private CompleteUfsFileOptions() throws IOException {
    mPermission = Permission.defaults();
    // Set owner and group from user login module, apply default file UMask.
    mPermission.setOwnerFromLoginModule().applyFileUMask();
    // TODO(chaomin): set permission based on the alluxio file. Not needed for now since the
    // file is always created with default permission.
  }

  /**
   * @return the permission of the UFS file
   */
  public Permission getPermission() {
    return mPermission;
  }

  /**
   * @param permission the permission to be set
   * @return the updated options object
   */
  public CompleteUfsFileOptions setPermission(Permission permission) {
    mPermission = permission;
    return this;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof CompleteUfsFileOptions)) {
      return false;
    }
    CompleteUfsFileOptions that = (CompleteUfsFileOptions) o;
    return Objects.equal(mPermission, that.mPermission);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(mPermission);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("permission", mPermission)
        .toString();
  }

  /**
   * @return Thrift representation of the options
   */
  public CompleteUfsFileTOptions toThrift() {
    CompleteUfsFileTOptions options = new CompleteUfsFileTOptions();
    if (!mPermission.getOwner().isEmpty()) {
      options.setOwner(mPermission.getOwner());
    }
    if (!mPermission.getGroup().isEmpty()) {
      options.setGroup(mPermission.getGroup());
    }
    short mode = mPermission.getMode().toShort();
    if (mode != Constants.INVALID_MODE) {
      options.setMode(mode);
    }
    return options;
  }
}


text:
'use strict';

angular.module('rippleDemonstrator')
  .controller('AllergiesDetailCtrl', function ($scope, $stateParams, SearchInput, $modal, $state, $location, Helper, usSpinnerService, PatientService, Allergy) {

    SearchInput.update();
    PatientService.get($stateParams.patientId).then(function (patient) {
      $scope.patient = patient;
    });

    Allergy.get($stateParams.patientId, $stateParams.allergyIndex).then(function (result) {
      $scope.allergy = result.data;
      usSpinnerService.stop('allergiesDetail-spinner');
    });

    $scope.edit = function () {
      var modalInstance = $modal.open({
        templateUrl: 'views/allergies/allergies-modal.html',
        size: 'lg',
        controller: 'AllergiesModalCtrl',
        resolve: {
          modal: function () {
            return {
              title: 'Edit Allergy'
            };
          },
          allergy: function () {
            return angular.copy($scope.allergy);
          },
          patient: function () {
            return $scope.patient;
          }
        }
      });

      modalInstance.result.then(function (allergy) {
        var toUpdate = {
          sourceId: allergy.sourceId,
          cause: allergy.cause,
          causeCode: allergy.causeCode,
          causeTerminology: allergy.causeTerminology,
          reaction: allergy.reaction,
          source: 'openehr'
        };

        Allergy.update($scope.patient.id, toUpdate).then(function () {
          setTimeout(function () {
            $state.go('allergies-detail', {
              patientId: $scope.patient.id,
              allergyIndex: Helper.updateId(allergy.sourceId),
              page: $scope.currentPage,
              reportType: $stateParams.reportType,
              searchString: $stateParams.searchString,
              queryType: $stateParams.queryType
            });
          }, 2000);
        });
      });
    };

  });


text:
define([

  'performer/transformers/wrap',
  'performer/transformers/sibling'

],
function(Wrap, Sibling) {

  return {
    tag: [Sibling.label,Wrap.li],
    set: [Wrap.ol,Sibling.legend,Wrap.fieldset]
  };

});


text:
<?php

namespace Sabre\VObject\ITip;

class Message
{
    /**
     * The object's UID.
     *
     * @var string
     */
    public $uid;

    /**
     * The component type, such as VEVENT.
     *
     * @var string
     */
    public $component;

    /**
     * Contains the ITip method, which is something like REQUEST, REPLY or
     * CANCEL.
     *
     * @var string
     */
    public $method;

    /**
     * The current sequence number for the event.
     *
     * @var int
     */
    public $sequence;

    /**
     * The senders' email address.
     *
     * Note that this does not imply that this has to be used in a From: field
     * if the message is sent by email. It may also be populated in Reply-To:
     * or not at all.
     *
     * @var string
     */
    public $sender;

    /**
     * The name of the sender. This is often populated from a CN parameter from
     * either the ORGANIZER or ATTENDEE, depending on the message.
     *
     * @var string|null
     */
    public $senderName;

    /**
     * The recipient's email address.
     *
     * @var string
     */
    public $recipient;

    /**
     * The name of the recipient. This is usually populated with the CN
     * parameter from the ATTENDEE or ORGANIZER property, if it's available.
     *
     * @var string|null
     */
    public $recipientName;

    /**
     * After the message has been delivered, this should contain a string such
     * as : 1.1;Sent or 1.2;Delivered.
     *
     * In case of a failure, this will hold the error status code.
     *
     * See:
     * http://tools.ietf.org/html/rfc6638#section-7.3
     *
     * @var string
     */
    public $scheduleStatus;

    /**
     * The iCalendar / iTip body.
     *
     * @var \Sabre\VObject\Component\VCalendar
     */
    public $message;

    /**
     * This will be set to true, if the iTip broker considers the change
     * 'significant'.
     *
     * In practice, this means that we'll only mark it true, if for instance
     * DTSTART changed. This allows systems to only send iTip messages when
     * significant changes happened. This is especially useful for iMip, as
     * normally a ton of messages may be generated for normal calendar use.
     *
     * To see the list of properties that are considered 'significant', check
     * out Sabre\VObject\ITip\Broker::$significantChangeProperties.
     *
     * @var bool
     */
    public $significantChange = true;

    /**
     * Returns the schedule status as a string.
     *
     * For example:
     * 1.2
     *
     * @return mixed bool|string
     */
    public function getScheduleStatus()
    {
        if (!$this->scheduleStatus) {
            return false;
        } else {
            list($scheduleStatus) = explode(';', $this->scheduleStatus);

            return $scheduleStatus;
        }
    }
}


text:
package io.school.entity;

import java.util.List;

/**
 * 表数据
 *
 * @author school
 * @email
 * @date 2016年12月20日 上午12:02:55
 */
public class TableEntity {
	//表的名称
	private String tableName;
	//表的备注
	private String comments;
	//表的主键
	private ColumnEntity pk;
	//表的列名(不包含主键)
	private List<ColumnEntity> columns;

	//类名(第一个字母大写),如:sys_user => SysUser
	private String className;
	//类名(第一个字母小写),如:sys_user => sysUser
	private String classname;

	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	public String getComments() {
		return comments;
	}
	public void setComments(String comments) {
		this.comments = comments;
	}
	public ColumnEntity getPk() {
		return pk;
	}
	public void setPk(ColumnEntity pk) {
		this.pk = pk;
	}
	public List<ColumnEntity> getColumns() {
		return columns;
	}
	public void setColumns(List<ColumnEntity> columns) {
		this.columns = columns;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getClassname() {
		return classname;
	}
	public void setClassname(String classname) {
		this.classname = classname;
	}
}


text:
package me.lemire.microbenchmarks.algorithms;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class Shuffle {

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

    public static void shuffle(int arr[], ThreadLocalRandom rnd) {
        int size = arr.length;
        // Shuffle array
        for (int i = size; i > 1; i--)
            swap(arr, i - 1, rnd.nextInt(i));
    }

    public static void shuffle(int arr[], MersenneTwisterFast rnd) {
        int size = arr.length;

        // Shuffle array
        for (int i = size; i > 1; i--)
            swap(arr, i - 1, rnd.nextInt(i));
    }

    static int fancy_ranged_random_mult_lazy(int  range,  MersenneTwisterFast rnd) {
        long random32bit, multiresult;
        long leftover;
        if((range & (range - 1)) == 0)
            return rnd.nextInt() & (range - 1);
        final long mask = 0xFFFFFFFFL;
        random32bit = rnd.nextInt()  & mask;
        multiresult = random32bit * range;
        leftover = multiresult & mask;
        if(leftover < range) {
          final long threshold = 0xFFFFFFFF % range;
          while (leftover <= threshold) {
              random32bit = rnd.nextInt() & mask;
              multiresult = random32bit * range;
              leftover =  multiresult & mask;
          }
        }
        return (int) (multiresult >>> 32); // [0, range)
    }

    static int ranged_random_mult_lazy(int  range,  MersenneTwisterFast rnd) {
        long random32bit, multiresult;
        long leftover;
        final long mask = 0xFFFFFFFFL;
        random32bit = rnd.nextInt()  & mask;
        multiresult = random32bit * range;
        leftover = multiresult & mask;
        if(leftover < range) {
          final long threshold = (-range) % range;
          while (leftover <= threshold) {
              random32bit = rnd.nextInt() & mask;
              multiresult = random32bit * range;
              leftover =  multiresult & mask;
          }
        }
        return (int) (multiresult >>> 32); // [0, range)
    }

    public static void shuffle_fastF(int arr[], MersenneTwisterFast rnd) {
        int size = arr.length;

        // Shuffle array
        for (int i = size; i > 1; i--)
            swap(arr, i - 1, ranged_random_mult_lazy(i,rnd));
    }
    static int fancy_ranged_random_mult_lazy(int  range,  ThreadLocalRandom rnd) {
        long random32bit, multiresult;
        long leftover;
        if((range & (range - 1)) == 0)
            return rnd.nextInt() & (range - 1);
        final long mask = 0xFFFFFFFFL;
        random32bit = rnd.nextInt() & mask;
        multiresult = random32bit * range;
        leftover = multiresult & mask;
        if(leftover < range) {
          final long threshold = 0xFFFFFFFF % range;
          while (leftover <= threshold) {
              random32bit = rnd.nextInt()  & mask;
              multiresult = random32bit * range;
              leftover =  multiresult & mask;
          }
        }
        return (int) (multiresult >>> 32); // [0, range)
    }

    static int ranged_random_mult_lazy(int  range,  ThreadLocalRandom rnd) {
        long random32bit, multiresult;
        long leftover;
        final long mask = 0xFFFFFFFFL;
        random32bit = rnd.nextInt() & mask;
        multiresult = random32bit * range;
        leftover = multiresult & mask;
        if(leftover < range) {
          final long threshold = (-range) % range;
          while (leftover <= threshold) {
              random32bit = rnd.nextInt()  & mask;
              multiresult = random32bit * range;
              leftover =  multiresult & mask;
          }
        }
        return (int) (multiresult >>> 32); // [0, range)
    }

    public static void shuffle_fastF(int arr[], ThreadLocalRandom rnd) {
        int size = arr.length;

        // Shuffle array
        for (int i = size; i > 1; i--)
            swap(arr, i - 1, ranged_random_mult_lazy(i,rnd));
    }

    @State(Scope.Benchmark)
    public static class BenchmarkState {
        int N = 1777216;
        int[] array = new int[N];

        public BenchmarkState() {

            for (int k = 0; k < N; ++k)
                array[k] = k;
        }

    }
    static MersenneTwisterFast rr = new MersenneTwisterFast();
    static ThreadLocalRandom r = ThreadLocalRandom.current();

    @Benchmark
    public void basicshuffle(BenchmarkState s) {
        shuffle(s.array, r);
    }
    @Benchmark
    public void basicshuffle_MT(BenchmarkState s) {
        shuffle(s.array, rr);
    }

    @Benchmark
    public void fastFshuffle(BenchmarkState s) {
        shuffle_fastF(s.array, r);
    }

    @Benchmark
    public void fastFshuffle_MT(BenchmarkState s) {
        shuffle_fastF(s.array, rr);
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
        .include(Shuffle.class.getSimpleName()).warmupIterations(2)
        .measurementIterations(3).forks(1).build();

        new Runner(opt).run();
    }

}


text:
<!DOCTYPE html>

	<title> scheduler: parser-created defer script after document load</title>

FAILED (This TC requires JavaScript enabled)


text:
Rails.application.routes.draw do
    resources :remarks,             :only => [:create]
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">

  <link href="assets/images/favicon.ico" rel="shortcut icon" type="image/x-icon">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      This page requires JavaScript. Please enable it in your browser.


text:
export function refreshOrLogout() {
  $.ajax(
    { url: Routes.refresh_session_main_index_path(),
      method: "POST"
    }
  )
}


text:
package de.beikern.quilltests.evidences

import akka.Done
import akka.stream.scaladsl.Sink
import de.beikern.quilltests.contexts.{AkkaContext, CassandraContext, QuillCtx}
import de.beikern.quilltests.daos.Dao.{Bar, Foo}
import de.beikern.quilltests.typeclasses.SinkLike

import scala.concurrent.Future

trait SinkEvidences { self: AkkaContext with CassandraContext =>

  val errorLog: PartialFunction[Throwable, Unit] = PartialFunction[Throwable, Unit](
      ex => println(s"There was an error persisting elements. Stacktrace: ${ex.getMessage}")
  )
  implicit object FooSinkLike extends SinkLike[Foo] {
    override def getSink(
        implicit quillCtx: QuillCtx
    ): Sink[Foo, Future[Done]] = {
      import quillCtx._
      Sink.foreach[Foo](elem => {
        quillCtx.run(mappedFoo.insert(lift(elem))).onFailure(errorLog)
      })
    }
  }
  implicit object BarSinkLike extends SinkLike[Bar] {
    override def getSink(
        implicit quillCtx: QuillCtx
    ): Sink[Bar, Future[Done]] = {
      import quillCtx._
      Sink.foreach[Bar](elem => {
        run(mappedBar.insert(lift(elem))).onFailure(errorLog)
      })
    }
  }
}


text:
import React from 'react';
import { get } from 'lodash';

import withData from './HasCases.relay';

export default withData(
  p =>
    get(p, 'viewer.explore.cases.hits.total', 0) ? (
      <div>{p.children}</div>
    ) : null,
);


text:
/*! \addtogroup PIO
 * @{
 *
 * \brief Pin Input/Output
 *
 */

#ifndef APPLIB_PIO_H_
#define APPLIB_PIO_H_

#include <dev/pio.h>
#include "periph.h"

#ifdef __cplusplus
extern "C" {
#endif

/*! \brief Open \a port */
int pio_open(port_t port);

/*! \brief Close \a port */
int pio_close(port_t port);
/*! \brief Get the port attributes */
int pio_getattr(port_t port, pio_attr_t * attr);
/*! \brief Set the port attributes */
int pio_setattr(port_t port, const pio_attr_t * attr);
/*! \brief Set the port action */
int pio_setaction(port_t port, const pio_action_t * action);
/*! \brief Set the mask for \a port */
int pio_setmask(port_t port, pio_sample_t mask);
/*! \brief Clear the mask for \a port */
int pio_clrmask(port_t port, pio_sample_t mask);
/*! \brief Get the value of \a port */
pio_sample_t pio_get(port_t port);
/*! \brief Set the value of \a port */
int pio_set(port_t port, pio_sample_t value);

#ifdef __cplusplus
}
#endif

#endif /* APPLIB_PIO_H_ */

/*! @} */