text:
<?php

/**
 * Payment transaction model
 * Tracks transaction history
 *
 * @method Mage_Paypal_Model_Resource_Payment_Transaction _getResource()
 * @method Mage_Paypal_Model_Resource_Payment_Transaction getResource()
 * @method string getTxnId()
 * @method string getCreatedAt()
 * @method Mage_Paypal_Model_Payment_Transaction setCreatedAt(string $value)
 *
 * @category    Mage
 * @package     Mage_Paypal
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Paypal_Model_Payment_Transaction extends Mage_Core_Model_Abstract
{
    /**
     * Whether to throw exceptions on different operations
     *
     * @var bool
     */
    protected $_isFailsafe = false;

    /**
     * Event object prefix
     *
     * @see Mage_Core_Model_Absctract::$_eventPrefix
     * @var string
     */
    protected $_eventPrefix = 'paypal_payment_transaction';

    /**
     * Event object prefix
     *
     * @see Mage_Core_Model_Absctract::$_eventObject
     * @var string
     */
    protected $_eventObject = 'paypal_payment_transaction';

    /**
     * Order website id
     *
     * @var int
     */
    protected $_orderWebsiteId = null;

    /**
     * Initialize resource model
     */
    protected function _construct()
    {
        $this->_init('paypal/payment_transaction');
        return parent::_construct();
    }

    /**
     * Transaction ID setter
     * @param string $txnId
     * @return Mage_Paypal_Model_Payment_Transaction
     */
    public function setTxnId($txnId)
    {
        $this->_verifyTxnId($txnId);
        return $this->setData('txn_id', $txnId);
    }

    /**
     * Check object before loading by by specified transaction ID
     * @param $txnId
     * @return Mage_Paypal_Model_Payment_Transaction
     */
    protected function _beforeLoadByTxnId($txnId)
    {
        Mage::dispatchEvent(
            $this->_eventPrefix . '_load_by_txn_id_before',
            $this->_getEventData() + array('txn_id' => $txnId)
        );
        return $this;
    }

    /**
     * Load self by specified transaction ID. Requires the valid payment object to be set
     * @param string $txnId
     * @return Mage_Paypal_Model_Payment_Transaction
     */
    public function loadByTxnId($txnId)
    {
        $this->_beforeLoadByTxnId($txnId);
        $this->getResource()->loadObjectByTxnId(
            $this, $txnId
        );
        $this->_afterLoadByTxnId();
        return $this;
    }

    /**
     * Check object after loading by by specified transaction ID
     * @param $txnId
     * @return Mage_Paypal_Model_Payment_Transaction
     */
    protected function _afterLoadByTxnId()
    {
        Mage::dispatchEvent($this->_eventPrefix . '_load_by_txn_id_after', $this->_getEventData());
        return $this;
    }

    /**
     * Additional information setter
     * Updates data inside the 'additional_information' array
     * Doesn't allow to set arrays
     *
     * @param string $key
     * @param mixed $value
     * @return Mage_Paypal_Model_Order_Payment_Transaction
     * @throws Mage_Core_Exception
     */
    public function setAdditionalInformation($key, $value)
    {
        if (is_object($value)) {
            Mage::throwException(Mage::helper('paypal')->__('Payment transactions disallow storing objects.'));
        }
        $info = $this->_getData('additional_information');
        if (!$info) {
            $info = array();
        }
        $info[$key] = $value;
        return $this->setData('additional_information', $info);
    }

    /**
     * Getter for entire additional_information value or one of its element by key
     * @param string $key
     * @return array|null|mixed
     */
    public function getAdditionalInformation($key = null)
    {
        $info = $this->_getData('additional_information');
        if (!$info) {
            $info = array();
        }
        if ($key) {
            return (isset($info[$key]) ? $info[$key] : null);
        }
        return $info;
    }

    /**
     * Unsetter for entire additional_information value or one of its element by key
     * @param string $key
     * @return Mage_Paypal_Model_Payment_Transaction
     */
    public function unsAdditionalInformation($key = null)
    {
        if ($key) {
            $info = $this->_getData('additional_information');
            if (is_array($info)) {
                unset($info[$key]);
            }
        } else {
            $info = array();
        }
        return $this->setData('additional_information', $info);
    }

    /**
     * Setter/Getter whether transaction is supposed to prevent exceptions on saving
     *
     * @param bool $failsafe
     */
    public function isFailsafe($setFailsafe = null)
    {
        if (null === $setFailsafe) {
            return $this->_isFailsafe;
        }
        $this->_isFailsafe = (bool)$setFailsafe;
        return $this;
    }

    /**
     * Verify data required for saving
     * @return Mage_Paypal_Model_Payment_Transaction
     * @throws Mage_Core_Exception
     */
    protected function _beforeSave()
    {
        if (!$this->getId()) {
            $this->setCreatedAt(Mage::getModel('core/date')->gmtDate());
        }
        return parent::_beforeSave();
    }

    /**
     * Check whether specified transaction ID is valid
     * @param string $txnId
     * @throws Mage_Core_Exception
     */
    protected function _verifyTxnId($txnId)
    {
        if (null !== $txnId && 0 == strlen($txnId)) {
            Mage::throwException(Mage::helper('paypal')->__('Transaction ID must not be empty.'));
        }
    }

    /**
     * Make sure this object is a valid transaction
     * TODO for more restriction we can check for data consistency
     * @throws Mage_Core_Exception
     */
    protected function _verifyThisTransactionExists()
    {
        if (!$this->getId()) {
            Mage::throwException(Mage::helper('paypal')->__('This operation requires an existing transaction object.'));
        }
    }
}


text:
'use strict';

require('es6-promise').polyfill();
require('isomorphic-fetch');
const json2csv = require('json2csv');
const fs       = require('fs');

const Podcast = require('./podcast');

const LOCALE = 'jp';
const EDUCATION_GENRE = 1304;

Podcast.getTopPodcasts(LOCALE, EDUCATION_GENRE).then((topPodcasts) => {
    console.log('Retrieved podcasts.'); // eslint-disable-line no-console
    Podcast.setReviewsOnPodcasts(topPodcasts, LOCALE).then(() => {
        const csv = json2csv({
            data: topPodcasts.reduce(
                (all, currentPodcast, index) => all.concat(currentPodcast.getReviewCsvData(index + 1)),
                []
            ),
            fields: Podcast.getReviewCsvFields(),
        });

        fs.writeFile('output/reviews.csv', csv, function(err) {
            if (err) throw err;
            console.log('file saved'); // eslint-disable-line no-console
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
    @foreach ($items as $gallery)
    @include('galleries::public._list-item')
    @endforeach


text:
package jadx.gui.jobs;

import jadx.api.JavaClass;
import jadx.core.codegen.CodeWriter;
import jadx.gui.JadxWrapper;
import jadx.gui.utils.CacheObject;
import jadx.gui.utils.CodeLinesInfo;
import jadx.gui.utils.CodeUsageInfo;
import jadx.gui.utils.JNodeCache;
import jadx.gui.utils.Utils;
import jadx.gui.utils.search.StringRef;
import jadx.gui.utils.search.TextSearchIndex;

import java.util.List;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IndexJob extends BackgroundJob {

	private static final Logger LOG = LoggerFactory.getLogger(IndexJob.class);
	private final CacheObject cache;

	public IndexJob(JadxWrapper wrapper, CacheObject cache, int threadsCount) {
		super(wrapper, threadsCount);
		this.cache = cache;
	}

	protected void runJob() {
		JNodeCache nodeCache = cache.getNodeCache();
		final TextSearchIndex index = new TextSearchIndex(nodeCache);
		final CodeUsageInfo usageInfo = new CodeUsageInfo(nodeCache);
		cache.setTextIndex(index);
		cache.setUsageInfo(usageInfo);
		for (final JavaClass cls : wrapper.getClasses()) {
			addTask(new Runnable() {
				@Override
				public void run() {
					try {
						index.indexNames(cls);

						CodeLinesInfo linesInfo = new CodeLinesInfo(cls);
						List<StringRef> lines = splitLines(cls);

						usageInfo.processClass(cls, linesInfo, lines);
						if (Utils.isFreeMemoryAvailable()) {
							index.indexCode(cls, linesInfo, lines);
						} else {
							index.classCodeIndexSkipped(cls);
						}
					} catch (Exception e) {
						LOG.error("Index error in class: {}", cls.getFullName(), e);
					}
				}
			});
		}
	}

	@NotNull
	protected List<StringRef> splitLines(JavaClass cls) {
		List<StringRef> lines = StringRef.split(cls.getCode(), CodeWriter.NL);
		int size = lines.size();
		for (int i = 0; i < size; i++) {
			lines.set(i, lines.get(i).trim());
		}
		return lines;
	}

	@Override
	public String getInfoString() {
		return "Indexing: ";
	}
}


text:
//-*-C++-*-

#ifndef rsxgl_striped_array_H
#define rsxgl_striped_array_H

#if !defined(assert)
#include <cassert>
#endif

#include <memory>
#include <cstdlib>
#include <cstring>
#include <boost/mpl/transform.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip.hpp>
#include <boost/type_traits.hpp>

#include <iostream>

#include "cxxutil.h"

#if defined(__APPLE__)
#define RSXGL_MEMALIGN(ALIGN,SIZE) malloc((SIZE))
#else
#include <malloc.h>
#define RSXGL_MEMALIGN(ALIGN,SIZE) memalign((ALIGN),(SIZE))
#endif

// Align must be a power of two.
template< typename Types, typename SizeType, size_t Align >
struct striped_object_array {
  typedef Types value_types;
  typedef SizeType size_type;

  typedef typename boost::mpl::transform< value_types, boost::add_pointer< boost::mpl::_ > >::type pointers_type;
  typedef typename boost::mpl::transform< value_types, typename boost::add_reference< boost::mpl::_ > >::type references_type;

  struct allocate_array {
    size_type size;

    allocate_array(size_type _size) : size(_size) {}

    template< typename Type >
    void operator()(Type * & array) const {
      const size_t aligned_size = align_pot< size_t, Align >(size * sizeof(Type));
      array = (Type *)RSXGL_MEMALIGN(Align,aligned_size);
    }
  };

  struct default_predicate {
    bool operator()(size_type) const {
      return true;
    }
  };

  template< typename Predicate = default_predicate >
  struct destruct_fn {
    size_type size;
    const Predicate & p;

    destruct_fn(size_type _size,const Predicate & _p) : size(_size), p(_p) {}

    template< typename Type >
    void operator()(Type * & array) const {
      if(array != 0) {
	for(size_type i = 0;i < size;++i) {
	  if(p(i)) {
	    (array + i) -> ~Type();
	  }
	}
	free(array);
	array = 0;
      }
    }
  };

  struct resize_array {
    const size_type prev_size, new_size;

    resize_array(const size_type _prev_size,const size_type _new_size) : prev_size(_prev_size), new_size(_new_size) {
    }

    template< typename Type >
    void operator()(Type * & array) const {
      // See if aligned sizes actually match - then we don't actually allocate anything new:
      const size_t new_aligned_size = align_pot< size_t, Align >(new_size * sizeof(Type));
      if((array != 0) && (align_pot< size_t, Align >(prev_size * sizeof(Type)) == new_aligned_size)) return;

      Type * tmp = (Type *)RSXGL_MEMALIGN(Align,new_aligned_size);

      if(array != 0) {
	// Here we do something potentially dangerous, which is to move C++ objects without telling them.
	// Yup, C++0x move constructors could be helpful here, so let's make that a TODO.
	memcpy(tmp,array,std::min(prev_size,new_size) * sizeof(Type));
	free(array);
      }

      array = tmp;
    }
  };

  struct construct_item_fn {
    size_type i;

    construct_item_fn(size_type _i)
      : i(_i) {
    }

    template< typename Type >
    void operator()(Type * & array) const {
      new (array + i) Type;
    }
  };

  struct destruct_item_fn {
    size_type i;

    destruct_item_fn(size_type _i)
      : i(_i) {
    }

    template< typename Type >
    void operator()(Type * & array) const {
      (array + i) -> ~Type();
    }
  };

  struct type {
    pointers_type & values;
    size_type & size;

    type(pointers_type & _values,size_type & _size)
      : values(_values), size(_size) {
    }

    void allocate(size_type _size = 0) {
      boost::fusion::for_each(values,allocate_array(_size));
      size = _size;
    }

    void destruct() {
      default_predicate p;
      boost::fusion::for_each(values,destruct_fn< default_predicate >(size,p));
    }

    template< typename Predicate >
    void destruct(const Predicate & p) {
      boost::fusion::for_each(values,destruct_fn< Predicate >(size,p));
    }

    //
    void resize(size_type _size) {
      boost::fusion::for_each(values,resize_array(size,_size));
      size = _size;
    }

    template< size_t I >
    typename boost::add_reference< typename boost::fusion::result_of::at_c< value_types, I >::type >::type
    at(size_type i) {
      return boost::fusion::at_c< I >(values)[i];
    }

    void construct_item(size_type i) {
      boost::fusion::for_each(values,construct_item_fn(i));
    }

    void destruct_item(size_type i) {
      boost::fusion::for_each(values,destruct_item_fn(i));
    }
  };

  struct const_type {
    const pointers_type & values;
    const size_type & size;

    const_type(const pointers_type & _values,const size_type & _size)
      : values(_values), size(_size) {
    }

    /*const_type(type & rhs)
      : values(rhs.values), size(rhs.size) {
      }*/

    template< size_t I >
    typename boost::add_reference< typename boost::add_const< typename boost::fusion::result_of::at_c< value_types, I >::type >::type >::type
    at(size_type i) const {
      return boost::fusion::at_c< I >(values)[i];
    }
  };

  // Actually moves an object in the same manner as arrays are resized.
  struct move_item_fn {
    size_type lhs_i, rhs_i;

    move_item_fn(const size_type _lhs_i,const size_type _rhs_i)
      : lhs_i(_lhs_i), rhs_i(_rhs_i) {
    }

    template< typename Type >
    static void move_it(Type & lhs,Type const & rhs) {
      memcpy(&lhs,&rhs,sizeof(Type));
    }

    template< typename ArraysPair >
    void operator()(ArraysPair p) const {
      //boost::fusion::at_c< 0 >(p)[lhs_i] = boost::fusion::at_c< 1 >(p)[rhs_i];
      move_it(boost::fusion::at_c< 0 >(p)[lhs_i],boost::fusion::at_c< 1 >(p)[rhs_i]);
    }
  };

  static void move_item(type lhs,const size_type lhs_i,
			type rhs,const size_type rhs_i) {
    assert(lhs_i < lhs.size);
    assert(rhs_i < rhs.size);

    boost::fusion::for_each(boost::fusion::zip(lhs.values,rhs.values),move_item_fn(lhs_i,rhs_i));
  }
};

#endif


text:
{- *** MOCS-COPYRIGHT-NOTICE-BEGIN ***
 -
 - This copyright notice is auto-generated by ./add-copyright-notice.
 - Additional copyright notices must be added below the last line of this notice.
 -
 - MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/): "haskell-frontend/Main.hs".
 - The content of this file is copyright of Saarland University -
 - Copyright (C) 2009 Saarland University, Reactive Systems Group, Lars Kuhtz.
 -
 - This file is part of MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/).
 -
 - License: three-clause BSD style license.
 - The license text can be found in the file LICENSE.
 -
 - *** MOCS-COPYRIGHT-NOTICE-END *** -}

-- | Main MoCS module
module Main where

import Control.Monad

import Data.List
import Data.Maybe
import System.Console.GetOpt
import System ( getArgs )
import System.Exit ( exitSuccess )
import qualified Data.Map as M
import Foreign.C.Types
import IO

import PSL
import ToString
import PSLFragment
import T2Automaton
import Ordinal

import CExpr
import CAut

-- generated by make
import MoCSVersion

-- -------------------------------------------------------------------------- --
-- Program Options
data Options = Options { version :: Bool
                       , formula :: Maybe PSL  -- takes an input method
                       , help :: Bool
                       , output :: String
                       }

options :: [OptDescr (Options -> Options)]
options = [ Option ['V'] ["version"] (NoArg (\o -> o {version = True})) "show version number"
          , Option ['f'] ["formula"] (ReqArg (\s o -> o {formula = getFormula s}) "STRING") "formula string"
          , Option ['h'] ["help"] (NoArg (\o -> o {help = True})) "display help text"
          , Option ['o'] ["output"] (ReqArg (\s o -> o {output = s}) "STRING") "output file name"
          ]

defaultOpts :: Options
defaultOpts = Options
  { version = False
  , formula = Nothing
  , help = False
  , output = "/dev/stdout"
  }

getOptions :: [String] -> IO Options
getOptions args = do
  case getOpt RequireOrder options args of
    (o,[f],[])   -> x (foldl (flip id) defaultOpts o, Just f)
    (o,[],[])    -> x (foldl (flip id) defaultOpts o, Nothing)
    (_,(_:t),[]) -> error ("Unexpected parameters: " ++ concat t ++ "\n" ++ commandLineHelp)
    (_,_,errs)   -> error (concat errs ++ commandLineHelp)
    where
    x (o@(Options { formula = Just _ }), _ ) = return o
    x (o@(Options { formula = Nothing }) , Just f ) = do { x <- parseFormulaFile f; return $ o { formula = x } }
    x (o@(Options { formula = Nothing }) , Nothing ) = do { x <- getContents; return $ o { formula = getFormula x } } --error ("Either option '-f' or a parameter with a formula file must be givien\n" ++ commandLineHelp)
    parseFormulaFile f = readFile f >>= (return.getFormula)

getFormula s = either (error . show) Just (parsePSL s)

usageHeader = "\
\MoCS [--ouput FILE] FILE\n\
\MoCS [--output FILE] --formula STRING\n\
\MoCS [--output FILE]\n\
\MoCS --help\n\
\MoCS --version\n\n\
\The formula is provided either via the -f option or in a file.\n\
\By default the formula is read from stdin and the result is written to stdout."

name = "MoCS"
versionInfo = name ++ " (version " ++ mocsVersion ++ " revision " ++ mocsRevision ++ ")\n\n" ++
              "Copyright (C) 2010 Saarland University\n" ++
              "Author: Lars Kuhtz <kuhtz@cs.uni-sb.de>\n\n" ++
              "All rights reserved. Usage exclusively under the terms of the license\n\
              \available from: http://react.cs-uni-sb.de/tools/mocs/LICENSE\n\n" ++
              "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
              \PARTICULAR PURPOSE."

syntaxHelp = "\
\Syntax for formulas:\n\
\\n\
\Formula ::= '(' Formula ')' | RegEx | '\\strong' Regex\n\
\          | PrefixOp Formula | BPrefixOp BoundExpr Formula\n\
\          | Formula BinaryOp Formula | Formula BBinaryOp BoundExpr Formula\n\
\          | Formula '\\abort' Prop | RegEx '\\simplies' Formula\n\
\\n\
\PrefixOp ::= '\\not' | '\\N' | '\\wN' | '\\G' | '\\F'\n\
\BPreifxOp ::= '\\BN' | '\\wBN' | '\\BG' | '\\BF' | '\\sBG' | '\\wBF' \n\
\\n\
\BinaryOp ::= '\\and' | '\\or' | '\\implies' | '\\equiv'\n\
\           | '\\U' | '\\W' | '\\R' | '\\sR'\n\
\BBinaryOp ::= '\\BU' | '\\BR' | '\\BW' | '\\SBR'\n\
\\n\
\Prop ::= '(' Prop ')' | Var | 'true' | 'false' | '-' Prop\n\
\       | Prop '+' Prop | Prop '^' Prop\n\
\\n\
\RegEx ::= '(' RegEx ')' | Prop | 'epsilon'\n\
\        | RegEx '&&' RegEx | RegEx '|' RegEx | RegEx ':' RegEx | RegEx ';' RegEx\n\
\        | RegEx '*' | RegEx '[' Ordinal ']'\n\
\\n\
\Var ::= \"[_a-zA-Z][_a-zA-Z0-9]*\"\n\
\\n\
\BoundExpr ::= '(' BoundExpr ')' | Ordinal\n\
\            | BoundExpr '*' BoundExpr | '-' BoundExpr | BoundExpr '++'\n\
\\n\
\Ordinal ::= [0-9]+ | 'infty'"

commandLineHelp = usageInfo usageHeader options ++ "\n\n" ++ syntaxHelp

-- -------------------------------------------------------------------------- --
-- main program
{--
 main = do
 -  x <- newAutCtx
 -  -  a0 <- propAut x [1,2]
 -  -  a1 <- constAut x True
 -  -  a2 <- propAut x [2,3]
 -  -  a3 <- andAut a0 a1
 -  -  a4 <- orAut a3 a2
 -  -  a5 <- dualAut a4
 -  -  a6 <- nextAut =<< gAut =<< (untilAut a4 a3)
 -  -  autToDot "test.dot" a6 "aut"
 -  -  print "done"
 -
--}

-- enable / disable debugging
d a = a

main = do

  -- get arguments
  args <- getArgs
  opts <- getOptions args

  when (version opts) (putStrLn versionInfo >> exitSuccess)
  when (help opts) (putStrLn commandLineHelp >> exitSuccess)

  -- Parse Formula
  let f = fromJust $ formula opts
  --d putStrLn $ toString f
  --d putStrLn $ show $ horizon f

  -- Separate
  let (prefix,suffix) = separate f
  let hor = maximum $ map horizon suffix
  --d putSep
  --d putStrLn $ "prefix-formula:"
  --d putStrLn $ toString prefix

  ------------------------------------------------------------------------------
  -- Prefix Automaton
  (_,ptable,a) <- createAut prefix
  --d putStrLn $ "prefix-automaton (ptable):"
  --d putStrLn $ toString $ ptable

  -- autToDot "pre.dot" a "prefix-automaton"
  --sctx <- contextSize ctx
  --d putStrLn $ "size of prefix-automaton-context: " ++ (show sctx)

  -- Universal prefix automaton
  --d putStrLn $ "universal prefix-automaton:"
  (_,b) <- universalAut a
  -- autToDot "preu.dot" b "universal prefix-automaton"
  --suctx <- contextSize uctx
  --d putStrLn $ "size of universal prefix-automaton-context: " ++ (show suctx)

  -- Build state machine
  -- sm <- mkStateMachine b
  -- smToDot "sm.dot" sm "state machine"

  -- rollout
  --d putStrLn $ "rollout " ++ (show hor) ++ " steps:"
  e <- autPrefixRollout (fromInteger $ finite $ hor) b
  -- putStrLn $ "get size of rollout context"
  --se <- getExprCtx e >>= contextSize
  --d putStrLn $ "size of rollout-context: " ++ (show $ se)

  ------------------------------------------------------------------------------
  -- Suffix Automata
  -- putSep
  --d putStrLn $ "number of suffixes: " ++ show (length suffix)
  tmpctx <- newAutCtx
  (_,stable,as) <- foldM doSuffix (tmpctx,M.empty,[]) (zip [0..] suffix)
  oexprs <- mapM (rollmap hor) as

  -- exprsToDot "suffix_exprs.dot" (concatMap snd oexprs) "suffix_expressions"

  -- oexprs is a map from suffix-formulas (toString as used in variables names of prefix)
  -- to its oexprs list

  -- print "build vhdl monitor"

  callVhdlBuildMonitor (output opts) (fromInteger $ finite $ hor) b ptable e oexprs stable

  -- print "done"
  --  putStrLn $ concat (parMap rnf doSuffix' suffix)

  where
  rollmap h (i,a) = do
    exprs <- autSuffixRollout (fromInteger $ finite $ h) a
    return (i,exprs)

doSuffix (ctx,table,as) (_,s) = do
  (nctx,ntable,sa) <- createAutWithCtxAndTable ctx table s
  --  putStrLn $ toString sa
  -- putStrLn $ A.stats sa
  -- autToDot ("suf" ++ show i ++ ".dot") sa ("suffix-automaton " ++ toString s)
  --bracket (openFile ("suf" ++ show i) WriteMode) hClose (\h -> A.doA2dot h $ mkInt sa)
  -- putSep
  return (nctx,ntable,as ++ [(toString s,sa)]) -- what does ntable look like?

putSep = putStrLn $ "--------------------"

callVhdlBuildMonitor :: String -> Int -> AutPtr -> PropTable -> ExprPtr -> [(String,[ExprPtr])] -> PropTable -> IO ()
callVhdlBuildMonitor
  fname -- filename
  hor    -- horizon
  prefix_automaton
  ptable -- variable index tabel for prefix automaton
  pa_expr -- output expression of prefix automaton
  suffix_expressions -- map from suffix formulae (variable name) to list of output expressions
  stable -- variable index tabel for suffix automata
  = do
    vhdlBuildMonitor fname hor (M.size stable) (M.size ptable) pa_expr prefix_automaton sexprs
    where
    sexprs :: [[ExprPtr]]
    sexprs =
      let
        swap (a,b) = (b,a)
        swap_sort_ptable :: [(CLong,String)]
        swap_sort_ptable = sortBy (comp) (map swap (M.toList ptable))
        comp a b = if a < b then LT else (if b < a then GT else EQ)
      in
        map (\(_,v) -> maybe (lookuperror v) id (lookup v suffix_expressions)) swap_sort_ptable

    lookuperror v = error $ "variable " ++ v ++ " in ptable but not in suffix expressions"


text:
#include "dev/button-sensor.h"

#ifdef SKY_CONF_SENSORS
#define SKY_SENSORS SKY_CONF_SENSORS
#else
#define SKY_SENSORS 1
#endif

#if SKY_SENSORS
SENSORS(&button_sensor);
#endif

void
init_platform(void)
{
#if SKY_SENSORS
  process_start(&sensors_process, NULL);
#endif
}


text:
import logging
import re
from binascii import unhexlify
from datetime import datetime
from os import urandom
from urllib.parse import urlparse

from hiss.encryption import PY_CRYPTO, encrypt, decrypt
from hiss.exception import MarshalError
from hiss.handler.gntp import GNTP_BASE_VERSION, ENCRYPTION_ALGORITHM
from hiss.hash import HashInfo, generate_hash, validate_hash
from hiss.resource import Icon
from hiss.utility import parse_datetime

class Request(object):
    def __init__(self, version=GNTP_BASE_VERSION):
        self.version = version
        self.password = None
        self.command = ''
        self.body = {}
        self.sections = []
        self.identifiers = []

        self.use_hash = False
        self.use_encryption = False

        self._hash = None
        self._encryption = None

    def marshal(self, encoding='UTF-8'):
        """marshal the request ready to send over the wire."""

        if self.use_hash or self.use_encryption:
            if self.password is None:
                raise MarshalError('Password required to generate hash for marshaling of request.',
                                    'Request.marshal')

            self._hash = generate_hash(self.password.encode('UTF-8'))

        if self.use_encryption:
            if not PY_CRYPTO:
                raise MarshalError('Unable to encrypt message. PyCrypto not available')

            if ENCRYPTION_ALGORITHM == 'AES':
                iv = urandom(16)
            else:
                iv = urandom(8)

            self._encryption = (ENCRYPTION_ALGORITHM, iv)

        header = 'GNTP/%s %s' % (self.version, self.command)
        if self._encryption is not None:
            header += ' %s:%s' % self._encryption
        else:
            header += ' NONE'

        if self._hash is not None:
            header += ' %s:%s.%s' % self._hash

        header += '\r\n'
        data = bytearray(header.encode(encoding))

        body_data = bytearray()
        for name, value in iter(sorted(self.body.items())):
            body_data.extend(('%s: %s\r\n' % (name, value)).encode(encoding))

        body_data.extend(('\r\n').encode(encoding))

        if self._encryption is not None:
            body_data = self._encrypt(body_data)

        data.extend(body_data)

        for section in self.sections:
            section_data = bytearray()
            for name, value in section.items():
                if isinstance(value, self._IdReference):
                    section_data.extend(('%s: x-growl-resource//%s\r\n' % (name, str(value))).encode(encoding))
                else:
                    section_data.extend(('%s: %s\r\n' % (name, value)).encode(encoding))

            section_data.extend(('\r\n').encode(encoding))

            if self._encryption is not None:
                section_data = self._encrypt(section_data)

            data.extend(section_data)

        for identifier in self.identifiers:
            identifier_data = bytearray()
            identifier_data.extend(('Identifier: %s\r\n' % identifier['Identifier']).encode(encoding))
            idata = identifier['Data']
            identifier_data.extend(('Length: %d\r\n\r\n' % len(idata)).encode(encoding))

            if self._encryption is not None:
                idata = self._encrypt(idata)

            identifier_data.extend(idata)
            identifier_data.extend(('\r\n\r\n').encode(encoding))

            data.extend(identifier_data)

        return data

    def unmarshal(self, data, encoding='UTF-8'):
        """Unmarshal data received over the wire into a valid request"""

        if self._encryption is not None and not PY_CRYPTO:
            raise MarshalError('PyCrypto required to decrypt message')

        sections = data.split(b'\r\n\r\n')

        header_info_re = b'GNTP\/(?P<version>\d\.\d) (?P<command>[A-Z]+)( ((?P<encryptionAlgorithmID>\w+)\:(?P<ivValue>[a-fA-F0-9]+)|NONE)( (?P<keyHashAlgorithmID>\w+)\:(?P<keyHash>[a-fA-F0-9]+)\.(?P<salt>[a-fA-F0-9]+))?)?'
        header_section = sections.pop(0)
        header_info, *headers = header_section.split(b'\r\n')
        m = re.match(header_info_re, header_info)

        if m is not None:
            d = m.groupdict()
            self.version = d['version'].decode(encoding)
            self.command = d['command'].decode(encoding)

            if d['encryptionAlgorithmID'] is None:
                self.use_encryption = False
                self._encryption = None
            else:
                self.use_encryption = True
                self._encryption = (d['encryptionAlgorithmID'].decode(encoding),
                                    unhexlify(d['ivValue']))

            if d['keyHashAlgorithmID'] is None:
                self.use_hash = False
                self._hash = None
            else:
                if self.password is None:
                    raise MarshalError('Password required to validate hash for unmarshal of request.')

                self._hash = HashInfo(d['keyHashAlgorithmID'].decode(encoding),
                                      unhexlify(d['keyHash']),
                                      unhexlify(d['salt']))
                self.use_hash = True
                validate_hash(self.password, self._hash)

            if len(headers[0]) > 0:
                self._unmarshal_section(headers, self.body)

            if len(sections) > 0:
                info = None
                next_section_is_data = False
                for section in sections:
                    if not next_section_is_data:
                        info = {}
                        self._unmarshal_section(section.split(b'\r\n'), info)

                        if 'Identifier' in info:
                            next_section_is_data = True
                            self.identifiers.append(info)
                        else:
                            self.sections.append(info)
                    elif info is not None:
                        length = int(info['Length'])
                        info['Data'] = section[:length]
                        next_section_is_data = False
        else:
            raise MarshalError('Response.unmarshal: Invalid GNTP message')

    def _add_resource(self, key, resource):
        uid = resource.uid
        data = resource.data
        self.body[key] = 'x-growl-resource://%s' % uid

        identifier = {}
        identifier['Identifier'] = uid
        identifier['Data'] = data
        self.identifiers.append(identifier)

    def _unmarshal_section(self, lines, info):
        for line in lines:
            name, value = line.split(b':', 1)
            name = name.decode('UTF-8')
            value = value.decode('UTF-8').strip()

            if value.startswith('x-growl-resource://'):
                info[name] = self._IdReference(value[19:])
            else:
                info[name] = value

    def identifier_data(self, identifier):
        for i in self.identifiers:
            if i['Identifier'] == identifier:
                return i['Data']

        return None

    def _encrypt(self, data):
        encryption_algorithm, iv = self._encryption
        return encrypt(encryption_algorithm, iv, self._hash.key_hash, data)

    def _decrypt(self, data):
        encryption_algorithm, iv = self._encryption
        return decrypt(encryption_algorithm, iv, self._hash.key_hash, data)

    class _IdReference(object):
        def __init__(self, reference):
            self.reference = reference

        def __repr__(self):
            return self.reference

class Response(object):
    """GNTP/1.0 -(OK|ERROR|CALLBACK) <encryptionAlgoritm>
    <body>: <value>
    """

    def __init__(self, version=GNTP_BASE_VERSION):
        self.version = version
        """The GNTP protocol version number of this response"""

        self.status = ''
        self.command = ''
        self.body = {}

        self.use_hash = False
        self.use_encryption = False
        self._hash = None
        self._encryption = None

    def marshal(self, custom_headers=None):
        """marshal the response ready to send over the wire."""

        if self._encryption is not None and not PY_CRYPTO:
            raise Exception('Unable to encrypt message. PyCrypto not available')

        data = bytearray()

        header = 'GNTP/%s -%s' % (self.version, self.status)

        if self._encryption is not None:
            header += ' %s:%s' % self._encryption
        else:
            header += ' NONE\r\n'

        data.extend(header.encode('UTF-8'))

        if self.command != '':
            response_action = 'Response-Action: %s\r\n' % self.command.upper()
            data.extend(response_action.encode('UTF-8'))

        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%SZ')
        data.extend(('X-Timestamp: %s\r\n' % str(timestamp)).encode('UTF-8'))

        if custom_headers is not None:
            for key, value in custom_headers:
                data.extend(('%s: %s\r\n' % (key, value)).encode('UTF-8'))

        body_data = bytearray()
        for name, value in self.body.items():
            line = '%s: %s\r\n' % (name.strip(), str(value).strip())
            body_data.extend(line.encode('UTF-8'))

        if self._encryption is not None:
            body_data = self._encrypt(body_data)

        data.extend(body_data)
        return data

    def unmarshal(self, data):
        """Unmarshal data received over the wire into a valid response"""

        if self._encryption is not None and not PY_CRYPTO:
            raise MarshalError('Unable to decrypt message. PyCrypto not available')

        header, data = data.split(b'\r\n', maxsplit=1)

        header_re = ('GNTP\/(?P<version>\d\.\d) (?P<responsetype>\-?[A-Z]+)'
                     ' ((?P<encryptionAlgorithmID>\w+)\:(?P<ivValue>[a-fA-F0-9]+)|NONE)')
        m = re.match(header_re, header.decode('UTF-8'))
        if m is not None:
            d = m.groupdict()
            self.version = d['version']
            self.status = d['responsetype'].lstrip('-')

            if self.status == 'OK':
                self.status_code = 0

            if d['encryptionAlgorithmID'] is None:
                self.use_encryption = False
                self._encryption = None
            else:
                self.use_encryption = True
                self._encryption = (d['encryptionAlgorithmID'],
                                   d['ivValue'])
                data = self._decrypt(data)

            for line in [l for l in data.split(b'\r\n') if len(l) != 0]:
                try:
                    name, value = line.split(b':', 1)
                    name = name.decode('UTF-8').strip()
                    value = value.decode('UTF-8').strip()

                    # All
                    if name == 'Response-Action':
                        self.command = value.lower()

                    elif name == 'X-Timestamp':
                        self.timestamp = parse_datetime(value)
                    elif name == 'X-Message-Daemon':
                        self.daemon = value
                    elif name == 'Origin-Machine-Name':
                        self.origin = value
                    elif name == 'Origin-Software-Name':
                        self.origin_software_name = value
                    elif name == 'Origin-Software-Version':
                        self.origin_software_version = value
                    elif name == 'Origin-Platform-Name':
                        self.origin_platform_name = value
                    elif name == 'Origin-Platform-Version':
                        self.origin_platform_version = value

                    elif name == 'Error-Code':
                        self.status_code = int(value)
                    elif name == 'Error-Description':
                        self.reason = value

                    # Notify
                    elif name == 'Application-Name':
                        self.notifier_name = value
                    elif name == 'Notification-ID':
                        self.nid = value
                    elif name == 'Notification-Callback-Result':
                        self.callback_status = value
                    elif name == 'Notification-Callback-Context':
                        self.callback_context = value
                    elif name == 'Notification-Callback-Context-Type':
                        self.callback_context_type = value
                    elif name == 'Notification-Callback-Timestamp':
                        self.callback_timestamp = parse_datetime(value)

                    # Subscribe
                    elif name == 'Subscription-TTL':
                        self.ttl = int(value)

                    else:
                        if name not in self.body:
                            self.body[name] = value
                        else:
                            if not isinstance(self.body[name], list):
                                self.body[name] = [self.body[name]]

                            self.body[name].append(value)
                except ValueError:
                    logging.debug('hiss.handler.GNTP.Response.unmarshal - Error splitting %s' % line)
                    raise

    def _encrypt(self, data):
        pass

    def _decrypt(self, lines):
        pass

class RegisterRequest(Request):
    def __init__(self, notifier):
        Request.__init__(self)

        self.command = 'REGISTER'
        self.body['Application-Name'] = notifier.name
        self.body['Notifications-Count'] = len(notifier.notification_classes)

        if isinstance(notifier.icon, Icon):
            self._add_resource('Application-Icon', notifier.icon)
        else:
            self.body['Application-Icon'] = notifier.icon

        for info in notifier.notification_classes.values():
            section = {}
            section['Notification-Name'] = info.name
            section['Notification-Enabled'] = info.enabled

            self.sections.append(section)

class NotifyRequest(Request):
    def __init__(self, notification, notifier):
        Request.__init__(self)

        self.command = 'NOTIFY'
        self.body['Application-Name'] = notifier.name
        self.body['Notification-Name'] = notification.name
        self.body['Notification-ID'] = notification.uid
        self.body['Notification-Title'] = notification.title

        if notification.text is not None:
            self.body['Notification-Text'] = notification.text

        if notification.timeout == 0:
            self.body['Notification-Sticky'] = 'True'

        if notification.sound is not None:
            self.body['X-Sound'] = notification.sound

        if isinstance(notification.icon, Icon):
            self._add_resource('Notification-Icon', notification.icon)
        else:
            self.body['Notification-Icon'] = notification.icon

        callback = notification.callback
        if callback is not None:
            if urlparse(callback.command).scheme != '':
                self.body['Notification-Callback-Target'] = callback.command
            else:
                self.body['Notification-Callback-Context'] = callback.command
                self.body['Notification-Callback-Context-Type'] = 'string'

class SubscribeRequest(Request):
    def __init__(self, notifier):
        Request.__init__(self)

        self.command = 'SUBSCRIBE'
        self.body['Subscriber-ID'] = notifier.signature
        self.body['Subscriber-Name'] = notifier.name

class UnregisterRequest(Request):
    def __init__(self, notifier):
        Request.__init__(self)

        self.command = 'REGISTER'
        self.body['Application-Name'] = notifier.name
        self.body['Notifications-Count'] = 0


text:
(function() {
    "use strict";

    this.Video = function() {
        this.orientation = new Orientation(Video.shader);
        // Initialize a texture for the video.
        this.texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        // Add a hidden video element to the page.
        document.getElementById('hiddenElementsGoHere').innerHTML = `
<video id="video" src="video.mp4"
style="display: none;"
preload="auto" crossorigin="anonymous" autoplay controls>
Video support is required to run some features of this demo.
</video>
`;
    };

    this.Video.prototype.cleanup = function() {
        this.orientation.cleanup();
        gl.deleteTexture(this.texture);
        document.getElementById('hiddenElementsGoHere').innerHTML = '';
    };

    this.Video.prototype.render = function() {
        // Update the texture.
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
            document.getElementById('video'));
        this.orientation.render();
    };

    this.Video.shader = `

precision highp float;
uniform mat4 uOrientation;
uniform sampler2D sampler;
#define pi 3.141592653589793
vec4 scene(vec3 p) {
    vec3 d = normalize(vec3(-p.x, -p.y, 1));
    d = (vec4(d, 1.0) * uOrientation).xyz;
    float x = mod((atan(d.z, d.x) + (pi / 2.0)) / (2.0 * pi), 1.0);
    float y = mod(acos(d.y) / pi, 1.0);
    if(p.z >= 0.0) {
        return texture2D(sampler, vec2(x, y * 0.5));
    } else {
        return texture2D(sampler, vec2(x, y * 0.5 + 0.5));
    }
}

`;

}).call(this);
Scenes.push(Video);


text:
START_ATF_NAMESPACE
    struct  CFtpConnection : CInternetConnection
    {
        enum CmdResponseType
        {
            CmdRespNone = 0x0,
            CmdRespRead = 0x1,
            CmdRespWrite = 0x2,
        };
        ATL::CStringT<char> m_strServerName;
    };
END_ATF_NAMESPACE


text:
from PySide import QtCore, QtGui

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(311, 194)
        self.blue_top = QtGui.QComboBox(Form)
        self.blue_top.setGeometry(QtCore.QRect(10, 10, 131, 22))
        self.blue_top.setStyleSheet("background-color: rgb(170, 170, 255);")
        self.blue_top.setObjectName("blue_top")
        self.blue_top.addItem("")
        self.purple_top = QtGui.QComboBox(Form)
        self.purple_top.setGeometry(QtCore.QRect(170, 10, 131, 22))
        self.purple_top.setStyleSheet("background-color: rgb(255, 170, 255)")
        self.purple_top.setObjectName("purple_top")
        self.purple_top.addItem("")
        self.blue_mid = QtGui.QComboBox(Form)
        self.blue_mid.setGeometry(QtCore.QRect(10, 70, 131, 22))
        self.blue_mid.setStyleSheet("background-color: rgb(170, 170, 255);")
        self.blue_mid.setObjectName("blue_mid")
        self.blue_mid.addItem("")
        self.purple_mid = QtGui.QComboBox(Form)
        self.purple_mid.setGeometry(QtCore.QRect(170, 70, 131, 22))
        self.purple_mid.setStyleSheet("background-color: rgb(255, 170, 255)")
        self.purple_mid.setObjectName("purple_mid")
        self.purple_mid.addItem("")
        self.blue_jungle = QtGui.QComboBox(Form)
        self.blue_jungle.setGeometry(QtCore.QRect(10, 40, 131, 22))
        self.blue_jungle.setStyleSheet("background-color: rgb(170, 170, 255);")
        self.blue_jungle.setObjectName("blue_jungle")
        self.blue_jungle.addItem("")
        self.purple_jungle = QtGui.QComboBox(Form)
        self.purple_jungle.setGeometry(QtCore.QRect(170, 40, 131, 22))
        self.purple_jungle.setStyleSheet("background-color: rgb(255, 170, 255)")
        self.purple_jungle.setObjectName("purple_jungle")
        self.purple_jungle.addItem("")
        self.blue_adc = QtGui.QComboBox(Form)
        self.blue_adc.setGeometry(QtCore.QRect(10, 100, 131, 22))
        self.blue_adc.setStyleSheet("background-color: rgb(170, 170, 255);")
        self.blue_adc.setObjectName("blue_adc")
        self.blue_adc.addItem("")
        self.purple_adc = QtGui.QComboBox(Form)
        self.purple_adc.setGeometry(QtCore.QRect(170, 100, 131, 22))
        self.purple_adc.setStyleSheet("background-color: rgb(255, 170, 255)")
        self.purple_adc.setObjectName("purple_adc")
        self.purple_adc.addItem("")
        self.blue_support = QtGui.QComboBox(Form)
        self.blue_support.setGeometry(QtCore.QRect(10, 130, 131, 22))
        self.blue_support.setStyleSheet("background-color: rgb(170, 170, 255);")
        self.blue_support.setObjectName("blue_support")
        self.blue_support.addItem("")
        self.purple_support = QtGui.QComboBox(Form)
        self.purple_support.setGeometry(QtCore.QRect(170, 130, 131, 22))
        self.purple_support.setStyleSheet("background-color: rgb(255, 170, 255)")
        self.purple_support.setObjectName("purple_support")
        self.purple_support.addItem("")
        self.set_button = QtGui.QPushButton(Form)
        self.set_button.setGeometry(QtCore.QRect(10, 160, 291, 23))
        self.set_button.setObjectName("set_button")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        Form.setTabOrder(self.blue_top, self.purple_top)
        Form.setTabOrder(self.purple_top, self.purple_jungle)
        Form.setTabOrder(self.purple_jungle, self.blue_jungle)
        Form.setTabOrder(self.blue_jungle, self.blue_mid)
        Form.setTabOrder(self.blue_mid, self.purple_mid)
        Form.setTabOrder(self.purple_mid, self.purple_adc)
        Form.setTabOrder(self.purple_adc, self.blue_adc)
        Form.setTabOrder(self.blue_adc, self.blue_support)
        Form.setTabOrder(self.blue_support, self.purple_support)
        Form.setTabOrder(self.purple_support, self.set_button)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate("Form", "Lineups", None, QtGui.QApplication.UnicodeUTF8))
        self.blue_top.setItemText(0, QtGui.QApplication.translate("Form", "Top", None, QtGui.QApplication.UnicodeUTF8))
        self.purple_top.setItemText(0, QtGui.QApplication.translate("Form", "Top", None, QtGui.QApplication.UnicodeUTF8))
        self.blue_mid.setItemText(0, QtGui.QApplication.translate("Form", "Mid", None, QtGui.QApplication.UnicodeUTF8))
        self.purple_mid.setItemText(0, QtGui.QApplication.translate("Form", "Mid", None, QtGui.QApplication.UnicodeUTF8))
        self.blue_jungle.setItemText(0, QtGui.QApplication.translate("Form", "Jungle", None, QtGui.QApplication.UnicodeUTF8))
        self.purple_jungle.setItemText(0, QtGui.QApplication.translate("Form", "Jungle", None, QtGui.QApplication.UnicodeUTF8))
        self.blue_adc.setItemText(0, QtGui.QApplication.translate("Form", "ADC", None, QtGui.QApplication.UnicodeUTF8))
        self.purple_adc.setItemText(0, QtGui.QApplication.translate("Form", "ADC", None, QtGui.QApplication.UnicodeUTF8))
        self.blue_support.setItemText(0, QtGui.QApplication.translate("Form", "Support", None, QtGui.QApplication.UnicodeUTF8))
        self.purple_support.setItemText(0, QtGui.QApplication.translate("Form", "Support", None, QtGui.QApplication.UnicodeUTF8))
        self.set_button.setText(QtGui.QApplication.translate("Form", "Set lineup", None, QtGui.QApplication.UnicodeUTF8))


text:
Release Notes
=============

1.1.1
-----
* Added Django 1.8 support

1.1.0
-----
* Fixed #14 -- Truncate long user_agents
* Fixed #23 -- Cannot use admin view search
* Added Django 1.7 migrations

1.0.0
-----
*No changes from 1.0.0-beta1.*

1.0.0-beta1
-----------
* #8 -- Consistent URL patterns
* #11 -- Support Django 1.6's ATOMIC_REQUESTS
* German translation added

0.1.4
-----
* Python 3.4 support
* Django 1.7 (beta) support
* Italian translation added
* Chinese translation added
* Arabic translation updated

0.1.3
-----
* Documentation
* Hebrew translation added
* Arabic translation added
* Fixed #3 -- Reset user_id on logout
* Fixed #4 -- Add explicit license text

0.1.2
-----
* Ship with default templates
* Added Dutch translation

0.1.1
-----
* Added South migrations

0.1.0
-----
* Initial release


text:
require('enyo');

/**
* Contains the declaration for the {@link module:enyo/InvertBooleanBinding~InvertBooleanBinding} kind.
* @module enyo/InvertBooleanBinding
*/

var
	kind = require('./kind');

var
	Binding = require('./Binding');

/**
* An {@link module:enyo/Binding~Binding} designed to invert a {@glossary Boolean} value.
*
* @class InvertBooleanBinding
* @extends module:enyo/Binding~Binding
* @public
*/
module.exports = kind(
	/** @lends module:enyo/InvertBooleanBinding~InvertBooleanBinding.prototype */ {

	name: 'enyo.InvertBooleanBinding',

	/**
	* @private
	*/
	kind: Binding,

	/**
	* @private
	*/
	transform: function (value) {
		return ! value;
	}
});


text:
namespace Zip
{

/// @addtogroup zipint_group Zip Code Internals
///
/// The zip code internals are mostly undocumented, but should be fairly
/// obvious to anyone who is familiar with the zip file format.

/// @ingroup zip_group
// @{

//////////////////////////////////////////////////////////////////////////
/// \brief Helper class for tracking CRC and uncompressed size
///
/// ZipStatFilter allows us to track CRC and uncompressed size
/// on the fly. This is necessary when dealing with compressed files as the
/// CRC must be of the uncompressed data.
///
/// ZipStatFilter is mostly intended for internal use by the zip code.
/// However, it can be useful when reading zips sequentially using the
/// stream interface to provide CRC checking.
///
/// Example
///
/// @code
/// // It's assumed that you would use proper error checking and that
/// // zip is a valid pointer to a ZipArchive and otherStream is a pointer
/// // to a valid stream.
/// Zip::ZipArchive *zip;
/// Stream *otherStream;
///
/// // We need the real central directory to compare the CRC32
/// Zip::CentralDir *realCD = zip->findFileInfo("file.txt");
/// Stream *stream = zip->openFile("file.txt", ZipArchive::Read);
///
/// Zip::CentralDir fakeCD;
/// Zip::ZipStatFilter zsf(&fakeCD);
///
/// zsf.attachStream(stream);
///
/// // ... read entire file sequentially using zsf instead of stream
/// otherStream->copyFrom(&zsf);
///
/// zsf.detachStream();
///
/// // fakeCD.mCRC32 now contains the CRC32 of the stream
/// if(fakeCD.mCRC32 != realCD->mCRC32)
/// {
///    // ... handle CRC failure ...
/// }
///
/// zip->closeFile(stream);
/// @endcode
///
/// A more complete example of this may be found in the code for the
/// ZipArchive::extractFile() method in zipArchive.cc
///
//////////////////////////////////////////////////////////////////////////
class ZipStatFilter : public FilterStream
{
   typedef FilterStream Parent;

protected:
   Stream *mStream;

   CentralDir *mCD;

   virtual bool _write(const U32 numBytes, const void *buffer)
   {
      if(! mStream->write(numBytes, buffer))
         return false;

      mCD->mUncompressedSize += numBytes;
      mCD->mCRC32 = calculateCRC(buffer, numBytes, mCD->mCRC32);

      return true;
   }

   virtual bool _read(const U32 numBytes, void *buffer)
   {
      if(! mStream->read(numBytes, buffer))
         return false;

      mCD->mUncompressedSize += numBytes;
      mCD->mCRC32 = calculateCRC(buffer, numBytes, mCD->mCRC32);

      return true;
   }

public:
   ZipStatFilter() : mCD(NULL), mStream(NULL) {}
   ZipStatFilter(CentralDir *cd) : mCD(cd), mStream(NULL) {}
   virtual ~ZipStatFilter()
   {
      detachStream();
   }

   virtual bool attachStream(Stream *stream)
   {
      if(mCD == NULL)
         return false;

      mStream = stream;
      mCD->mUncompressedSize = 0;
      mCD->mCRC32 = INITIAL_CRC_VALUE;
      return true;
   }

   virtual void detachStream()
   {
      if(mStream == NULL)
         return;

      // Post condition the CRC
      mCD->mCRC32 ^= CRC_POSTCOND_VALUE;
      mStream = NULL;
   }

   virtual Stream *getStream()                     { return mStream; }

   void setCentralDir(CentralDir *cd)              { mCD = cd; }
   CentralDir *getCentralDir()                     { return mCD; }
};

// @}

} // end namespace Zip

#endif // _ZIPSTATFILTER_H_


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
//   Copyright (c) 2013 Microsoft Corporation
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using Microsoft.Research.DataOnboarding.FileService.Interface;
using Microsoft.Research.DataOnboarding.FileService.Interface.Fakes;
using Microsoft.Research.DataOnboarding.QueueService;
using Microsoft.Research.DataOnboarding.QueueService.Fakes;
using Microsoft.Research.DataOnboarding.RepositoriesService.Interface;
using Microsoft.Research.DataOnboarding.RepositoriesService.Interface.Fakes;
using Microsoft.Research.DataOnboarding.Utilities.Enums;
using Microsoft.Research.DataOnboarding.Utilities.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace QueueService.Tests
{
    [TestClass]
    public class MessageRouterTest
    {
        /// <summary>
        /// Contains the reference to queueRepository.
        /// </summary>
        private IQueueRepository queueRepository;

        /// <summary>
        /// Contains the reference to fileServiceFactory.
        /// </summary>
        private IFileServiceFactory fileServiceFactory;

        /// <summary>
        /// Contains the reference to repositoryService.
        /// </summary>
        private IRepositoryService repositoryService;

        /// <summary>
        /// Contains the reference to blobRepository.
        /// </summary>
        private IBlobDataRepository blobRepository;

        /// <summary>
        /// Contains the reference to fileServiceFactory.
        /// </summary>
        private IMessageHandlerFactory messageHandlerFactory;

        /// <summary>
        /// Contains the list of messages.
        /// </summary>
        private List<BaseMessage> messages;

        /// <summary>
        /// contains the reference to processed message.
        /// </summary>
        private List<BaseMessage> processedMessage;

        [TestMethod]
        public void Allow_Process()
        {
            this.messages = new List<BaseMessage>();
            this.messages.Add(new PublishMessage() { RepositoryId = 1, FileId = 1 });
            this.messages.Add(new VerifyFileMessage() { RepositoryId = 1, FileId = 1 });

            MessageRouter messageRouter = this.GetMessageRouter(false);
            messageRouter.ProcessQueue();
            Assert.IsTrue(this.messages.Count == this.processedMessage.Count);
        }

        [TestMethod]
        public void Skip_Process_When_ProcessOn_Is_Greater_Than_Now()
        {
            this.messages = new List<BaseMessage>();
            this.messages.Add(new PublishMessage() { RepositoryId = 1, FileId = 1, ProcessOn=DateTime.UtcNow.AddHours(1) });
            this.messages.Add(new VerifyFileMessage() { RepositoryId = 1, FileId = 1, ProcessOn = DateTime.UtcNow.AddMinutes(5)});

            MessageRouter messageRouter = this.GetMessageRouter(false);
            messageRouter.ProcessQueue();

            Assert.IsTrue(this.processedMessage.Count == 0);
        }

        [TestMethod]
        public void Skip_Process_When_Handler_Is_Null()
        {
            this.messages = new List<BaseMessage>();
            this.messages.Add(new PublishMessage() { RepositoryId = 1, FileId = 1});
            this.messages.Add(new VerifyFileMessage() { RepositoryId = 1, FileId = 1});

            MessageRouter messageRouter = this.GetMessageRouter(true);
            messageRouter.ProcessQueue();

            Assert.IsTrue(this.processedMessage.Count == 0);
        }

        /// <summary>
        /// Reuturns the message Router instance.
        /// </summary>
        /// <param name="nullMessageHandler">Indicates if the handler has to be returned or not.</param>
        /// <returns>MessaeRouter instance.</returns>
        private MessageRouter GetMessageRouter(bool nullMessageHandler)
        {
            this.processedMessage = new List<BaseMessage>();
            this.fileServiceFactory = new StubIFileServiceFactory();
            this.repositoryService = new StubIRepositoryService();
            this.blobRepository = new StubIBlobDataRepository();
            IMessageHandler messageHandler = null;

            if (!nullMessageHandler)
            {
                messageHandler = new StubIMessageHandler()
                {
                    ProcessMessageBaseMessage = (message) =>
                        {
                            this.processedMessage.Add(message);
                        }
                };
            }

            this.messageHandlerFactory = new StubIMessageHandlerFactory
            {
                GetMessageHandlerMessageHandlerEnum = (handler) => {

                    return messageHandler;
                }
            };

            this.queueRepository = new StubIQueueRepository()
            {
                GetQueuedMessagesInt32Int32 = (noofmessages, visibilityTimeout) =>
                    {
                        return this.messages;
                    }
            };

            MessageRouter messageRouter = new MessageRouter(this.messageHandlerFactory, this.queueRepository);
            return messageRouter;
        }
    }
}


text:
package com.google.common.collect.testing.testers;

import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;

import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * A generic JUnit test which tests {@code retainAll} operations on a
 * collection. Can't be invoked directly; please see
 * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
 *
 * @author Chris Povirk
 */
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible
public class CollectionRetainAllTester<E> extends AbstractCollectionTester<E> {

  /**
   * A collection of elements to retain, along with a description for use in
   * failure messages.
   */
  private class Target {
    private final Collection<E> toRetain;
    private final String description;

    private Target(Collection<E> toRetain, String description) {
      this.toRetain = toRetain;
      this.description = description;
    }

    @Override public String toString() {
      return description;
    }
  }

  private Target empty;
  private Target disjoint;
  private Target superset;
  private Target nonEmptyProperSubset;
  private Target sameElements;
  private Target partialOverlap;
  private Target containsDuplicates;
  private Target nullSingleton;

  @Override public void setUp() throws Exception {
    super.setUp();

    empty = new Target(emptyCollection(), "empty");
    /*
     * We test that nullSingleton.retainAll(disjointList) does NOT throw a
     * NullPointerException when disjointList does not, so we can't use
     * MinimalCollection, which throws NullPointerException on calls to
     * contains(null).
     */
    List<E> disjointList = Arrays.asList(e3(), e4());
    disjoint
        = new Target(disjointList, "disjoint");
    superset
        = new Target(MinimalCollection.of(
            e0(), e1(), e2(), e3(), e4()),
            "superset");
    nonEmptyProperSubset
        = new Target(MinimalCollection.of(e1()), "subset");
    sameElements
        = new Target(Arrays.asList(createSamplesArray()), "sameElements");
    containsDuplicates = new Target(
        MinimalCollection.of(e0(), e0(), e3(), e3()),
        "containsDuplicates");
    partialOverlap
        = new Target(MinimalCollection.of(e2(), e3()),
            "partialOverlap");
    nullSingleton
        = new Target(Collections.<E>singleton(null), "nullSingleton");
  }

  // retainAll(empty)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_emptyPreviouslyEmpty() {
    expectReturnsFalse(empty);
    expectUnchanged();
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_emptyPreviouslyEmptyUnsupported() {
    expectReturnsFalseOrThrows(empty);
    expectUnchanged();
  }

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_emptyPreviouslyNonEmpty() {
    expectReturnsTrue(empty);
    expectContents();
    expectMissing(e0(), e1(), e2());
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_emptyPreviouslyNonEmptyUnsupported() {
    expectThrows(empty);
    expectUnchanged();
  }

  // retainAll(disjoint)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_disjointPreviouslyEmpty() {
    expectReturnsFalse(disjoint);
    expectUnchanged();
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_disjointPreviouslyEmptyUnsupported() {
    expectReturnsFalseOrThrows(disjoint);
    expectUnchanged();
  }

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_disjointPreviouslyNonEmpty() {
    expectReturnsTrue(disjoint);
    expectContents();
    expectMissing(e0(), e1(), e2());
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_disjointPreviouslyNonEmptyUnsupported() {
    expectThrows(disjoint);
    expectUnchanged();
  }

  // retainAll(superset)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  public void testRetainAll_superset() {
    expectReturnsFalse(superset);
    expectUnchanged();
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  public void testRetainAll_supersetUnsupported() {
    expectReturnsFalseOrThrows(superset);
    expectUnchanged();
  }

  // retainAll(subset)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_subset() {
    expectReturnsTrue(nonEmptyProperSubset);
    expectContents(nonEmptyProperSubset.toRetain);
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_subsetUnsupported() {
    expectThrows(nonEmptyProperSubset);
    expectUnchanged();
  }

  // retainAll(sameElements)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  public void testRetainAll_sameElements() {
    expectReturnsFalse(sameElements);
    expectUnchanged();
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  public void testRetainAll_sameElementsUnsupported() {
    expectReturnsFalseOrThrows(sameElements);
    expectUnchanged();
  }

  // retainAll(partialOverlap)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_partialOverlap() {
    expectReturnsTrue(partialOverlap);
    expectContents(e2());
  }

  @CollectionFeature.Require(absent = SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_partialOverlapUnsupported() {
    expectThrows(partialOverlap);
    expectUnchanged();
  }

  // retainAll(containsDuplicates)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(ONE)
  public void testRetainAll_containsDuplicatesSizeOne() {
    expectReturnsFalse(containsDuplicates);
    expectContents(e0());
  }

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_containsDuplicatesSizeSeveral() {
    expectReturnsTrue(containsDuplicates);
    expectContents(e0());
  }

  // retainAll(nullSingleton)

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_nullSingletonPreviouslyEmpty() {
    expectReturnsFalse(nullSingleton);
    expectUnchanged();
  }

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_nullSingletonPreviouslyNonEmpty() {
    expectReturnsTrue(nullSingleton);
    expectContents();
  }

  @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
  @CollectionSize.Require(ONE)
  public void testRetainAll_nullSingletonPreviouslySingletonWithNull() {
    initCollectionWithNullElement();
    expectReturnsFalse(nullSingleton);
    expectContents(createArrayWithNullElement());
  }

  @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testRetainAll_nullSingletonPreviouslySeveralWithNull() {
    initCollectionWithNullElement();
    expectReturnsTrue(nullSingleton);
    expectContents(nullSingleton.toRetain);
  }

  // nullSingleton.retainAll()

  @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_containsNonNullWithNull() {
    initCollectionWithNullElement();
    expectReturnsTrue(disjoint);
    expectContents();
  }

  // retainAll(null)

  /*
   * AbstractCollection fails the retainAll(null) test when the subject
   * collection is empty, but we'd still like to test retainAll(null) when we
   * can. We split the test into empty and non-empty cases. This allows us to
   * suppress only the former.
   */

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(ZERO)
  public void testRetainAll_nullCollectionReferenceEmptySubject() {
    try {
      collection.retainAll(null);
      // Returning successfully is not ideal, but tolerated.
    } catch (NullPointerException expected) {
    }
  }

  @CollectionFeature.Require(SUPPORTS_REMOVE)
  @CollectionSize.Require(absent = ZERO)
  public void testRetainAll_nullCollectionReferenceNonEmptySubject() {
    try {
      collection.retainAll(null);
      fail("retainAll(null) should throw NullPointerException");
    } catch (NullPointerException expected) {
    }
  }

  private void expectReturnsTrue(Target target) {
    String message
        = Platform.format("retainAll(%s) should return true", target);
    assertTrue(message, collection.retainAll(target.toRetain));
  }

  private void expectReturnsFalse(Target target) {
    String message
        = Platform.format("retainAll(%s) should return false", target);
    assertFalse(message, collection.retainAll(target.toRetain));
  }

  private void expectThrows(Target target) {
    try {
      collection.retainAll(target.toRetain);
      String message = Platform.format("retainAll(%s) should throw", target);
      fail(message);
    } catch (UnsupportedOperationException expected) {
    }
  }

  private void expectReturnsFalseOrThrows(Target target) {
    String message
        = Platform.format("retainAll(%s) should return false or throw", target);
    try {
      assertFalse(message, collection.retainAll(target.toRetain));
    } catch (UnsupportedOperationException tolerated) {
    }
  }
}


text:
<?php
	include_once 'template/header.php';
	if(isset($_GET)){
		$token = $_GET['token'];

		$trocaDeSenhaModel 	= new TrocaDeSenhaModel();
		$trocaDeSenhaModel->setTdsToken($token);
		$trocaDeSenhaController = new TrocaDeSenhaController();
		$tdsArray = $trocaDeSenhaController->tdsByToken($trocaDeSenhaModel);
		// print_r($tdsArray);
		// echo "
";
		// echo date("Y-m-d");
		$email = $tdsArray[0]['tdsEmail'];

		$psModel 		= new ProfissionalDeSaudeModel();
		$psModel->setPsEmail($email);
		$psController 	= new ProfissionalDeSaudeController();
		$psArray 		= $psController->psByEmail($psModel);

		if($psArray != NULL){
			foreach ($psArray as $key => $value) {
				$psId = $value['psId'];
			}
		}else{
			$psId = 0;
		}
	}

	// echo 'token: '.$token.'
'.' psid '.$psId;
?>

<?php include_once 'template/navibarPag.php'; ?>

					SENHA ALTERADA COM SUCESSO

					Clique aqui
					para entrar

NOVA SENHA

						Digite a nova senha

						<input id="senhaNova" name="senhaNova" type="password" class="form-control_cadastro input-md" data-toggle="popover" title="" data-content="" data-placement="top" required="" value="">

						Confirme a senha

						<input id="senhaConfirma" name="senhaConfirma" type="password" class="form-control_cadastro input-md" data-toggle="popover" title="" data-content="" data-placement="top" required="" value="">
						<input type="hidden" id="psId" name="psId" value="<?php echo $psId; ?>">

						<button id="btNovaSenha" name="btNovaSenha" class="btn pull-right btn-danger btn-color-cad" >SALVAR</button>

<?php
	echo '';
	include_once 'template/footer.php';
?>


text:
rem
rem Header: oe_comnt.sql 09-jan-01
rem
rem Copyright (c) 2001, 2015, Oracle Corporation.  All rights reserved.
rem
rem Permission is hereby granted, free of charge, to any person obtaining
rem a copy of this software and associated documentation files (the
rem "Software"), to deal in the Software without restriction, including
rem without limitation the rights to use, copy, modify, merge, publish,
rem distribute, sublicense, and/or sell copies of the Software, and to
rem permit persons to whom the Software is furnished to do so, subject to
rem the following conditions:
rem
rem The above copyright notice and this permission notice shall be
rem included in all copies or substantial portions of the Software.
rem
rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
rem EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
rem MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
rem NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
rem LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
rem OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
rem WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
rem
rem Owner  : ahunold
rem
rem NAME
rem   oe_comnt.sql - create comments for OE Common Schema
rem
rem DESCRIPTON
rem
rem
rem MODIFIED   (MM/DD/YY)
rem   hyeh      08/29/02 - hyeh_mv_comschema_to_rdbms
rem   ahunold   01/30/01 - OE script headers
rem   ahunold   01/24/01 - Eliminate extra lines from last merge
rem   ahunold   01/09/01 - checkin ADE

COMMENT ON TABLE oe.customers IS
'Contains customers data either entered by an employee or by the customer
him/herself over the Web.';

COMMENT ON COLUMN oe.customers.cust_address IS
'Object column of type address_typ.';

COMMENT ON COLUMN oe.customers.phone_numbers IS
'Varray column of type phone_list_typ';
.
COMMENT ON COLUMN oe.customers.cust_geo_location IS
'SDO (spatial) column.';

COMMENT ON COLUMN oe.customers.cust_first_name IS
'NOT NULL constraint.';

COMMENT ON COLUMN oe.customers.cust_last_name IS
'NOT NULL constraint.';

COMMENT ON COLUMN oe.customers.credit_limit IS
'Check constraint.';

COMMENT ON COLUMN oe.customers.customer_id IS
'Primary key column.';

COMMENT ON COLUMN oe.customers.account_mgr_id IS
'References hr.employees.employee_id.';

REM ===========================================================================

COMMENT ON TABLE oe.warehouses IS
'Warehouse data unspecific to any industry.';

COMMENT ON COLUMN oe.warehouses.wh_geo_location IS
'SDO (spatial) column.';

COMMENT ON COLUMN oe.warehouses.warehouse_id IS
'Primary key column.';

COMMENT ON COLUMN oe.warehouses.location_id IS
'Primary key column, references hr.locations.location_id.';

REM ===========================================================================

COMMENT ON TABLE oe.order_items IS
'Example of many-to-many resolution.';

COMMENT ON COLUMN oe.order_items.order_id IS
'Part of concatenated primary key, references orders.order_id.';

COMMENT ON COLUMN oe.order_items.product_id IS
'References product_information.product_id.';

COMMENT ON COLUMN oe.order_items.line_item_id IS
'Part of concatenated primary key.';

COMMENT ON COLUMN oe.orders.order_status IS
'0: Not fully entered, 1: Entered, 2: Canceled - bad credit, -
3: Canceled - by customer, 4: Shipped - whole order, -
5: Shipped - replacement items, 6: Shipped - backlog on items, -
7: Shipped - special delivery, 8: Shipped - billed, 9: Shipped - payment plan,-
10: Shipped - paid';

REM ===========================================================================

COMMENT ON TABLE oe.orders IS
'Contains orders entered by a salesperson as well as over the Web.';

COMMENT ON COLUMN oe.orders.order_date IS
'TIMESTAMP WITH LOCAL TIME ZONE column, NOT NULL constraint.';

COMMENT ON COLUMN oe.orders.order_id IS
'PRIMARY KEY column.';

COMMENT ON COLUMN oe.orders.sales_rep_id IS
'References hr.employees.employee_id.';

COMMENT ON COLUMN oe.orders.promotion_id IS
'Sales promotion ID. Used in SH schema';

COMMENT ON COLUMN oe.orders.order_mode IS
'CHECK constraint.';

COMMENT ON COLUMN oe.orders.order_total IS
'CHECK constraint.';

REM ===========================================================================

COMMENT ON TABLE oe.inventories IS
'Tracks availability of products by product_it and warehouse_id.';

COMMENT ON COLUMN oe.inventories.product_id IS
'Part of concatenated primary key, references product_information.product_id.';

COMMENT ON COLUMN oe.inventories.warehouse_id IS
'Part of concatenated primary key, references warehouses.warehouse_id.';

REM ===========================================================================

COMMENT ON TABLE oe.product_information IS
'Non-industry-specific data in various categories.';

COMMENT ON COLUMN oe.product_information.product_id IS
'Primary key column.';

COMMENT ON COLUMN oe.product_information.product_description IS
'Primary language description corresponding to translated_description in
oe.product_descriptions, added to provide non-NLS text columns for OC views
to accss.';

COMMENT ON COLUMN oe.product_information.category_id IS
'Low cardinality column, can be used for bitmap index.
Schema SH uses it as foreign key';

COMMENT ON COLUMN oe.product_information.weight_class IS
'Low cardinality column, can be used for bitmap index.';

COMMENT ON COLUMN oe.product_information.warranty_period IS
'INTERVAL YEAER TO MONTH column, low cardinality, can be used for bitmap
index.';

COMMENT ON COLUMN oe.product_information.supplier_id IS
'Offers possibility of extensions outside Common Schema.';

COMMENT ON COLUMN oe.product_information.product_status IS
'Check constraint. Appropriate for complex rules, such as "All products in
status PRODUCTION must have at least one inventory entry." Also appropriate
for a trigger auditing status change.';

REM ===========================================================================

COMMENT ON TABLE product_descriptions IS
'Non-industry-specific design, allows selection of NLS-setting-specific data
derived at runtime, for example using the products view.';

COMMENT ON COLUMN product_descriptions.product_id IS
'Primary key column.';

COMMENT ON COLUMN product_descriptions.language_id IS
'Primary key column.';

REM Description of OE views ===================================================

COMMENT ON TABLE products IS
'This view joins product_information and product_descriptions, using NLS
settings to pick the appropriate language-specific product description.';

COMMENT ON TABLE bombay_inventory IS
'This view shows inventories at the Bombay warehouse.';

COMMENT ON TABLE sydney_inventory IS
'This view shows inventories at the Sydney warehouse.';

COMMENT ON TABLE toronto_inventory IS
'This view shows inventories at the Toronto warehouse.';


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Text;

using ZD.Gui.Zen;

namespace ZD.Gui
{
    /// <summary>
    /// Represents a Windows text box control, with an opaque textual hint when it is empty.
    /// </summary>
    internal class HintedTextBox : TextBox
    {
        /// <summary>
        /// See <see cref="HintText"/>.
        /// </summary>
        private string hintText = string.Empty;

        /// <summary>
        /// The textual hint to display when the text box contains no actual text.
        /// </summary>
        public string HintText
        {
            get { return hintText; }
            set { if (value == null) hintText = string.Empty; else hintText = value; }
        }

        /// <summary>
        /// True if IME is composing (active).
        /// </summary>
        private bool imeActive = false;

        /// <summary>
        /// Ctor: inits colors to match Zen parameters.
        /// </summary>
        public HintedTextBox()
        {
            BackColor = ZenParams.WindowColor;
            ForeColor = ZenParams.StandardTextColor;
        }

        /// <summary>
        /// Windows paint event code.
        /// </summary>
        private const int WM_PAINT = 0x0f;

        /// <summary>
        /// IME composition started event.
        /// </summary>
        private const int WM_IME_STARTCOMPOSITION = 0x10d;

        /// <summary>
        /// IME composition ended event.
        /// </summary>
        private const int WM_IME_ENDCOMPOSITION = 0x10e;

        /// <summary>
        /// Intercepts (at least some) Paint events to display hint.
        /// </summary>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_IME_STARTCOMPOSITION || m.Msg == WM_IME_ENDCOMPOSITION)
            {
                imeActive = m.Msg == WM_IME_STARTCOMPOSITION;
                Invalidate();
            }
            base.WndProc(ref m);
            if (m.Msg == WM_PAINT) doPaintOver();
        }

        /// <summary>
        /// Shows or hides hint when user text changes.
        /// </summary>
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            imeActive = false;
            doPaintOver();
        }

        /// <summary>
        /// Paints hint over control's area.s
        /// </summary>
        private void doPaintOver()
        {
            if (Text != string.Empty || hintText == string.Empty || imeActive) return;
            using (Graphics g = CreateGraphics())
            {
                using (Font f = new Font(this.Font, FontStyle.Italic))
                using (Brush b = new SolidBrush(Color.FromArgb(Magic.SearchInputHintOpacity, this.ForeColor)))
                {
                    // Vertical offset for Noto. Ugly but not my fault the whole thing. Stupid fonts.
                    float top = 0;
                    if (f.Name.StartsWith("Noto"))
                    {
                        float scale = this.FindForm().CurrentAutoScaleDimensions.Height / 13.0F;
                        top = scale * 4F;
                    }
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    g.DrawString(hintText, f, b, new PointF(0, top));
                }
            }
        }
    }
}


text:
package priorities

import (
	"fmt"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/kubernetes/pkg/scheduler/algorithm"
	schedulerapi "k8s.io/kubernetes/pkg/scheduler/api"
	schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
	utilnode "k8s.io/kubernetes/pkg/util/node"

	"k8s.io/klog"
)

// When zone information is present, give 2/3 of the weighting to zone spreading, 1/3 to node spreading
// TODO: Any way to justify this weighting?
const zoneWeighting float64 = 2.0 / 3.0

// SelectorSpread contains information to calculate selector spread priority.
type SelectorSpread struct {
	serviceLister     algorithm.ServiceLister
	controllerLister  algorithm.ControllerLister
	replicaSetLister  algorithm.ReplicaSetLister
	statefulSetLister algorithm.StatefulSetLister
}

// NewSelectorSpreadPriority creates a SelectorSpread.
func NewSelectorSpreadPriority(
	serviceLister algorithm.ServiceLister,
	controllerLister algorithm.ControllerLister,
	replicaSetLister algorithm.ReplicaSetLister,
	statefulSetLister algorithm.StatefulSetLister) (PriorityMapFunction, PriorityReduceFunction) {
	selectorSpread := &SelectorSpread{
		serviceLister:     serviceLister,
		controllerLister:  controllerLister,
		replicaSetLister:  replicaSetLister,
		statefulSetLister: statefulSetLister,
	}
	return selectorSpread.CalculateSpreadPriorityMap, selectorSpread.CalculateSpreadPriorityReduce
}

// CalculateSpreadPriorityMap spreads pods across hosts, considering pods
// belonging to the same service,RC,RS or StatefulSet.
// When a pod is scheduled, it looks for services, RCs,RSs and StatefulSets that match the pod,
// then finds existing pods that match those selectors.
// It favors nodes that have fewer existing matching pods.
// i.e. it pushes the scheduler towards a node where there's the smallest number of
// pods which match the same service, RC,RSs or StatefulSets selectors as the pod being scheduled.
func (s *SelectorSpread) CalculateSpreadPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulernodeinfo.NodeInfo) (schedulerapi.HostPriority, error) {
	var selectors []labels.Selector
	node := nodeInfo.Node()
	if node == nil {
		return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
	}

	priorityMeta, ok := meta.(*priorityMetadata)
	if ok {
		selectors = priorityMeta.podSelectors
	} else {
		selectors = getSelectors(pod, s.serviceLister, s.controllerLister, s.replicaSetLister, s.statefulSetLister)
	}

	if len(selectors) == 0 {
		return schedulerapi.HostPriority{
			Host:  node.Name,
			Score: 0,
		}, nil
	}

	count := countMatchingPods(pod.Namespace, selectors, nodeInfo)

	return schedulerapi.HostPriority{
		Host:  node.Name,
		Score: int64(count),
	}, nil
}

// CalculateSpreadPriorityReduce calculates the source of each node
// based on the number of existing matching pods on the node
// where zone information is included on the nodes, it favors nodes
// in zones with fewer existing matching pods.
func (s *SelectorSpread) CalculateSpreadPriorityReduce(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo, result schedulerapi.HostPriorityList) error {
	countsByZone := make(map[string]int64, 10)
	maxCountByZone := int64(0)
	maxCountByNodeName := int64(0)

	for i := range result {
		if result[i].Score > maxCountByNodeName {
			maxCountByNodeName = result[i].Score
		}
		zoneID := utilnode.GetZoneKey(nodeNameToInfo[result[i].Host].Node())
		if zoneID == "" {
			continue
		}
		countsByZone[zoneID] += result[i].Score
	}

	for zoneID := range countsByZone {
		if countsByZone[zoneID] > maxCountByZone {
			maxCountByZone = countsByZone[zoneID]
		}
	}

	haveZones := len(countsByZone) != 0

	maxCountByNodeNameFloat64 := float64(maxCountByNodeName)
	maxCountByZoneFloat64 := float64(maxCountByZone)
	MaxPriorityFloat64 := float64(schedulerapi.MaxPriority)

	for i := range result {
		// initializing to the default/max node score of maxPriority
		fScore := MaxPriorityFloat64
		if maxCountByNodeName > 0 {
			fScore = MaxPriorityFloat64 * (float64(maxCountByNodeName-result[i].Score) / maxCountByNodeNameFloat64)
		}
		// If there is zone information present, incorporate it
		if haveZones {
			zoneID := utilnode.GetZoneKey(nodeNameToInfo[result[i].Host].Node())
			if zoneID != "" {
				zoneScore := MaxPriorityFloat64
				if maxCountByZone > 0 {
					zoneScore = MaxPriorityFloat64 * (float64(maxCountByZone-countsByZone[zoneID]) / maxCountByZoneFloat64)
				}
				fScore = (fScore * (1.0 - zoneWeighting)) + (zoneWeighting * zoneScore)
			}
		}
		result[i].Score = int64(fScore)
		if klog.V(10) {
			klog.Infof(
				"%v -> %v: SelectorSpreadPriority, Score: (%d)", pod.Name, result[i].Host, int64(fScore),
			)
		}
	}
	return nil
}

// ServiceAntiAffinity contains information to calculate service anti-affinity priority.
type ServiceAntiAffinity struct {
	podLister     algorithm.PodLister
	serviceLister algorithm.ServiceLister
	label         string
}

// NewServiceAntiAffinityPriority creates a ServiceAntiAffinity.
func NewServiceAntiAffinityPriority(podLister algorithm.PodLister, serviceLister algorithm.ServiceLister, label string) (PriorityMapFunction, PriorityReduceFunction) {
	antiAffinity := &ServiceAntiAffinity{
		podLister:     podLister,
		serviceLister: serviceLister,
		label:         label,
	}
	return antiAffinity.CalculateAntiAffinityPriorityMap, antiAffinity.CalculateAntiAffinityPriorityReduce
}

// Classifies nodes into ones with labels and without labels.
func (s *ServiceAntiAffinity) getNodeClassificationByLabels(nodes []*v1.Node) (map[string]string, []string) {
	labeledNodes := map[string]string{}
	nonLabeledNodes := []string{}
	for _, node := range nodes {
		if labels.Set(node.Labels).Has(s.label) {
			label := labels.Set(node.Labels).Get(s.label)
			labeledNodes[node.Name] = label
		} else {
			nonLabeledNodes = append(nonLabeledNodes, node.Name)
		}
	}
	return labeledNodes, nonLabeledNodes
}

// countMatchingPods cout pods based on namespace and matching all selectors
func countMatchingPods(namespace string, selectors []labels.Selector, nodeInfo *schedulernodeinfo.NodeInfo) int {
	if nodeInfo.Pods() == nil || len(nodeInfo.Pods()) == 0 || len(selectors) == 0 {
		return 0
	}
	count := 0
	for _, pod := range nodeInfo.Pods() {
		// Ignore pods being deleted for spreading purposes
		// Similar to how it is done for SelectorSpreadPriority
		if namespace == pod.Namespace && pod.DeletionTimestamp == nil {
			matches := true
			for _, selector := range selectors {
				if !selector.Matches(labels.Set(pod.Labels)) {
					matches = false
					break
				}
			}
			if matches {
				count++
			}
		}
	}
	return count
}

// CalculateAntiAffinityPriorityMap spreads pods by minimizing the number of pods belonging to the same service
// on given machine
func (s *ServiceAntiAffinity) CalculateAntiAffinityPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulernodeinfo.NodeInfo) (schedulerapi.HostPriority, error) {
	var firstServiceSelector labels.Selector

	node := nodeInfo.Node()
	if node == nil {
		return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
	}
	priorityMeta, ok := meta.(*priorityMetadata)
	if ok {
		firstServiceSelector = priorityMeta.podFirstServiceSelector
	} else {
		firstServiceSelector = getFirstServiceSelector(pod, s.serviceLister)
	}
	//pods matched namespace,selector on current node
	var selectors []labels.Selector
	if firstServiceSelector != nil {
		selectors = append(selectors, firstServiceSelector)
	}
	score := countMatchingPods(pod.Namespace, selectors, nodeInfo)

	return schedulerapi.HostPriority{
		Host:  node.Name,
		Score: int64(score),
	}, nil
}

// CalculateAntiAffinityPriorityReduce computes each node score with the same value for a particular label.
// The label to be considered is provided to the struct (ServiceAntiAffinity).
func (s *ServiceAntiAffinity) CalculateAntiAffinityPriorityReduce(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo, result schedulerapi.HostPriorityList) error {
	var numServicePods int64
	var label string
	podCounts := map[string]int64{}
	labelNodesStatus := map[string]string{}
	maxPriorityFloat64 := float64(schedulerapi.MaxPriority)

	for _, hostPriority := range result {
		numServicePods += hostPriority.Score
		if !labels.Set(nodeNameToInfo[hostPriority.Host].Node().Labels).Has(s.label) {
			continue
		}
		label = labels.Set(nodeNameToInfo[hostPriority.Host].Node().Labels).Get(s.label)
		labelNodesStatus[hostPriority.Host] = label
		podCounts[label] += hostPriority.Score
	}

	//score int - scale of 0-maxPriority
	// 0 being the lowest priority and maxPriority being the highest
	for i, hostPriority := range result {
		label, ok := labelNodesStatus[hostPriority.Host]
		if !ok {
			result[i].Host = hostPriority.Host
			result[i].Score = 0
			continue
		}
		// initializing to the default/max node score of maxPriority
		fScore := maxPriorityFloat64
		if numServicePods > 0 {
			fScore = maxPriorityFloat64 * (float64(numServicePods-podCounts[label]) / float64(numServicePods))
		}
		result[i].Host = hostPriority.Host
		result[i].Score = int64(fScore)
	}

	return nil
}


text:
<!doctype html>

    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Comeback!</title>

        Comeback!

        <button class="optionButton">
           Later today
          [Tonight, 6:00 PM]
        </button>

        <button class="optionButton">
           Tomorrow
          [Tomorrow, 8:00 AM]
        </button>

        <button class="optionButton">
           This weekend
          [Saturday, 8:00 AM]
        </button>

        <button class="optionButton">
           Next week
          [Monday, 8:00 AM]
        </button>

        <button class="optionButton">
           Someday
          [Who can say?]
        </button>

        <button class="optionButton">
           Pick date & time

        </button>


text:
<!doctype html>

		<title>Dragging text from UI widgets to themselves</title>

Select all text in the address bar.

Drag the selection around a little, and release it over the address bar again.

Try to select the text in this sentence.

Pass if:

A visible representation of the selected text appears to be dragged.

The mouse cursor shows that the drop will be allowed over the address bar.

The text on this page can be selected afterwards.

Repeat the test with other UI text inputs as drag source/destination.


text:
require File.expand_path('../../lib/video_embed.rb', __FILE__)

describe VideoEmbed do
  describe 'YouTube' do
    it 'returns embed html from a url' do
      video_embed = VideoEmbed.embed('http://www.youtube.com/watch?v=4Z3r9X8OahA&feature=fvwp&NR=1')
      video_embed.should eql(%Q{})
    end

    it 'returns embed html from a short url' do
      video_embed = VideoEmbed.embed('http://youtu.be/4Z3r9X8OahA')
      video_embed.should include('http://www.youtube.com/embed/4Z3r9X8OahA?rel=0')
    end

    it 'accepts a custom width' do
      video_embed = VideoEmbed.embed('http://www.youtube.com/watch?v=NtgtMQwr3Ko', :width => 1280)
      video_embed.should match(/width="1280"/)
    end

    it 'accepts a custom height' do
      video_embed = VideoEmbed.embed('http://www.youtube.com/watch?v=NtgtMQwr3Ko', :height => 720)
      video_embed.should match(/height="720"/)
    end
  end

  describe 'Vimeo' do
    it 'returns embed html from a url' do
      video_embed = VideoEmbed.embed('http://vimeo.com/11040425')
      video_embed.should eql(%Q{})
    end

    it 'returns embed html from a mobile url' do
      video_embed = VideoEmbed.embed('http://vimeo.com/m/11040425')
      video_embed.should include('http://player.vimeo.com/video/11040425?title=0&byline=0&portrait=0')
    end

    it 'returns embed html from an album url' do
      video_embed = VideoEmbed.embed('http://vimeo.com/album/2590693/video/78279754')
      video_embed.should include('http://player.vimeo.com/video/78279754?title=0&byline=0&portrait=0')
    end

    it 'accepts a custom width' do
      video_embed = VideoEmbed.embed('http://vimeo.com/11040425', :width => 720)
      video_embed.should match(/width="720"/)
    end

    it 'accepts a custom height' do
      video_embed = VideoEmbed.embed('http://vimeo.com/11040425', :height => 480)
      video_embed.should match(/height="480"/)
    end
  end

  describe 'Fallback' do
    it 'returns an empty string when not a supported service' do
      video_embed = VideoEmbed.embed('http://example.com/')
      video_embed.should eql(%Q{
Video embed not available.
})
    end
  end
end


text:
.. _enum:

============
Enum classes
============

.. module:: enumchoicefield.enum

.. class:: PrettyEnum

    A :class:`PrettyEnum` makes defining nice, human-readable names
    for enum members easy.
    To use it, subclass :class:`PrettyEnum` and
    declare the enum members with their human-readable name as their value:

    .. code-block:: python

        class Fruit(PrettyEnum):
            apple = "Apple"
            banana = "Banana"
            orange = "Orange"

    The members' values will be automatically set to ascending integers,
    starting at one.
    In the example above,
    ``Fruit.apple.value`` is ``1``, and
    ``Fruit.orange.value`` is ``3``.

.. class:: DeconstructableEnum

    .. py:method:: deconstruct()

        a :class:`DeconstructableEnum` defines :meth:`deconstruct`,
        compatible with Django migrations.
        If you want to set a default for an
        :class:`~enumchoicefield.fields.EnumChoiceField`,
        the enum must be deconstructable.

.. class:: ChoiceEnum

    a :class:`ChoiceEnum` extends both
    :class:`PrettyEnum` and :class:`DeconstructableEnum`.
    It is recommended to use a :class:`ChoiceEnum` subclass with
    :class:`~enumchoicefield.fields.EnumChoiceField`,
    but this is not required.


text:
@interface SectionedMenu : NSMenu

#pragma mark - Sections

- (void)insertSectionWithTag:(NSInteger)tag atIndex:(NSUInteger)index;
- (void)removeSectionWithTag:(NSInteger)tag;

#pragma mark - Section items

- (void)insertItem:(NSMenuItem *)item
           atIndex:(NSUInteger)index
  inSectionWithTag:(NSInteger)sectionTag;

- (NSMenuItem *)itemWithTag:(NSInteger)tag
           inSectionWithTag:(NSInteger)sectionTag;

- (void)removeItemWithTag:(NSInteger)tag
         inSectionWithTag:(NSInteger)sectionTag;
@end


text:
test_description='git p4 preserve users'

. ./lib-git-p4.sh

test_expect_success 'start p4d' '
	start_p4d
'

test_expect_success 'create files' '
	(
		cd "$cli" &&
		p4 client -o | sed "/LineEnd/s/:.*/:unix/" | p4 client -i &&
		echo file1 >file1 &&
		echo file2 >file2 &&
		p4 add file1 file2 &&
		p4 submit -d "add files"
	)
'

p4_grant_admin() {
	name=$1 &&
	{
		p4 protect -o &&
		echo "    admin user $name * //depot/..."
	} | p4 protect -i
}

p4_check_commit_author() {
	file=$1 user=$2 &&
	p4 changes -m 1 //depot/$file | grep -q $user
}

make_change_by_user() {
	file=$1 name=$2 email=$3 &&
	echo "username: a change by $name" >>"$file" &&
	git add "$file" &&
	git commit --author "$name <$email>" -m "a change by $name"
}

# Test username support, submitting as user 'alice'
test_expect_success 'preserve users' '
	p4_add_user alice &&
	p4_add_user bob &&
	p4_grant_admin alice &&
	git p4 clone --dest="$git" //depot &&
	test_when_finished cleanup_git &&
	(
		cd "$git" &&
		echo "username: a change by alice" >>file1 &&
		echo "username: a change by bob" >>file2 &&
		git commit --author "Alice <alice@example.com>" -m "a change by alice" file1 &&
		git commit --author "Bob <bob@example.com>" -m "a change by bob" file2 &&
		git config git-p4.skipSubmitEditCheck true &&
		P4EDITOR="test-chmtime +5" P4USER=alice P4PASSWD=secret &&
		export P4EDITOR P4USER P4PASSWD &&
		git p4 commit --preserve-user &&
		p4_check_commit_author file1 alice &&
		p4_check_commit_author file2 bob
	)
'

# Test username support, submitting as bob, who lacks admin rights. Should
# not submit change to p4 (git diff should show deltas).
test_expect_success 'refuse to preserve users without perms' '
	git p4 clone --dest="$git" //depot &&
	test_when_finished cleanup_git &&
	(
		cd "$git" &&
		git config git-p4.skipSubmitEditCheck true &&
		echo "username-noperms: a change by alice" >>file1 &&
		git commit --author "Alice <alice@example.com>" -m "perms: a change by alice" file1 &&
		P4EDITOR="test-chmtime +5" P4USER=bob P4PASSWD=secret &&
		export P4EDITOR P4USER P4PASSWD &&
		test_must_fail git p4 commit --preserve-user &&
		! git diff --exit-code HEAD..p4/master
	)
'

# What happens with unknown author? Without allowMissingP4Users it should fail.
test_expect_success 'preserve user where author is unknown to p4' '
	git p4 clone --dest="$git" //depot &&
	test_when_finished cleanup_git &&
	(
		cd "$git" &&
		git config git-p4.skipSubmitEditCheck true &&
		echo "username-bob: a change by bob" >>file1 &&
		git commit --author "Bob <bob@example.com>" -m "preserve: a change by bob" file1 &&
		echo "username-unknown: a change by charlie" >>file1 &&
		git commit --author "Charlie <charlie@example.com>" -m "preserve: a change by charlie" file1 &&
		P4EDITOR="test-chmtime +5" P4USER=alice P4PASSWD=secret &&
		export P4EDITOR P4USER P4PASSWD &&
		test_must_fail git p4 commit --preserve-user &&
		! git diff --exit-code HEAD..p4/master &&

		echo "$0: repeat with allowMissingP4Users enabled" &&
		git config git-p4.allowMissingP4Users true &&
		git config git-p4.preserveUser true &&
		git p4 commit &&
		git diff --exit-code HEAD..p4/master &&
		p4_check_commit_author file1 alice
	)
'

# If we're *not* using --preserve-user, git-p4 should warn if we're submitting
# changes that are not all ours.
# Test: user in p4 and user unknown to p4.
# Test: warning disabled and user is the same.
test_expect_success 'not preserving user with mixed authorship' '
	git p4 clone --dest="$git" //depot &&
	test_when_finished cleanup_git &&
	(
		cd "$git" &&
		git config git-p4.skipSubmitEditCheck true &&
		p4_add_user derek &&

		make_change_by_user usernamefile3 Derek derek@example.com &&
		P4EDITOR=cat P4USER=alice P4PASSWD=secret &&
		export P4EDITOR P4USER P4PASSWD &&
		git p4 commit |\
		grep "git author derek@example.com does not match" &&

		make_change_by_user usernamefile3 Charlie charlie@example.com &&
		git p4 commit |\
		grep "git author charlie@example.com does not match" &&

		make_change_by_user usernamefile3 alice alice@example.com &&
		git p4 commit |\
		test_must_fail grep "git author.*does not match" &&

		git config git-p4.skipUserNameCheck true &&
		make_change_by_user usernamefile3 Charlie charlie@example.com &&
		git p4 commit |\
		test_must_fail grep "git author.*does not match" &&

		p4_check_commit_author usernamefile3 alice
	)
'

test_expect_success 'kill p4d' '
	kill_p4d
'

test_done