text:
import notmuch
import BeautifulSoup
import datetime
import dateutil.parser
import emailparser
import logging
from tzlocal import get_localzone
import sys
import os

logging.basicConfig(filename='emailparser.log',level=logging.DEBUG)
logFormatter = logging.Formatter("[%(name)s %(levelname)s]: %(message)s")
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
consoleHandler.setLevel(logging.WARN)
logging.getLogger().addHandler(consoleHandler)

if len(sys.argv) < 3:
	sys.stderr.write("""SYNOPSIS: %(exe)s <query>

database: absolute path to notmuch database
query: query to use. Has to be in quotes.

Example usage:
%(exe)s 'schema.org/FlightReservation OR ticket OR flight OR flug OR viaje OR booking OR confirmation OR confirmacion'

To speed up date parsing, you can specify the languages to consider with the
LANGUAGES environment variable:
LANGUAGES="en de es" <cmd>

Author: Johannes Buchner (c) 2017
""" % dict(exe=sys.argv[0]))
	sys.exit(1)
db = notmuch.Database()
query = sys.argv[1]
query = db.create_query(query)
#'schema.org/FlightReservation OR ticket OR flight OR flug OR viaje OR booking OR confirmation OR confirmacion')
languages = os.environ.get('LANGUAGES', None)
if languages is not None:
	languages = languages.split()
#query = db.create_query('schema.org/FlightReservation OR eticket OR flight')
#languages = ['en']
#query = db.create_query('schema.org/FlightReservation')

all_reservations = emailparser.parse_multiple_email_messages(query.search_messages(), languages=languages)
#all_reservations = []
#messages = list(query.search_messages())
#for i, m in enumerate(messages[::-1]):
#	print('handling %d/%d: "%s" from %s' % (i, len(messages), m.get_header('Subject'),
#		datetime.datetime.fromtimestamp(m.get_date()).strftime('%Y-%m-%d')))
#	reservations = emailparser.parse_email_message(m, languages = languages)
#	print('got %d reservations' % len(all_reservations))
#	all_reservations += reservations
print('got %d reservations' % len(all_reservations))

def prepend(info, k, prefix):
	if info[k] and info[k] != '':
		info[k] = prefix + info[k]

def dateConverter(day):
	#day = dateutil.parser.parse(dateText)
	if day.tzinfo is not None:
		return day
	print 'Warning: Using local time zone to order %s' % day
	local_tz = get_localzone()
	return day.replace(tzinfo=local_tz)

# sort by departure time
all_reservations.sort(key=lambda info: dateConverter(info['departureTime']))

previous = None
fout = open('summary.html', 'w')
fout.write("""<!doctype html>

<meta charset=utf-8>
<title>Flight summary</title>
<link rel="stylesheet" type="text/css" href="theme.css">

Flights

""")

file_id = 1
for info in all_reservations:
	prepend(info, 'departureGate', 'Gate ')
	prepend(info, 'arrivalGate', 'Gate ')
	prepend(info, 'arrivalTerminal', 'Terminal ')
	prepend(info, 'departureTerminal', 'Terminal ')
	prepend(info, 'ticketNumber', 'Ticket#')
	prepend(info, 'operator', ' operated by ')
	flightday = info['departureTime'].date()
	prepend(info, 'boardingTimestr', 'Boarding ')

	filenames = []
	msg_id = info['emailId']
	for m in db.create_query('id:%s' % msg_id).search_messages():
		for mp in m.get_message_parts():
			if mp.get_content_type() == 'application/pdf' or (mp.get_content_type() == 'application/octet-stream' and mp.get_filename().lower().endswith('.pdf')):
				filename = 'file_id%d.pdf' % file_id
				with open(filename, 'w') as f:
					f.write(mp.get_payload(decode=True))
				filenames.append((mp.get_filename(), filename))
				file_id += 1
	info['pdffiles'] = ' | '.join(['%s' % (filename, origfilename) for (origfilename, filename) in filenames])

	if previous is not None and (flightday - previous).days > 14:
		delta = (flightday - previous).days
		print '=============', delta, 'days later'
		fout.write("""

%d days later

		""" % delta)
	else:
		fout.write("""

		""")
	previous = flightday
	info['departureDay'] = flightday.strftime('%Y-%m-%d')
	info['departureJustTime'] = info['departureTime'].strftime('%H:%M')
	info['emailday'] = info['emailTime'].date().strftime('%Y-%m-%d')

	print """
%(departureDay)s Flight %(departure)s --> %(arrival)s

Departing %(departureTimestr)s %(boardingTime)s
from %(departure)s %(departureTerminal)s %(departureGate)s
arriving %(arrivalTimestr)s
To   %(arrival)s %(arrivalTerminal)s %(arrivalGate)s
Flight number %(flightNumber)s with %(airline)s%(operator)s
%(ticketNumber)s %(ticketText)s %(ticketDownload)s %(ticketPrint)s

Email %(emailday)s "%(emailSubject)s"

""" % info
	fout.write(("""

From

%(departure)s
%(departureTerminal)s
%(departureGate)s
✈

Destination

%(arrival)s
%(arrivalTerminal)s
%(arrivalGate)s

Depart

%(departureJustTime)s

Date

%(departureDay)s

Arriving

%(arrivalTimestr)s

Flight number

Flight number %(flightNumber)s with %(airline)s%(operator)s

Ticket

%(ticketNumber)s %(ticketText)s %(ticketDownload)s %(ticketPrint)s

%(boardingTime)s

%(pdffiles)s

Email

%(emailday)s "%(emailSubject)s"

	""" % info).encode('utf-8'))


text:
<?php

namespace sndsgd;

/**
 * A subclass of the php Memcached extension
 *
 * This class is included as an example of how the php
 * [memcached extension](http://php.net/manual/en/book.memcached.php) can
 * be included in any project
 */
class Memcached extends \Memcached
{
   public function __construct($persistentId = '-')
   {
      parent::__construct($persistentId);
      $serverList = $this->getServerList();
      if (empty($serverList)) {
         $this->setOption(\Memcached::OPT_PREFIX_KEY, 'sndsgd-');
         $this->setOption(\Memcached::OPT_RECV_TIMEOUT, 1000);
         $this->setOption(\Memcached::OPT_SEND_TIMEOUT, 1000);
         $this->setOption(\Memcached::OPT_TCP_NODELAY, true);
         $this->setOption(\Memcached::OPT_SERVER_FAILURE_LIMIT, 50);
         $this->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 500);
         $this->setOption(\Memcached::OPT_RETRY_TIMEOUT, 300);
         $this->setOption(\Memcached::OPT_REMOVE_FAILED_SERVERS, true);
         $this->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
         $this->addServer('127.0.0.1', 11211, 1);
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace App\Service;

use Mandragora\Model\AbstractModel;
use Mandragora\Service\Crud\Doctrine\DoctrineCrud;

class Resource extends DoctrineCrud
{
    /**
     * @return void
     */
    public function init()
    {
        $this->openConnection();
        $this->decorateGateway();
    }

    /**
     * @return array
     */
    public function retrieveAllResources()
    {
        $this->init();
        return $this->getGateway()->findAll();
    }

    public function getModel(array $values = null): ?AbstractModel
    {
        return null;
    }
}


text:
<!DOCTYPE html>
<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#propdef-column-count">
<link rel="match" href="table-cell-as-multicol-ref.html">

You should see the word 'PASS' below.

P

    A

    S

    S


text:
export default function replacePageCss ({ css }) {
  console.log('debug: replacePageCss')
  function removeStyles () {
    var styleElements = document.querySelectorAll(
      'link[rel="stylesheet"], style'
    )
    Array.prototype.forEach.call(styleElements, function (element) {
      element.parentNode.removeChild(element)
    })
  }
  function insertStyles (styles) {
    var styleTag = document.createElement('style')
    styleTag.type = 'text/css'
    // inject defaultWhiteBg to match before-render
    styles = 'body { background: #fff }' + styles
    // if unreachable font-face src url in styles, phantomjs seems to crash here on Ubuntu :/
    styleTag.appendChild(document.createTextNode(styles))
    document.head.appendChild(styleTag)
  }
  removeStyles()
  console.log('debug: removed styles')
  insertStyles(css)
}


text:
#include "tensorflow/core/util/tensor_slice_reader_cache.h"

#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

namespace checkpoint {

TensorSliceReaderCacheWrapper::TensorSliceReaderCacheWrapper() {}
TensorSliceReaderCacheWrapper::~TensorSliceReaderCacheWrapper() {
  delete cache_;
  cache_ = nullptr;
}

const TensorSliceReader* TensorSliceReaderCacheWrapper::GetReader(
    const string& filepattern,
    TensorSliceReader::OpenTableFunction open_function,
    int preferred_shard) const {
  mutex_lock l(mu_);
  if (!cache_) {
    cache_ = new TensorSliceReaderCache;
  }
  return cache_->GetReader(filepattern, open_function, preferred_shard);
}

TensorSliceReaderCache::TensorSliceReaderCache() {}

TensorSliceReaderCache::~TensorSliceReaderCache() {
  for (auto pair : readers_) {
    delete pair.second.second;
  }
}

const TensorSliceReader* TensorSliceReaderCache::GetReader(
    const string& filepattern,
    TensorSliceReader::OpenTableFunction open_function, int preferred_shard) {
  mutex_lock l(mu_);

  // Get the function pointer from the open_function value.
  TensorSliceReaderCache::OpenFuncType* func_ptr =
      open_function.target<TensorSliceReaderCache::OpenFuncType>();
  if (!func_ptr) {
    // We could not get the pointer, no caching is possible.
    LOG(WARNING) << "Caching disabled because the open function is a lambda.";
    return nullptr;
  }

  // Wait if another thread is already trying to open the same files.
  while (still_opening_.find(filepattern) != still_opening_.end()) {
    cv_.wait(l);
  }

  TensorSliceReader* reader = nullptr;
  if (readers_.find(filepattern) == readers_.end()) {
    VLOG(1) << "Creating new TensorSliceReader for " << filepattern;
    still_opening_.insert(filepattern);
    // Release the lock temporary as constructing TensorSliceReader is
    // expensive.
    mu_.unlock();
    TensorSliceReader* tmp_reader(
        new TensorSliceReader(filepattern, open_function, preferred_shard));
    // Acquire the lock again.
    mu_.lock();
    if (tmp_reader->status().ok()) {
      reader = tmp_reader;
      readers_[filepattern] = make_pair(*func_ptr, reader);
    } else {
      delete tmp_reader;
    }
    CHECK_EQ(1, still_opening_.erase(filepattern));
    VLOG(1) << "Cached TensorSliceReader for " << filepattern << ": " << reader;
  } else {
    auto cached_val = readers_[filepattern];
    if (cached_val.first == *func_ptr) {
      reader = cached_val.second;
      VLOG(1) << "Using cached TensorSliceReader for " << filepattern << ": "
              << reader;
    } else {
      LOG(WARNING) << "Caching disabled because the checkpoint file "
                   << "is being opened with two different open functions: "
                   << filepattern;
    }
  }

  cv_.notify_all();
  return reader;
}

}  // namespace checkpoint

}  // namespace tensorflow


text:
Regression - PCBC_251_oo

--SKIPIF--
<?php
include dirname(__FILE__)."/../../cbtestframework/cbtest-phpt-loader.inc";
couchbase_phpt_skipif("Regression", "testPCBC_251_oo");

--FILE--
<?php
include dirname(__FILE__)."/../../cbtestframework/cbtest-phpt-loader.inc";
couchbase_phpt_runtest("Regression", "testPCBC_251_oo");
--EXPECT--
PHP_COUCHBASE_OK


text:
<?php
class Loader {
	/// <summary>
  /// smoothly import classes by php include function
  /// </summary>
  /// <param name="filePath">the class file path, which exploded by ".". </param>
  /// <param name="key">the classes' base folder. default: components</param>
  /// <param name="include_once">if true then use include_once function, else use include function. default: true</param>
  /// <param name="base">the base folder's path</param>
	public static function import ( $filePath, $key = '', $include_once = true, $base = null ) {
		$path = Loader::get_path ($filePath, $key, $base);
		if (!$path) return;
		if ($include_once) { include_once ( $path ); }
		else { include ( $path ); }
	}
	/// <summary>
  /// smoothly import classes by php require function
  /// </summary>
  /// <param name="filePath">the class file path, which exploded by ".". </param>
  /// <param name="key">the classes' base folder. default: components</param>
  /// <param name="include_once">if true then use require_once function, else use require function. default: true</param>
  /// <param name="base">the base folder's path</param>
	public static function embed ( $filePath, $key = '', $require_once = true, $base = null ) {
		$path = Loader::get_path ($filePath, $key, $base);
		if (!$path) return;
		if ($require_once) { require_once ( $path ); }
		else { require ( $path ); }
	}

	/// <summary>
  /// smoothly get class file path
  /// </summary>
  /// <param name="filePath">the class file path, which exploded by ".". </param>
  /// <param name="key">the classes' base folder. default: components</param>
  /// <param name="base">the base folder's path</param>
	public static function get_path( $filePath, $key, $base )	{

		//check duplicate classes
		$parts = explode( '.', $filePath );
		$classname = array_pop( $parts );
		if (class_exists($classname)) {
			//die('The class CANNOT be imported for duplicate classes. ClassName: ' . $classname);
			return;
		}

		//rebuild base and key
		if (!$base) {
			$base = dirname(dirname( __FILE__ ));
			if (!$key) { $key = str_replace( $base . DIRECTORY_SEPARATOR, '', dirname( __FILE__ ) ); }
		}

		//get import path and check file exist
		$path = $base . DIRECTORY_SEPARATOR . $key . DIRECTORY_SEPARATOR . str_replace( '.', DIRECTORY_SEPARATOR, $filePath ) . ".php";
		if (!file_exists($path)) {
			die('The function CANNOT be imported for 1.symlinks pointing to non-existing files, 2.inaccessible due to safe mode restrictions. Path: ' . $path);
		}
		return $path;
	}
}

// need import other function
Loader::import('TrustList', 'libraries');
Loader::import('Debug', 'libraries');
Loader::import('Config', 'libraries');
if (!isset($NoGoogleJQuery) || !$NoGoogleJQuery) { Loader::import('GoogleJQuery', 'libraries'); }
if (strcasecmp(Config::Read('ConnectLog'), "On") == 0) {
	Loader::import('ConnectLog', 'libraries');
}
Debug::php_execute_complete(sprintf("%s", __FILE__), "LINE:" . __LINE__);
?>


text:
<?php

##|+PRIV
##|*IDENT=page-system-usermanager-addprivs
##|*NAME=System: User Manager: Add Privileges
##|*DESCR=Allow access to the 'System: User Manager: Add Privileges' page.
##|*WARN=standard-warning-root
##|*MATCH=system_usermanager_addprivs.php*
##|-PRIV

require_once("guiconfig.inc");
require_once("pfsense-utils.inc");

if (isset($_REQUEST['userid']) && is_numericint($_REQUEST['userid'])) {
	$userid = $_REQUEST['userid'];
}

$pgtitle = array(gettext("System"), gettext("User Manager"), gettext("Users"), gettext("Edit"), gettext("Add Privileges"));
$pglinks = array("", "system_usermanager.php", "system_usermanager.php", "system_usermanager.php?act=edit&userid=" . $userid, "@self");

if (!isset($config['system']['user'][$userid]) && !is_array($config['system']['user'][$userid])) {
	pfSenseHeader("system_usermanager.php");
	exit;
}

$a_user = & $config['system']['user'][$userid];

if (!is_array($a_user['priv'])) {
	$a_user['priv'] = array();
}

// Make a local copy and sort it
$spriv_list = $priv_list;
uasort($spriv_list, "compare_by_name");

if ($_POST['save']) {
	unset($input_errors);
	$pconfig = $_POST;

	/* input validation */
	$reqdfields = explode(" ", "sysprivs");
	$reqdfieldsn = array(gettext("Selected privileges"));

	do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);

	if (!$input_errors) {

		if (!is_array($pconfig['sysprivs'])) {
			$pconfig['sysprivs'] = array();
		}

		if (!count($a_user['priv'])) {
			$a_user['priv'] = $pconfig['sysprivs'];
		} else {
			$a_user['priv'] = array_merge($a_user['priv'], $pconfig['sysprivs']);
		}

		$a_user['priv'] = sort_user_privs($a_user['priv']);
		local_user_set($a_user);
		write_config();

		post_redirect("system_usermanager.php", array('act' => 'edit', 'userid' => $userid));

		exit;
	}

}

function build_priv_list() {
	global $spriv_list, $a_user;

	$list = array();

	foreach ($spriv_list as $pname => $pdata) {
		if (in_array($pname, $a_user['priv'])) {
			continue;
		}

		$list[$pname] = $pdata['name'];
	}

	return($list);
}

function get_root_priv_item_text() {
	global $priv_list;

	$priv_text = "";

	foreach ($priv_list as $pname => $pdata) {
		if (isset($pdata['warn']) && ($pdata['warn'] == 'standard-warning-root')) {
			$priv_text .= '
' . $pdata['name'];
		}
	}

	return($priv_text);
}

include("head.inc");

if ($input_errors) {
	print_input_errors($input_errors);
}

$tab_array = array();
$tab_array[] = array(gettext("Users"), true, "system_usermanager.php");
$tab_array[] = array(gettext("Groups"), false, "system_groupmanager.php");
$tab_array[] = array(gettext("Settings"), false, "system_usermanager_settings.php");
$tab_array[] = array(gettext("Authentication Servers"), false, "system_authservers.php");
display_top_tabs($tab_array);

$form = new Form();

$section = new Form_Section('User Privileges');

$name_string = $a_user['name'];
if (!empty($a_user['descr'])) {
	$name_string .= " ({$a_user['descr']})";
}

$section->addInput(new Form_StaticText(
	'User',
	$name_string
));

$section->addInput(new Form_Select(
	'sysprivs',
	'*Assigned privileges',
	null,
	build_priv_list(),
	true
))->addClass('multiselect')
  ->setHelp('Hold down CTRL (PC)/COMMAND (Mac) key to select multiple items.');

$section->addInput(new Form_Select(
	'shadow',
	'Shadow',
	null,
	build_priv_list(),
	true
))->addClass('shadowselect')
  ->setHelp('Hold down CTRL (PC)/COMMAND (Mac) key to select multiple items.');

$section->addInput(new Form_Input(
	'filtertxt',
	'Filter',
	'text',
	null
))->setHelp('Show only the choices containing this term');

$section->addInput(new Form_StaticText(
	gettext('Privilege information'),
	''.
	gettext('The following privileges effectively give the user administrator-level access ' .
		' because the user gains access to execute general commands, edit system files, ' .
		' modify users, change passwords or similar:') .
	'
' .
	get_root_priv_item_text() .
	'

' .
	gettext('Please take care when granting these privileges.') .
	''
));

$btnfilter = new Form_Button(
	'btnfilter',
	'Filter',
	null,
	'fa-filter'
);

$btnfilter->setAttribute('type','button')->addClass('btn btn-info');

$form->addGlobal($btnfilter);

$btnclear = new Form_Button(
	'btnclear',
	'Clear',
	null,
	'fa-times'
);

$btnclear->setAttribute('type','button')->addClass('btn btn-warning');

$form->addGlobal($btnclear);

if (isset($userid)) {
	$section->addInput(new Form_Input(
	'userid',
	null,
	'hidden',
	$userid
	));
}

$form->add($section);

print($form);
?>

<?=gettext("Select a privilege from the list above for a description")?>

<?php include("foot.inc");


text:
package com.google.doclava;

import com.google.clearsilver.jsilver.data.Data;

public class SeeTagInfo extends TagInfo {
  private ContainerInfo mBase;
  LinkReference mLink;

  SeeTagInfo(String name, String kind, String text, ContainerInfo base, SourcePositionInfo position) {
    super(name, kind, text, position);
    mBase = base;
  }

  protected LinkReference linkReference() {
    if (mLink == null) {
      mLink =
          LinkReference.parse(text(), mBase, position(), (!"@see".equals(name()))
              && (mBase != null ? mBase.checkLevel() : true));
    }
    return mLink;
  }

  public String label() {
    return linkReference().label;
  }

  @Override
  public void makeHDF(Data data, String base) {
    LinkReference linkRef = linkReference();
    if (linkRef.kind != null) {
      // if they have a better suggestion about "kind" use that.
      // do this before super.makeHDF() so it picks it up
      setKind(linkRef.kind);
    }

    super.makeHDF(data, base);

    data.setValue(base + ".label", linkRef.label);
    if (linkRef.href != null) {
      data.setValue(base + ".href", linkRef.href);
    }

    if (ClearPage.toroot != null) {
      data.setValue("toroot", ClearPage.toroot);
    }

    if (linkRef.federatedSite != null) {
      data.setValue("federated", linkRef.federatedSite);
    }
  }

  public boolean checkLevel() {
    return linkReference().checkLevel();
  }

  public static void makeHDF(Data data, String base, SeeTagInfo[] tags) {
    int j = 0;
    for (SeeTagInfo tag : tags) {
      if (tag.mBase.checkLevel() && tag.checkLevel()) {
        tag.makeHDF(data, base + "." + j);
        j++;
      }
    }
  }
}


text:
<?php

namespace PlentyConnector\Components\Bundle\PlentymarketsAdapter\QueryHandler;

use Exception;
use PlentyConnector\Components\Bundle\PlentymarketsAdapter\ResponseParser\BundleResponseParserInterface;
use PlentyConnector\Components\Bundle\TransferObject\Bundle;
use PlentyConnector\Connector\ServiceBus\Query\FetchTransferObjectQuery;
use PlentyConnector\Connector\ServiceBus\Query\QueryInterface;
use PlentyConnector\Connector\ServiceBus\QueryHandler\QueryHandlerInterface;
use PlentyConnector\Connector\ServiceBus\QueryType;
use PlentyConnector\Console\OutputHandler\OutputHandlerInterface;
use PlentymarketsAdapter\PlentymarketsAdapter;
use PlentymarketsAdapter\ReadApi\Item;
use Psr\Log\LoggerInterface;

class FetchAllBundlesQueryHandler implements QueryHandlerInterface
{
    /**
     * @var Item
     */
    private $itemApi;

    /**
     * @var BundleResponseParserInterface
     */
    private $responseParser;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var OutputHandlerInterface
     */
    private $outputHandler;

    public function __construct(
        Item $itemApi,
        BundleResponseParserInterface $responseParser,
        LoggerInterface $logger,
        OutputHandlerInterface $outputHandler
    ) {
        $this->itemApi = $itemApi;
        $this->responseParser = $responseParser;
        $this->logger = $logger;
        $this->outputHandler = $outputHandler;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(QueryInterface $query)
    {
        return $query instanceof FetchTransferObjectQuery &&
            $query->getAdapterName() === PlentymarketsAdapter::NAME &&
            $query->getObjectType() === Bundle::TYPE &&
            $query->getQueryType() === QueryType::ALL;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(QueryInterface $query)
    {
        $elements = $this->itemApi->findAll();

        $this->outputHandler->startProgressBar(count($elements));

        foreach ($elements as $element) {
            try {
                $result = $this->responseParser->parse($element);
            } catch (Exception $exception) {
                $this->logger->error($exception->getMessage());

                $result = null;
            }

            if (empty($result)) {
                $result = [];
            }

            $result = array_filter($result);

            foreach ($result as $parsedElement) {
                yield $parsedElement;
            }

            $this->outputHandler->advanceProgressBar();
        }

        $this->outputHandler->finishProgressBar();
    }
}


text:
import TrackList from "./track-list.js";
import Player from "./sound/player.js";
import Filter from "./sound/filter.js";
import Fx from "./sound/fx.js";

import PlayerView from "./view/player.js";
import EffectorView from "./view/effector.js";

class App{
  constructor(el, list){
    this._el = el;
    TrackList.load(list).then(trackList => {
      console.log(trackList);
      this._trackList = trackList;

      this._online = new AudioContext();
      this._effector = new Fx(this._online);
      this.effector.connect(this.speaker);

      this._player = new Player(this._online, this.trackList);
      this.player.connect(this.effector.input);

      this._playerView = new PlayerView(this.player);
      this._effectorView = new EffectorView(this.effector);

      this.el.appendChild(this._playerView.el);
      this.el.appendChild(this._effectorView.el);
    }).catch(error => {
      console.log(error);
    });
  }
  get el(){
    return this._el;
  }
  get audioTracks(){
    return this._trackList;
  }
  get effector(){
    return this._effector;
  }
  get player(){
    return this._player;
  }
  get speaker(){
    return this._online.destination;
  }
  get trackList(){
    return this._trackList;
  }
}

NodeList.prototype.map = function(func){
  var result = [];
  for(var i = 0; i < this.length; i++){
    result.push(func(this[i]));
  }
  return result;
};

window.addEventListener("load", function(){
  var trackList =
        document.querySelector("[rel=music-list]").href;
  var app = new App(document.querySelector("[data-role=app]"), trackList);
});


text:
require 'ruble'

command t(:disable_application) do |cmd|
  cmd.output = :discard
  cmd.input = :none
  cmd.invoke do |context|
    require 'rallycap'
    cap(context, 'deploy:web:disable')
  end
end


text:
'use strict';

var helper = require('./helpers.authentication.e2e.client.Spec');

describe('deleteCampaigns', function() {
  beforeEach(function() {
    helper.loadApp('/');
  });
  it('should delete a campaign when a user confirms ok', function() {
    helper.logoutifLoggedIn();
    var signInButton = element(by.id('signIn'));
    signInButton.click();
    var myAndonation = element(by.id('myAndonation'));
    myAndonation.click();
    var titleButton = element.all(by.binding('campaign.title')).first().click();
    var titleUrl = titleButton.getAttribute('href');
    element(by.id('editBtn')).click();
    var deleteButton = element(by.id('deleteCampaignBtn'));
    deleteButton.click();
    var confirmDialog = browser.switchTo().alert();
    expect(confirmDialog.accept).toBeDefined();
    confirmDialog.accept();
    expect(element(by.tagName('table')).isPresent()).toBe(true);
    expect(element.all(by.binding('campaign.title')).first().getAttribute('href')).not.toBe(titleUrl);
    });

    it('should not delete a campaign when a user clicks cancel', function() {
    browser.sleep(1000);
    var myAndonation = element(by.id('myAndonation'));
    myAndonation.click();
    var titleButton2 = element.all(by.binding('campaign.title')).first();
    titleButton2.click();
    element(by.id('editBtn')).click();
    element(by.id('deleteCampaignBtn')).click();
    var confirmDialog = browser.switchTo().alert();
    expect(confirmDialog.dismiss).toBeDefined();
    confirmDialog.dismiss();
    expect(element(by.id('deleteCampaignBtn')).isPresent()).toBe(true);
    helper.logoutifLoggedIn();
    });
});


text:
package org.pixmob.freemobile.netstat.gae.web;

import com.google.inject.Singleton;
import com.google.inject.name.Names;
import com.google.inject.util.Providers;
import com.googlecode.objectify.ObjectifyFilter;
import org.pixmob.freemobile.netstat.gae.web.cron.CronServlet;
import org.pixmob.freemobile.netstat.gae.web.task.ResetKnownDevices;
import org.pixmob.freemobile.netstat.gae.web.task.UpdateChartsTask;
import org.pixmob.freemobile.netstat.gae.web.task.UpdateKnownDevices;
import org.pixmob.freemobile.netstat.gae.web.v1.DailyDeviceStatService;
import org.pixmob.freemobile.netstat.gae.web.v1.DeviceService;
import org.pixmob.freemobile.netstat.gae.web.v1.InfoService;
import org.pixmob.freemobile.netstat.gae.web.v1.NetworkUsageChart;

import com.google.inject.servlet.ServletModule;
import com.google.sitebricks.SitebricksModule;
import com.googlecode.objectify.cache.AsyncCacheFilter;

/**
 * Guice web configuration.
 * @author Pixmob
 */
public class WebModule extends ServletModule {
    @Override
    protected void configureServlets() {
        // Enable AppEngine statistics with AppStats.
        install(new AppStatsModule());

        // Enable AppEngine Remote API.
        install(new RemoteApiModule());

        filter("/*").through(ObjectifyFilter.class);
        // An AsyncCacheFilter is required in order to use async datastore
        // queries with Objectify.
        final AsyncCacheFilter asyncCacheFilter = new AsyncCacheFilter();
        filter("/task/*").through(asyncCacheFilter);
        filter("/1/*").through(asyncCacheFilter);
        serve("/cron/*").with(new CronServlet());

        install(new SitebricksModule() {
            @Override
            protected void configureSitebricks() {
                at("/task/update-charts").serve(UpdateChartsTask.class);
                at("/task/update-known-devices").serve(UpdateKnownDevices.class);
                at("/task/reset-known-devices").serve(ResetKnownDevices.class);
                at("/1").serve(InfoService.class);
                at("/1/device/:id").serve(DeviceService.class);
                at("/1/device/:id/daily/:date").serve(DailyDeviceStatService.class);
                at("/1/chart/network-usage").serve(NetworkUsageChart.class);
            }
        });
    }
}


text:
jQuery(function($) {

	if (!window.tinymce)
		return;

	var plugins = [ 'code', 'link' ],
		toolbar = 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | link';

	if (Keystone.wysiwyg.options.enableImages) {
		plugins.push('image');
		toolbar += ' | image';
	}

	if (Keystone.wysiwyg.options.enableCloudinaryUploads) {
		plugins.push('uploadimage');
		toolbar += (Keystone.wysiwyg.options.enableImages) ? ' uploadimage' : ' | uploadimage';
	}

	if (Keystone.wysiwyg.options.additionalButtons) {
	    var additionalButtons = Keystone.wysiwyg.options.additionalButtons.split(',');
	    for (var i=0; i<additionalButtons.length; i++) {
	        toolbar += (' | ' + additionalButtons[i]);
	    }
	}

	toolbar += ' | code';

	//init editable wysiwygs
	tinymce.init({
		selector: 'textarea.wysiwyg',
		menubar: false,
		plugins: plugins,
		toolbar: toolbar,
		skin: 'keystone',
		uploadimage_form_url: '/keystone/api/cloudinary/upload'
	});

	//init non-editable wysiwygs
	tinymce.init({
		selector: 'textarea.wysiwyg-noedit',
		mode: 'textareas',
		readonly: true,
		menubar: false,
		plugins: plugins,
		toolbar: 'code',
		statusbar: false,
		skin: 'keystone'
	});

});


text:
UC-Denver bioinformaticist [Wladimir Labeikovsky](http://hslibraryguides.ucdenver.edu/prf.php?account_id=134943) invited me to present at his Reproducible Research / Data Science lecture series some time ago, so I decided to share my method for keeping track of laboratory projects in an "electronic lab notebook." The presentation was well-received last Friday March 30, so I thought I'd summarize in a blog post here. I can't overemphasize how effective this approach has been for me personally, and how valuable I think it can be for trainees moving forward.

## The Problem:

## The Electronic Lab Notebook as "The Narrative"

## The Example Output

![placeholder_workflowr screenshot](local_wflowr_screenshot.png)

## Some Final Thoughts and Areas for Improvement


text:
Skyscrapers view Kong the Beijing Temple walk Heaven.
===

> 2017-04-30

> tags: update

![Beautiful along climb visit and.](./image0.jpg)

Backpackers Great magestic the hong the climb mountain. Of of hong at sunrise visit sunset how. Backpackers see and Range the. Visit Bangkok far mountain of. Of and at China monasteries Taj. Beijing temples Beijing The the and. Japan in backpackers of Wall visit walk. Mountain see the far behind streets Bangkok highest.

# At climb sunset backpackers can Himalayan sunrise monasteries.

![Buddhist of at highest of __the__.](./image1.jpg)

![Climb or you Tokyo bustling hong of.](./image0.jpg)

# The backpackers at of see.

The or  neon or Range. Mahal bustling see hong tradition Great. The Temple bustling and the. Of China of the behind. Bangkok or and see the. Magestic tradition Mahal in streets streets along. Tales climb Mahal the or or of.
![Backpackers Wall Beijing temples Range climb at Buddhist.](./image0.jpg)

Nepal in along the and tradition the or. Mountain can or of of along the. Wat The or see visit the Nepal. Hong of of Beijing see the Great the. And Wat Range of sunset tradition or Japan.

![Of Great Heaven visit Heaven.](./image0.jpg)
![Or Angkor China Mt.Fuji of visit sunset.](./image1.jpg)


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import datetime
import os
import pendulum
import time
import random

from sqlalchemy import event, exc, select
from sqlalchemy.types import DateTime, TypeDecorator

from airflow.utils.log.logging_mixin import LoggingMixin

log = LoggingMixin().log
utc = pendulum.timezone('UTC')

def setup_event_handlers(
        engine,
        reconnect_timeout_seconds,
        initial_backoff_seconds=0.2,
        max_backoff_seconds=120):

    @event.listens_for(engine, "engine_connect")
    def ping_connection(connection, branch):
        """
        Pessimistic SQLAlchemy disconnect handling. Ensures that each
        connection returned from the pool is properly connected to the database.

        http://docs.sqlalchemy.org/en/rel_1_1/core/pooling.html#disconnect-handling-pessimistic
        """
        if branch:
            # "branch" refers to a sub-connection of a connection,
            # we don't want to bother pinging on these.
            return

        start = time.time()
        backoff = initial_backoff_seconds

        # turn off "close with result".  This flag is only used with
        # "connectionless" execution, otherwise will be False in any case
        save_should_close_with_result = connection.should_close_with_result

        while True:
            connection.should_close_with_result = False

            try:
                connection.scalar(select([1]))
                # If we made it here then the connection appears to be healty
                break
            except exc.DBAPIError as err:
                if time.time() - start >= reconnect_timeout_seconds:
                    log.error(
                        "Failed to re-establish DB connection within %s secs: %s",
                        reconnect_timeout_seconds,
                        err)
                    raise
                if err.connection_invalidated:
                    log.warning("DB connection invalidated. Reconnecting...")

                    # Use a truncated binary exponential backoff. Also includes
                    # a jitter to prevent the thundering herd problem of
                    # simultaneous client reconnects
                    backoff += backoff * random.random()
                    time.sleep(min(backoff, max_backoff_seconds))

                    # run the same SELECT again - the connection will re-validate
                    # itself and establish a new connection.  The disconnect detection
                    # here also causes the whole connection pool to be invalidated
                    # so that all stale connections are discarded.
                    continue
                else:
                    log.error(
                        "Unknown database connection error. Not retrying: %s",
                        err)
                    raise
            finally:
                # restore "close with result"
                connection.should_close_with_result = save_should_close_with_result

    @event.listens_for(engine, "connect")
    def connect(dbapi_connection, connection_record):
        connection_record.info['pid'] = os.getpid()

    if engine.dialect.name == "sqlite":
        @event.listens_for(engine, "connect")
        def set_sqlite_pragma(dbapi_connection, connection_record):
            cursor = dbapi_connection.cursor()
            cursor.execute("PRAGMA foreign_keys=ON")
            cursor.close()

    # this ensures sanity in mysql when storing datetimes (not required for postgres)
    if engine.dialect.name == "mysql":
        @event.listens_for(engine, "connect")
        def set_mysql_timezone(dbapi_connection, connection_record):
            cursor = dbapi_connection.cursor()
            cursor.execute("SET time_zone = '+00:00'")
            cursor.close()

    @event.listens_for(engine, "checkout")
    def checkout(dbapi_connection, connection_record, connection_proxy):
        pid = os.getpid()
        if connection_record.info['pid'] != pid:
            connection_record.connection = connection_proxy.connection = None
            raise exc.DisconnectionError(
                "Connection record belongs to pid {}, "
                "attempting to check out in pid {}".format(connection_record.info['pid'], pid)
            )

class UtcDateTime(TypeDecorator):
    """
    Almost equivalent to :class:`~sqlalchemy.types.DateTime` with
    ``timezone=True`` option, but it differs from that by:
    - Never silently take naive :class:`~datetime.datetime`, instead it
      always raise :exc:`ValueError` unless time zone aware value.
    - :class:`~datetime.datetime` value's :attr:`~datetime.datetime.tzinfo`
      is always converted to UTC.
    - Unlike SQLAlchemy's built-in :class:`~sqlalchemy.types.DateTime`,
      it never return naive :class:`~datetime.datetime`, but time zone
      aware value, even with SQLite or MySQL.
    - Always returns DateTime in UTC
    """

    impl = DateTime(timezone=True)

    def process_bind_param(self, value, dialect):
        if value is not None:
            if not isinstance(value, datetime.datetime):
                raise TypeError('expected datetime.datetime, not ' +
                                repr(value))
            elif value.tzinfo is None:
                raise ValueError('naive datetime is disallowed')

            return value.astimezone(utc)

    def process_result_value(self, value, dialect):
        """
        Processes DateTimes from the DB making sure it is always
        returning UTC. Not using timezone.convert_to_utc as that
        converts to configured TIMEZONE while the DB might be
        running with some other setting. We assume UTC datetimes
        in the database.
        """
        if value is not None:
            if value.tzinfo is None:
                value = value.replace(tzinfo=utc)
            else:
                value = value.astimezone(utc)

        return value


text:
<!DOCTYPE html>

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

    <meta name="baidu-site-verification" content="5WXAH3PIF0" />

    <title>程序员面试宝典 第5版 链表 — 夏天</title>

    <link rel="stylesheet" href="/assets/vendor/primer-css/css/primer.css">
    <link rel="stylesheet" href="/assets/vendor/primer-markdown/dist/user-content.min.css">
    <link rel="stylesheet" href="/assets/vendor/octicons/octicons/octicons.css">
    <link rel="stylesheet" href="/assets/css/components/collection.css">
    <link rel="stylesheet" href="/assets/css/components/repo-card.css">
    <link rel="stylesheet" href="/assets/css/sections/repo-list.css">
    <link rel="stylesheet" href="/assets/css/sections/mini-repo-list.css">
    <link rel="stylesheet" href="/assets/css/components/boxed-group.css">

    <link rel="stylesheet" href="/assets/css/globals/common.css">
    <link rel="stylesheet" href="/assets/vendor/share.js/dist/css/share.min.css">
    <link rel="stylesheet" href="/assets/css/globals/responsive.css">
    <link rel="stylesheet" href="/assets/css/posts/index.css">

    <link rel="stylesheet" href="/assets/css/components/lightbox.min.css">
    <link rel="stylesheet" href="/assets/css/custom/custom.css">
    <link rel="stylesheet" href="/assets/css/jqcloud.min.css">

    <link rel="canonical" href="http://blog.sudoyc.com/2018/01/14/crack-interview-linkedlist/">

    <link rel="alternate" type="application/atom+xml" title="夏天" href="/feed.xml">
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <meta property="og:title" content="程序员面试宝典 第5版 链表">
    <meta name="keywords" content="刷题, Java">
    <meta name="og:keywords" content="刷题, Java">
    <meta name="description" content="程序员面试宝典 第5版本 链表习题解答笔记">
    <meta name="og:description" content="程序员面试宝典 第5版本 链表习题解答笔记">
    <meta property="og:url" content="http://blog.sudoyc.com/2018/01/14/crack-interview-linkedlist/">
    <meta property="og:site_name" content="夏天">
    <meta property="og:type" content="article">
    <meta property="og:locale" content="zh_CN" />
    <meta property="article:published_time" content="2018-01-14">

 夏天

            <button class="collapsed mobile-visible" type="button" onclick="toggleMenu();">

            </button>

                首页
                分类
                归档
                标签
                关于

    <link rel="stylesheet" href="/assets/css/mermaid/mermaid.css">
<link rel="stylesheet" href="/assets/css/mermaid/mermaid.forest.css">

程序员面试宝典 第5版 链表

              2018/01/14

              刷题

               刷题

               Java

            本文为「原创」内容,如需转载请注明出处!

            本文共 2161 字,
             需 12 分钟阅读

程序员面试宝典 第5版本 链表习题解答笔记

数据结构

/**
 * 单向链表
 */
class OneWayNode {
    Object data;
    OneWayNode next;

    public OneWayNode(Object data) {
        this.data = data;
    }
}

第 1 题 √

在不使用额外空间的情况下移除未排序链表中的重复节点

在不使用额外空间只能用时间换空间,即循环两层,外层为待比较的节点,内层为比较节点后节点的遍历

public class LinkedList {
    /**
     * 第 2.1 题,在不使用额外空间的情况下删除未排序链表的重复节点
     */
    public static void makeOnWayNodesUnique(OneWayNode header) {
        if (header == null)
            return;
        OneWayNode std = header;
        while (std != null) {
            OneWayNode runner = std;
            while (runner.next != null) {
                //找到重复节点并删除掉
                if (runner.next.data.equals(std.data)) {
                    runner.next = runner.next.next;
                } else {
                    runner = runner.next;
                }
            }
            std = std.next;
        }
    }
}

第 2 题 √

找出单向表中的倒数第 K 个节点

可以先求出表的长度,然后在顺序找 Length - K 的点

public class LinkedList {
    /**
     * 第 2.2 题,找出单向列表中的倒数第 K 个节点
     */
    public static OneWayNode findKLastNode(OneWayNode header, int k) {
        if (header == null) {
            return null;
        }
        int length = 0;
        OneWayNode cur = header;
        while (cur != null) {
            length += 1;
            cur = cur.next;
        }
        int lst = length - k;
        int count = 0;
        if (lst < 0) {
            return null;
        }
        cur = header;
        while (count != lst) {
            cur = cur.next;
            count += 1;
        }
        return cur;
    }
}

第 3 题 √

删除单向表中的某个节点,假定只能访问该节点

该方法不能删除尾节点

public class LinkedList {
    /**
     * 第 2.3 题,删除某个节点,假定只能访问该节点
     * 不能删除 Tail 节点
     */
    public static boolean deleteNode(OneWayNode delNode) {
        if (delNode == null || delNode.next == null) {
            return false;
        }
        OneWayNode next = delNode.next;
        delNode.data = next.data;
        delNode.next = next.next;
        return true;
    }
}

第 4 题

以给定值 x 为基准将链表分为两部分,小于 x 的在前,大于等于 x 的在后

对于链表的划分操作可以建立临时链表保存划分的部分

public class LinkedList {
    /**
     * 第 2.4 题,将链表分成两部分,小于 x 的和不小于 x 的,小于 x 的部分排在前面
     * 构建三条链表:1.小于 x 的部分,2.等于 x 的部分,3. 大于 x 的部分,将三个链表连接起来即可
     */
    public static OneWayNode sortNode(OneWayNode header, OneWayNode xNode) {
        OneWayNode beforeStart = null;
        OneWayNode afterStart = null;
        OneWayNode beforeEnd = null;
        OneWayNode afterEnd = null;
        OneWayNode equalsStart = null;
        OneWayNode equalsEnd = null;
        OneWayNode pointer = header;
        while (pointer != null) {
            if (isSmaller(pointer, xNode)) {
                if (beforeStart == null) {
                    beforeStart = pointer;
                } else {
                    beforeEnd.next = pointer;
                }
                beforeEnd = pointer;
            } else if (isBigger(pointer, xNode)) {
                if (afterStart == null) {
                    afterStart = pointer;
                } else {
                    afterEnd.next = pointer;
                }
                afterEnd = pointer;
            } else if (isEquals(pointer, xNode)) {
                if (equalsStart == null) {
                    equalsStart = pointer;
                } else {
                    equalsEnd.next = pointer;
                }
                equalsEnd = pointer;
            }
            pointer = pointer.next;
        }
        OneWayNode start = header;
        if (afterStart != null) {
            afterEnd.next = null;
            start = afterStart;
        }
        if (equalsStart != null) {
            equalsEnd.next = null;
            equalsEnd.next = afterStart;
            start = equalsStart;
        }
        if (beforeStart != null) {
            beforeEnd.next = null;
            beforeEnd.next = equalsStart;
            start = beforeStart;
        }
        return start;
    }

   /**
     * x 节点值小于 y 节点值
     */
    public static Boolean isSmaller(OneWayNode x, OneWayNode y) {
        int val = x.data.toString().compareTo(y.data.toString());
        return val < 0;
    }

    public static Boolean isEquals(OneWayNode x, OneWayNode y) {
        int val = x.data.toString().compareTo(y.data.toString());
        return val == 0;
    }

    public static Boolean isBigger(OneWayNode x, OneWayNode y) {
        int val = x.data.toString().compareTo(y.data.toString());
        return val > 0;
    }
}

第 5 题 √

1->2->3 代表数字 321 求这样含义的两个链表之和的链表

思考,如果用 3->2->1 代表 321 又该如何处理

public class LinkedList {
        /**
     * 第 2.5 题,1->2->3 表示数:321 求这样的两个链表相加的 和 的链表
     */
    public static OneWayNode addTwoIntNode(OneWayNode node1, OneWayNode node2) {
        if(node1 == null || node2 == null){
            return null;
        }
        int carray = 0;
        OneWayNode pointer = null;
        OneWayNode header = null;
        while (node1 != null && node2 != null) {
            Integer val1 = (Integer) node1.data;
            Integer val2 = (Integer) node2.data;
            Integer sum = val1 + val2 + carray;
            Integer ones = sum % 10;
            carray = sum / 10;
            OneWayNode sumNode = new OneWayNode(ones);
            if (pointer == null) {
                pointer = sumNode;
                header = sumNode;
            } else {
                pointer.next = sumNode;
            }
            pointer = sumNode;
            node1 = node1.next;
            node2 = node2.next;
        }
        if (carray > 0) {
            OneWayNode carryNode = new OneWayNode(carray);
            pointer.next = carryNode;
        }

        return header;

    }
}

第 6 题

给定一个环链表,实现一个算法返回环路的开头结点

法一:每移动一下 pointer 都从头 header->pointer 开始遍历寻找是否有等于 pointer.next 的节点,有则是起始节点返回

法二:使用 FastRunner/SlowerRunner 算法

public class LinkedList {
     /**
     * 第 2.6 题,若链表中存在环则输出环的起始节点
     */
    public static OneWayNode findLoopStart(OneWayNode header) {
        if (header == null) {
            return null;
        }
        OneWayNode pointer = header;
        while (pointer != null) {
            OneWayNode trave = header;
            while (trave != pointer) {
                if (trave == pointer.next) {
                    return trave;
                }
                trave = trave.next;
            }
            pointer = pointer.next;
        }
        return null;
    }

    /**
     * 第 2.6 题,方法二,采用 FastRunner/SlowerRunner 算法
     * 思想:
     * 0. FasterRunner 与 SlowerRunner 必然相遇,且相遇点距离环起始点的距离和头结点距离环起始点的距离一致
     * 思路:
     * 1. FasterRuuner 每次移动两步,SlowerRunnder 每次移动一步,非环的长度为 K
     * 2. 第 K 步的时候 SlowerRunner 进入环的起始点,则 FastRunner 处于环中 K 的位置
     * 3. 现在两则均处于环中,可以看做是 FastRunner 在追赶 SlowerRunner ,且每次两则的距离会减少 1
     * 4. SlowerRuuner 领先 FasterRunner LoopSize - K 的距离,则两则相遇的位置是离环的起始点相差 K
     * 5. 定义两指针,一个指向 Header,一个指向 相遇点,两者同时出发,则相遇点即为环的起始点
     */
    public static OneWayNode findLoopStart2(OneWayNode header) {
        if (header == null) {
            return null;
        }
        OneWayNode slower = header;
        OneWayNode faster = header;
        while (faster != null && faster.next != null) {
            faster = faster.next.next;
            slower = slower.next;
            //两者相遇了
            if (faster == slower) {
                break;
            }
            //没有环
            if (faster == null || faster.next == null) {
                return null;
            }
        }
        slower = header;
        while (slower != faster) {
            slower = slower.next;
            faster = faster.next;
        }
        return slower;
    }
}

第 7 题 √

编写一个数,检查链表是否为回文

public class LinkedList {
    /**
     * 第 2.7 题检查链表是否为回文
     * 回文:1->2->3->2->1 这样的链表
     * 将链表逆序复制在另一个链表中,然后比较是否相等
     */
    public static boolean isPalindrome(OneWayNode header) {
        OneWayNode pointer = header;
        OneWayNode reverse = null;
        while (pointer != null) {
            OneWayNode copyNode = new OneWayNode(pointer.data);
            if (reverse == null) {
                reverse = copyNode;
            } else {
                copyNode.next = reverse;
                reverse = copyNode;
            }
            pointer = pointer.next;
        }
        pointer = header;
        while (pointer != null) {
            if (pointer.data != reverse.data) {
                return false;
            }
            reverse = reverse.next;
            pointer = pointer.next;
        }
        return true;
    }
}

总结

链表分为单向链表和双向链表,本次全部采用单向链表解决问题,虽然单向链表构造简单但是在解决问题的时候却很麻烦,有如下思考思路:

定义一些临时指针指向链表,最后返回这些临时指针构造的链表

将链表数据复制到一个反向链表中,这样就可以同时获得头部和尾部指针进行操作,或者用 Stack 然后 pop 也是反向操作

FastRunner/SlowRunner 算法 寻找回路

能不用递归尽量不用,递归边界条件不是很好判断

有时候用 pointer.next 去与目标值比较,这样可以同时持有 pointer 和 pointer.next 两个指针而不用定义临时变量

          上一篇: Java 中 String、StringBuffer和StringBuilder的区别

          下一篇:深入 Java 核心

搜索

		<input     name="word"  size="30" type="text" id="search_box" placeholder="搜索">
		<button  type="button" class="btn btn-default" id="site_search_do">
			</button>

		<link rel="stylesheet" type="text/css" href="/assets/css/modules/sidebar-search.css">

文章目录

            © 2016
            ychost

            TOP

                 您是本站第
                     位访问者,本页第  次点击

                TOP

                首页

                分类

                归档

                标签

                关于

<link rel="stylesheet" href="/assets/css/globals/prism.css">


text:
import Game from "../../core/models/game";
import {Artifact} from "../../core/models/artifact";
import {Monster} from "../../core/models/monster";
import {RoomExit} from "../../core/models/room";
import {Room} from "../../core/models/room";
import {ModalQuestion} from "../../core/models/modal";
import {CommandException} from "../../core/utils/command.exception";

declare let game: Game;

export var event_handlers = {

  "start": function() {
    game.data['inner gate open'] = false;
    game.data['clone check'] = false;
    game.data['cannon uses'] = 3;
    game.data['power off'] = false;
  },

  "beforeMove": function(arg: string, current_room: Room, exit: RoomExit): boolean {
    switch (exit.room_to) {
      case -4:
      case -9:
        // main gate
        if (game.artifacts.get(34).room_id !== null || game.monsters.get(21).room_id !== null) {
          game.history.write("The clone army is blocking the gates!");
          return false;
        } else {
          exit.room_to = Math.abs(exit.room_to);
        }
        break;
      case 3:
        if (current_room.id === 2 && !game.player.hasArtifact(5)) {
          game.history.write('One of the commandos says, "Don\'t forget the dynamite. You\'ll need it."');
          return false;
        }
        if (game.artifacts.get(34).room_id === null || game.monsters.get(21).room_id === null) {
          game.effects.print(12);
          game.exit();
        }
    }
    return true;
  },

  "afterMove": function(arg: string, room_from: Room, room_to: Room) {
    // airships follow
    if (room_from.id === 3 && room_to.id === 4 && game.artifacts.get(4).room_id === 3) {
      game.artifacts.get(4).moveToRoom();
    }
    // inner gate
    if (room_from.id === 20 && room_to.id === 21 && game.artifacts.get(22).room_id === 20 && !game.data["inner gate open"]) {
      game.data["inner gate open"] = true;
      game.effects.print(3);
    }
    // servants' doors
    if (room_from.id === 47 && room_to.id === 19) {
      game.artifacts.get(21).is_open = true;
    }
    if (room_from.id === 44 && room_to.id === 26) {
      game.artifacts.get(27).is_open = true;
    }
  },

  "attackArtifact": function(arg: string, target: Artifact) {
    if (target.id === 34) {
      if (game.in_battle) {
        throw new CommandException("That will take a while. You can't turn your back on the enemy!");
      }
      target.hardiness -= game.diceRoll(game.player.weapon.dice, game.player.weapon.sides);
      if (target.hardiness < 0) {
        game.effects.print(11);
        destroy_clonatorium();
      } else {
        game.history.write("You hack at the machines, but it's going to take a while to do enough damage.");
        if (game.diceRoll(1, 2) === 2) {
          // move guards into the room
          game.history.write("A guard enters the room!", 'emphasis');
          game.monsters.get(23).damage = 0;
          game.monsters.get(23).moveToRoom();
        } else {
          game.history.write("Better hurry! More guards are on the way!");
        }
      }
      return false;
    }
    return true;
  },

  "attackMonster": function(arg: string, target: Monster) {
    // to battle!
    if (target.id === 5 || target.id === 6) {
      game.effects.print(9);
      game.monsters.get(4).reaction = Monster.RX_NEUTRAL;
      game.monsters.get(5).reaction = Monster.RX_NEUTRAL;
      game.monsters.get(6).destroy();
      game.monsters.updateVisible();
      game.artifacts.get(4).name = 'rebel airship';
      game.delay();
      return false;
    }
    return true;
  },

  "beforeClose": function(arg: string, artifact: Artifact) {
    if (artifact.id === 22 && game.data['inner gate open']) {
      game.history.write("The gears have been smashed. You can't close it.");
      return false;
    }
    return true;
  },

  "flee": function(arg: string, exit: RoomExit) {
    if (game.monsters.get(20).isHere() && game.player.room_id === 28) {
      // big group of soldiers
      if (arg === 's' || arg === 'south') {
        game.history.write("The soldiers block the entrance!");
      } else {
        game.player.moveToRoom(27);  // always flee north
        game.skip_battle_actions = true;
      }
      return false;
    }
    return true;
  },

  "light": function(arg: string, artifact: Artifact) {
    if (artifact !== null) {
      // dyn-o-mite!
      if (artifact.id === 5) {
        if (artifact.monster_id === Monster.PLAYER) {
          game.history.write("Better put it down first!");
        } else {
          if (game.artifacts.get(6).isHere()) {  // west side
            game.effects.print(1);
            game.history.write("* * B O O M * *", "special");
            artifact.destroy();
            game.artifacts.get(6).destroy();
            game.artifacts.get(9).moveToRoom();
            game.artifacts.get(10).moveToRoom(11);
            game.rooms.current_room.createExit('e', 11);
            game.rooms.get(11).createExit('w', 6);
          } else if (game.artifacts.get(8).isHere()) {  // east side
            game.effects.print(1);
            game.history.write("* * B O O M * *", "special");
            artifact.destroy();
            game.artifacts.get(8).destroy();
            game.artifacts.get(11).moveToRoom();
            game.artifacts.get(12).moveToRoom(16);
            game.rooms.current_room.createExit('w', 16);
            game.rooms.get(16).createExit('e', 8);
          } else {
            game.history.write("Save that for when you need it.");
          }
        }
        return false; // skip the regular "light source" lighting routine
      }
    }
    return true;
  },

  "seeArtifact": function(artifact: Artifact): void {
    if (artifact.id === 45) {
      game.delay();
      game.effects.print(13);
      game.monsters.get(15).destroy();
    }
  },

  "seeMonster": function(monster: Monster): void {
    // nasreen's opening remarks
    if (monster.id === 1) {
      game.history.write('Nasreen tells you, "Two of my commandos, Nevil and Norwood, are waiting in the camp to the south. We should join them as soon as you\'re ready."');
    }
    if (monster.id === 19) {
      // dragon
      game.effects.print(10);
      monster.destroy();
      game.monsters.get(20).removeChildren(Math.floor(game.monsters.get(20).children.length * 0.4));
    }
  },

  "use": function(arg: string, artifact: Artifact) {
    if (artifact.isHere()) {
      switch (artifact.name) {
        case 'dynamite':
          game.history.write("Try lighting it.");
          break;
        case 'fire cannon':
          if (game.in_battle) {
            throw new CommandException("The soldiers won't let you!");
          }
          const q1 = new ModalQuestion;
          q1.type = 'multiple_choice';
          q1.question = "What do you target with the cannon?";
          q1.choices = ['Battlefield', 'Power Station', 'Inner Gate'];
          q1.callback = function (answer) {
            switch (answer) {
              case q1.choices[0]:
                game.effects.print(5);
                break;
              case q1.choices[1]:
                game.effects.print(6);
                break;
              case q1.choices[2]:
                game.effects.print(7);
                game.artifacts.get(22).destroy();
                game.rooms.getRoomById(20).getExit('s').door_id = null;
                game.artifacts.get(23).moveToRoom(20);
                game.monsters.get(12).destroy();
                game.artifacts.get(44).moveToRoom(21);
                break;
            }
            game.data['cannon uses']--;
            if (game.data['cannon uses'] <= 0) {
              game.effects.print(8);
              artifact.destroy();
              game.artifacts.get(20).moveToRoom();
            }
          };
          game.modal.questions = [q1];
          game.modal.run();
          break;
        case 'console':
          if (!game.data['power off']) {
            game.history.write("You use the console to shut down power to parts of the complex. You hear startled shouts from outside, and the sounds of soldiers running.");
            // reduce the size of the big guard group
            game.monsters.get(20).removeChildren(Math.floor(game.monsters.get(20).children.length * 0.4));
            game.data['power off'] = true;
          } else {
            game.history.write("You can't figure out how to turn off any more power feeds.");
          }
          break;
        case 'resonant transformer':
          if (game.artifacts.get(34).isHere()) {
            artifact.destroy();
            game.effects.print(14);
            destroy_clonatorium();
          } else if (game.player.room_id === 23 || game.player.room_id === 32 || game.player.room_id === 39) {
            game.history.write("The device powers up and emits a series of small lightning bolts, but otherwise it does nothing.");
          } else {
            game.history.write("There is no power source here to operate the device.");
          }
          break;
        case 'glass grenade':
          if (game.artifacts.get(34).isHere()) {
            artifact.destroy();
            game.effects.print(15);
            destroy_clonatorium();
          } else if (game.in_battle) {
            game.effects.print(16);
            for (const m of game.monsters.visible.filter(x => x.reaction === Monster.RX_HOSTILE)) {
              if (m.children.length) {
                // group monsters take 1 hit per member
                m.children.forEach(c => c.injure(game.diceRoll(1, 20), true));
              } else {
                m.injure(game.diceRoll(1, 20), true);
              }
            }
            artifact.destroy();
          } else {
            game.history.write("There is nothing here to use the grenade on. Save it for when you need it.");
          }
          break;
      }
    }
  },

  "endTurn2": function() {
    // inner gate
    if (game.artifacts.get(22).isHere() && game.artifacts.get(30).is_worn) {
      game.effects.print(2);
      game.artifacts.get(22).is_open = true;
    }
    // inside inner gate
    if (game.monsters.get(12).isHere() && !game.data['clone check']) {
      game.effects.print(4);
      game.data['clone check'] = true;
    }
  },

  "power": function(roll) {
    if (roll <= 50) {
      game.history.write("You hear a loud sonic boom which echoes all around you!");
    } else if (roll <= 75) {
      // teleport to random room
      game.history.write("You are being teleported...");
      const room = game.rooms.getRandom();
      game.player.moveToRoom(room.id);
      game.skip_battle_actions = true;
    } else {
      game.history.write("All your wounds are healed!");
      game.player.heal(1000);
    }
  },

  // event handler that happens at the very end, after the player has sold their treasure to sam slicker
  "afterSell": function() {
    game.after_sell_messages.push("The rebels gave you some sheets of green paper with lots of zeroes on them as a reward. You threw them away as valueless.");
  },

}; // end event handlers

// declare any functions used by event handlers and custom commands
function destroy_clonatorium() {
  game.artifacts.get(34).destroy();
  game.artifacts.get(35).moveToRoom();
  // chaos
  const guards = game.monsters.get(20);
  guards.children.filter(g => g.room_id === 28).forEach(g => g.destroy());

  game.monsters.get(5).destroy();
  game.monsters.get(13).destroy();
  game.monsters.get(23).moveToRoom(27);
  // todo: the group of guards starts with 1 member, but can grow. Need to research this
  game.monsters.get(23).spawnChild(); // turns it into a group monster with 1 member
  game.monsters.get(24).moveToRoom(20);
  game.monsters.get(25).moveToRoom(19);
  // any other remaining soldiers
  const possible_rooms = [10, 11, 12, 13, 16, 17, 20, 21, 22, 31, 37, 38, 43, 44, 45, 46, 47];
  for (let m = 7; m <= 12; m++) {
    if (game.monsters.get(m).room_id !== null) {
      const r = game.diceRoll(1, possible_rooms.length) - 1;
      const monster = game.monsters.get(m);
      monster.moveToRoom(possible_rooms[r]);
      // also move all living members of group monsters
      monster.children.filter(c => c.status === Monster.STATUS_ALIVE).forEach(c => c.moveToRoom(possible_rooms[r]));
    }
  }
}


text:
namespace gl
{
void GL_APIENTRY UniformMatrix2x3fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix2x3fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix2x3fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix2x3fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix2x3fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}

void GL_APIENTRY UniformMatrix2x4fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix2x4fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix2x4fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix2x4fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix2x4fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}

void GL_APIENTRY UniformMatrix3x2fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix3x2fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix3x2fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix3x2fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix3x2fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}

void GL_APIENTRY UniformMatrix3x4fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix3x4fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix3x4fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix3x4fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix3x4fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}

void GL_APIENTRY UniformMatrix4x2fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix4x2fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix4x2fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix4x2fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix4x2fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}

void GL_APIENTRY UniformMatrix4x3fv(GLint location,
                                    GLsizei count,
                                    GLboolean transpose,
                                    const GLfloat *value)
{
    Context *context = GetValidGlobalContext();
    EVENT("glUniformMatrix4x3fv",
          "context = %d, GLint location = %d, GLsizei count = %d, GLboolean transpose = %s, const "
          "GLfloat *value = 0x%016" PRIxPTR "",
          CID(context), location, count, GLbooleanToString(transpose), (uintptr_t)value);

    if (context)
    {
        UniformLocation locationPacked                        = FromGL<UniformLocation>(location);
        std::unique_lock<angle::GlobalMutex> shareContextLock = GetShareGroupLock(context);
        bool isCallValid =
            (context->skipValidation() ||
             ValidateUniformMatrix4x3fv(context, locationPacked, count, transpose, value));
        if (isCallValid)
        {
            context->uniformMatrix4x3fv(locationPacked, count, transpose, value);
        }
        ANGLE_CAPTURE(UniformMatrix4x3fv, isCallValid, context, locationPacked, count, transpose,
                      value);
    }
}
}  // namespace gl


text:
package org.lte.project.gtp.control.message;

import org.lte.project.gtp.core.message.GTPMessage;

/**
 * @author Calin Cerchez [calin.cerchez@gmail.com]
 */
public class CreateSessionRequest extends GTPMessage {

	public static final short CREATE_SESSION_REQUEST = 32;

	public CreateSessionRequest(long teid, long sequenceNumber) {
		super(new GTPcHeader(CREATE_SESSION_REQUEST, teid, sequenceNumber));
	}
}


text:
@interface BMPInstanceWithSetterRecord : NSObject

@property (nonatomic, strong, readwrite) NSMutableDictionary *valuePackagesByPropertyName;
@property (nonatomic, strong, readwrite) NSString *className;

@end


text:
FactoryGirl.define do
  factory :asset_event_asset_subsystem do
    association :rehabilitation_update_event
    association :asset_subsystem
  end
end


text:
using System.Collections.Generic;

namespace Microsoft.DotNet.ProjectModel.Server.Models
{
    public class ProjectInformationMessage
    {
        public string Name { get; set; }

        public IList<FrameworkData> Frameworks { get; set; }

        public IList<string> Configurations { get; set; }

        public IDictionary<string, string> Commands { get; set; }

        public IList<string> ProjectSearchPaths { get; set; }

        public string GlobalJsonPath { get; set; }
    }
}


text:
You actually have two ways to install it :

## 1. From scratch using Victoire Demo

Follow the instructions on [victoire demo Readme](https://github.com/Victoire/demo/blob/master/README.md)

## 2. In an existing Symfony project

- Install Victoire core :

    composer require victoire/victoire

- Declare in AppKernel:

```php
    //dependencies
    new AppVentus\AsseticInjectorBundle\AvAsseticInjectorBundle(),
    new AppVentus\AlertifyBundle\AvAlertifyBundle(),
    new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
    new FOS\UserBundle\FOSUserBundle(),
    new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
    new JMS\AopBundle\JMSAopBundle(),
    new JMS\TranslationBundle\JMSTranslationBundle(),
    new JMS\SerializerBundle\JMSSerializerBundle(),
    new JMS\DiExtraBundle\JMSDiExtraBundle($this),
    new Liip\ImagineBundle\LiipImagineBundle(),
    new Knp\Bundle\MenuBundle\KnpMenuBundle(),
    new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(),
    new Snc\RedisBundle\SncRedisBundle(),
    //Victoire bundles
    new Victoire\Bundle\AnalyticsBundle\VictoireAnalyticsBundle(),
    new Victoire\Bundle\BlogBundle\VictoireBlogBundle(),
    new Victoire\Bundle\BusinessEntityBundle\VictoireBusinessEntityBundle(),
    new Victoire\Bundle\BusinessPageBundle\VictoireBusinessPageBundle(),
    new Victoire\Bundle\CoreBundle\VictoireCoreBundle(),
    new Victoire\Bundle\FilterBundle\VictoireFilterBundle(),
    new Victoire\Bundle\FormBundle\VictoireFormBundle(),
    new Victoire\Bundle\I18nBundle\VictoireI18nBundle(),
    new Victoire\Bundle\MediaBundle\VictoireMediaBundle(),
    new Victoire\Bundle\PageBundle\VictoirePageBundle(),
    new Victoire\Bundle\QueryBundle\VictoireQueryBundle(),
    new Victoire\Bundle\ResourcesBundle\VictoireResourcesBundle(),
    new Victoire\Bundle\SeoBundle\VictoireSeoBundle(),
    new Victoire\Bundle\SitemapBundle\VictoireSitemapBundle(),
    new Victoire\Bundle\TemplateBundle\VictoireTemplateBundle(),
    new Victoire\Bundle\TwigBundle\VictoireTwigBundle(),
    new Victoire\Bundle\UserBundle\VictoireUserBundle(),
    new Victoire\Bundle\ViewReferenceBundle\ViewReferenceBundle(),
    new Victoire\Bundle\WidgetBundle\VictoireWidgetBundle(),
    new Victoire\Bundle\WidgetMapBundle\VictoireWidgetMapBundle(),
    //Victoire test bundles
    new Victoire\Widget\ForceBundle\VictoireWidgetForceBundle(),
    new Victoire\Widget\LightSaberBundle\VictoireWidgetLightSaberBundle(),
    new Victoire\Widget\ButtonBundle\VictoireWidgetButtonBundle(),
    new Victoire\Widget\TextBundle\VictoireWidgetTextBundle(),
    new Acme\AppBundle\AcmeAppBundle(),
```

- create victoire.yml config file:

```yml
    victoire_core:
        user_class: Victoire\Bundle\UserBundle\Entity\User
        templates:
            layout: "::layout.html.twig"
        layouts:
            fullWidth: "Contenu unique"
        slots:
            header_logo:
                max: 1
                widgets:
                    image: ~
```

- add the wanted widgets:

```json
        "friendsofvictoire/text-widget"      : "dev-master",
        "friendsofvictoire/button-widget"    : "dev-master",
        "friendsofvictoire/image-widget"     : "dev-master",
        "friendsofvictoire/render-widget"    : "dev-master",
        "friendsofvictoire/breadcrumb-widget": "dev-master",
        ...
```

Get the whole Victoire Widget list [**here**](http://packagist.org/search/?tags=victoire)

Check victoire dependencies:

```json
    "knplabs/knp-menu"                       : "2.1.*@dev",
    "knplabs/knp-menu-bundle"                : "2.1.*@dev",
    "friendsofsymfony/user-bundle"           : "2.0.*@dev",
    "stof/doctrine-extensions-bundle"        : "1.2.*@dev",
    "appventus/assetic-injector-bundle"      : "dev-master",
    "appventus/alertify-bundle"              : "dev-master",
    "appventus/shortcuts-bundle"             : "dev-master",
    "knplabs/gaufrette"                      : "v0.1.7",
    "knplabs/knp-gaufrette-bundle"           : "v0.1.7",
    "knplabs/knp-components"                 : "1.3.*@dev",
```

- setup routing:

```yml
        fos_user_security:
            resource: "@FOSUserBundle/Resources/config/routing/security.xml"

        fos_user_resetting:
            resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
            prefix: /resetting

        fos_js_routing:
            resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"

        VictoireCoreBundle:
            resource: .
            type: victoire
```

- Enable StofDoctrineExtensions in AppKernel

- add this config in doctrine.yml:

```yml
        orm:
           [...]
            mappings:
                gedmo_tree:
                    type: annotation
                    prefix: Gedmo\Tree\Entity
                    dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
                    is_bundle: false
```

- add this config in stof_doctrine_extensions (imported in config.yml)

```yml
    stof_doctrine_extensions:
        default_locale: fr_FR
        orm:
            default:
                tree: true
```

- install FOSJSRouting

```
    composer require friendsofsymfony/jsrouting-bundle
```

- enable the localizeddate filter

```yml
        twig.extension.intl:
            class: Twig_Extensions_Extension_Intl
            tags:
                - { name: twig.extension }
```

- import the victoire config file

```yml
imports:
        - { resource: @VictoireCoreBundle/Resources/config/config.yml }
```

- install redis

```
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
```

- setup redis

```yml
snc_redis:
   clients:
       victoire:
           type: predis
           alias: victoire
           dsn: redis://localhost
```

- start redis server

```
redis-server
```

- set a CRON

```
* * * * * bin/console victoire:widget-css:generate --limit 20 --outofdate
```

This command allow you to regenerate View's CSS

- log in

Use the following information to login and start to create your website

|Login|Password|
|-----|--------|
|`anakin@victoire.io`|test|


text:
require 'fog/core/collection'
require 'fog/aws/models/elasticache/security_group'

module Fog
  module AWS
    class Elasticache

      class SecurityGroups < Fog::Collection
        model Fog::AWS::Elasticache::SecurityGroup

        def all
          load(
            connection.describe_cache_security_groups.body['CacheSecurityGroups']
          )
        end

        def get(identity)
          new(
            connection.describe_cache_security_groups(
              identity
            ).body['CacheSecurityGroups'].first
          )
        rescue Fog::AWS::Elasticache::NotFound
          nil
        end
      end

    end
  end
end


text:
package org.apache.atlas.authorize.simple;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;

import org.apache.atlas.authorize.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;

public class SimpleAtlasAuthorizerTest {

    private static Logger LOG = LoggerFactory
            .getLogger(SimpleAtlasAuthorizerTest.class);

    @Test
    public void testAccessAllowedForUserAndGroup() {

        Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null;
        Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null;
        List<String> policies = new ArrayList<String>();
        policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:*abc,type:PII");

        List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies);
        PolicyUtil policyUtil = new PolicyUtil();
        // group read map
        groupReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP);
        // creating user readMap
        userReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER);

        Set<AtlasResourceTypes> resourceType = new HashSet<AtlasResourceTypes>();
        resourceType.add(AtlasResourceTypes.TYPE);
        String resource = "xsdfhjabc";
        AtlasActionTypes action = AtlasActionTypes.READ;
        String user = "usr1";

        Set<String> userGroups = new HashSet<String>();
        userGroups.add("grp3");
        try {
            AtlasAccessRequest request = new AtlasAccessRequest(resourceType,
                    resource, action, user, userGroups);
            SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory
                    .getAtlasAuthorizer();

            authorizer
                    .setResourcesForTesting(userReadMap, groupReadMap, action);

            boolean isAccessAllowed = authorizer.isAccessAllowed(request);
            // getUserReadMap
            AssertJUnit.assertEquals(true, isAccessAllowed);
        } catch (AtlasAuthorizationException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("AtlasAuthorizationException in Unit Test", e);
            }
        }

    }

    @Test
    public void testAccessAllowedForGroup() {

        Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null;
        Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null;
        List<String> policies = new ArrayList<String>();
        policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII");

        List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies);
        PolicyUtil policyUtil = new PolicyUtil();
        // creating group read map
        groupReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP);
        // creating user readMap
        userReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER);

        Set<AtlasResourceTypes> resourceType = new HashSet<AtlasResourceTypes>();
        resourceType.add(AtlasResourceTypes.TYPE);
        String resource = "PII";
        AtlasActionTypes action = AtlasActionTypes.READ;
        String user = "usr3";
        Set<String> userGroups = new HashSet<String>();
        userGroups.add("grp1");
        AtlasAccessRequest request = new AtlasAccessRequest(resourceType,
                resource, action, user, userGroups);
        try {
            SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory
                    .getAtlasAuthorizer();
            authorizer
                    .setResourcesForTesting(userReadMap, groupReadMap, action);

            boolean isAccessAllowed = authorizer.isAccessAllowed(request);
            AssertJUnit.assertEquals(true, isAccessAllowed);
        } catch (AtlasAuthorizationException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("AtlasAuthorizationException in Unit Test", e);
            }

        }

    }

    @Test
    public void testResourceNotAvailableInPolicy() {

        Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null;
        Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null;
        List<String> policies = new ArrayList<String>();
        policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII");

        List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies);
        PolicyUtil policyUtil = new PolicyUtil();
        // group read map
        groupReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP);
        // creating user readMap
        userReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER);

        Set<AtlasResourceTypes> resourceType = new HashSet<AtlasResourceTypes>();
        resourceType.add(AtlasResourceTypes.TYPE);
        String resource = "abc";
        AtlasActionTypes action = AtlasActionTypes.READ;
        String user = "usr1";
        Set<String> userGroups = new HashSet<String>();
        userGroups.add("grp1");
        AtlasAccessRequest request = new AtlasAccessRequest(resourceType,
                resource, action, user, userGroups);
        try {
            SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory
                    .getAtlasAuthorizer();
            authorizer
                    .setResourcesForTesting(userReadMap, groupReadMap, action);

            boolean isAccessAllowed = authorizer.isAccessAllowed(request);
            AssertJUnit.assertEquals(false, isAccessAllowed);
        } catch (AtlasAuthorizationException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("AtlasAuthorizationException in Unit Test", e);
            }
        }

    }

    @Test
    public void testAccessNotAllowedForUserAndGroup() {

        Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null;
        Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null;
        List<String> policies = new ArrayList<String>();
        policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII");

        List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies);
        PolicyUtil policyUtil = new PolicyUtil();
        // group read map
        groupReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP);
        // creating user readMap
        userReadMap = policyUtil.createPermissionMap(policyDefs,
                AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER);

        Set<AtlasResourceTypes> resourceType = new HashSet<AtlasResourceTypes>();
        resourceType.add(AtlasResourceTypes.TYPE);
        String resource = "PII";
        AtlasActionTypes action = AtlasActionTypes.READ;
        String user = "usr3";
        Set<String> userGroups = new HashSet<String>();
        userGroups.add("grp3");
        AtlasAccessRequest request = new AtlasAccessRequest(resourceType,
                resource, action, user, userGroups);
        try {
            SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory
                    .getAtlasAuthorizer();
            authorizer
                    .setResourcesForTesting(userReadMap, groupReadMap, action);

            boolean isAccessAllowed = authorizer.isAccessAllowed(request);
            AssertJUnit.assertEquals(false, isAccessAllowed);
        } catch (AtlasAuthorizationException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("AtlasAuthorizationException in Unit Test", e);
            }
        }

    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Crombie, J. Bot. , London 14: 264 (1876)

#### Original name
Lecidea coccocarpoides Nyl.

### Remarks
null


text:
package com.waiso.social.framework.exceptions;

import com.waiso.social.framework.log.GerenciadorLog;

public class WSSendException extends UserException{

	private static final long serialVersionUID = 1L;

	public WSSendException(Class origin, Throwable cause) {
		super(cause);
		GerenciadorLog.error(origin, cause);
	}

	public WSSendException(Class origin, String message) {
		super(message);
		GerenciadorLog.error(origin, message);
	}
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Stub.Models;
using StubDataAccess;
using StubDataAccess.Entities;
using StubDataAccess.Repositories;
using StubDataAccess.Types;
using StubDataAccess.Utils;

namespace Stub.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        [Import(typeof(IRepositoryCollection))]
        public IRepositoryCollection Repositories { get; set; }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AddReview(MainModel model)
        {
            if (ShouldSave(model))
            {
                Repositories.ReviewRepository.AddReview(new Review()
                {
                    Subject = new Subject(){Name = model.Subject, SubjectType = EnumHelper<SubjectType>.StringToEnum(model.SelectedType)},
                    TwoWordReview = model.TwoWordReview,
                });
            }
            return View("AddReview", new MainModel());
        }

        public bool ShouldSave(MainModel model)
        {
            if (string.IsNullOrEmpty(model.Subject) || string.IsNullOrEmpty(model.TwoWordReview) ||
                string.IsNullOrEmpty(model.SelectedType)) return false;
            return true;
        }

    }
}


text:
begin
  # aws-cleaner deps
  require 'json'
  require 'yaml'
  require 'aws-sdk-core'
  require 'chef-api'
  require 'chronic'
  require 'hipchat'
  require 'rest-client'
  require 'time'
  require 'trollop'
  require 'slack/poster'
  require 'aws_cleaner/aws_cleaner.rb'
  # aws_watcher deps
rescue LoadError => e
  raise "Missing Gems: #{e}"
end

require_relative '../lib/aws-watcher.rb'

# config file
def config(file)
  YAML.safe_load(File.read(file), [Symbol])
rescue StandardError => e
  raise "Failed to open config file: #{e}"
end

# get options
opts = Trollop.options do
  opt :config, 'Path to config file', type: :string, default: 'config.yml'
  opt :tag, 'tagName:tagValue1,tagValue2', type: String, required: true
end

@config = config(opts[:config])

# initialize clients
@sqs_client = AwsCleaner::SQS.client(@config)
@chef_client = AwsCleaner::Chef.client(@config)

# get tags
begin
  @tag_name = opts[:tag].split(':')[0].strip
  @tag_values = opts[:tag].split(':')[1].split(',').strip
  p "#{@tag_name}, #{@tag_values}"
rescue
  msg = "You passed be a tag of #{ops[:tag]} which is not valid "
  msg += 'tags must look like this: -t tag:value you can'
  msg += 'optionally pass multiple values for the same tag like '
  msg += 'this -t tag:value1,value2'
  p msg
  exit 1
end

# start program in infinate loop
loop do
  messages = @sqs_client.receive_message(
    queue_url: @config[:sqs][:queue],
    max_number_of_messages: 10,
    visibility_timeout: 3
  ).messages

  puts "Got #{messages.size} message(s)" # unless messages.size.zero?
  messages.each_with_index do |message, index|
    puts "Looking at message number #{index}" # unless messages.size.zero?
    body = AwsCleaner.new.parse(message.body)
    id = message.receipt_handle
    now = Time.now.utc
    launch_time = Chronic.parse(body['time'])

    unless body
      AwsCleaner.new.delete_message(id, @config)
      next
    end

    @instance_id = AwsCleaner.new.process_message(body)
    elapsed_time = now - launch_time
    p "launch_time: #{launch_time}"
    p "now: #{now}"
    # if the node is no longer in aws we don't care anymore
    # we can delete the message message
    if !AwsWatcher::EC2.instance_alive?(@instance_id, @config)
      p "instance: #{@instance_id} is not in aws anymore, removing message from queue"
      AwsCleaner.new.delete_message(id, @config)
    # if the node exists in chef it has bootstrapped
    # so we can delete the message
    elsif AwsWatcher::Chef.registered?(@instance_id, @config)
      p "instance: #{@instance_id} has bootstrapped, removing message from queue"
      AwsCleaner.new.delete_message(id, @config)
      next
    elsif !AwsWatcher::EC2.tag_matches?(@instance_id, @tag_name, @tag_values, @config)
      p "instance: #{@instance_id} has not bootstrap and was deleted because it did not have a tag of: #{@tag_name} matching one of these values: #{@tag_values}"
      AwsCleaner.new.delete_message(id, @config)
      next
    else
      p "instance: #{@instance_id}, launched: #{launch_time}, elapsed: #{elapsed_time} seconds"
    end
    # if the elapsed time is less than how long we consider
    # a 'normal' converge time that's ok we just move on and
    # wait for another pass
    if elapsed_time < @config[:bootstrap][:converged_by]
      if ENV['LOG_LEVEL'] == 'DEBUG'
        'node elaspsed time is normal'
      end
      next
    # if the elapsed time is greater than or equal then we need
    # to do something although I am not sure what yet.
    elsif elapsed_time >= @config[:bootstrap][:converged_by]
      # we want to validate that the machine is still in aws
      # and did not get terminated by something like an auto scale
      # group or someone messing around in console
      p 'node elaspsed time is too high'
      notification = "node: #{@instance_id} has not checked in, "
      notification += 'it should have converged by: '
      notification += "#{@config[:bootstrap][:converged_by]} seconds "
      notification += "and has been running since: #{launch_time}"
      AwsCleaner::Notify.notify_chat(notification, @config)
    end
  end
  sleep @config[:poll_time]
end


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Entity\EntityWithPluginCollectionInterface.
 */

namespace Drupal\Core\Entity;

/**
 * Provides an interface for an object using a plugin collection.
 *
 * @see \Drupal\Component\Plugin\LazyPluginCollection
 *
 * @ingroup plugin_api
 */
interface EntityWithPluginCollectionInterface extends EntityInterface {

  /**
   * Gets the plugin collections used by this entity.
   *
   * @return \Drupal\Component\Plugin\LazyPluginCollection[]
   *   An array of plugin collections, keyed by the property name they use to
   *   store their configuration.
   */
  public function getPluginCollections();

}


text:
package org.apache.struts.maven.snippetextractor.parser.java;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Class extracting the java package definition from the provided {@link String}. Additionally there is a convenience
 * method just checking if any package definition is available in the provided {@link String}.
 */
public class PackageParser {

    private static final String PACKAGE_REGEX = "(package[\\s]*+)(.+?)([\\s]*;)";
    private static final Pattern PACKAGE_PATTERN = Pattern.compile(PACKAGE_REGEX);

    /**
     * Finds a package definition in the provided string. The method works with the pattern
     * {@value PackageParser#PACKAGE_REGEX}. If no pattern is found, {@code null} will be returned.
     * @param string to search for a package definition
     * @return package as {@link String} or {@code null}
     */
    public static String find(String string) {
        String packagePath = null;
        Matcher packagePathMatcher = PACKAGE_PATTERN.matcher(string);
        if (contains(string, packagePathMatcher)) {
            packagePath = packagePathMatcher.group(2);
        }
        return packagePath;
    }

    /**
     * Check if the provided {@link String} contains a package definition.
     * @param string to check for a package definition
     * @return {@code true} if a package definition is found, otherwise {@code false}
     */
    public static boolean contains(String string) {
        return contains(string, null);
    }

    /**
     * Check if the provided {@link String} contains a package definition. Additionally you can provide a matcher. If
     * non is provided a new one is instantiated.
     * @param string to check for a package definition
     * @param matcher to use for searching a package definition. If {@code null} a new one is instantiated.
     * @return {@code true} if a package definition is found, otherwise {@code false}
     */
    private static boolean contains(String string, Matcher matcher) {
        if (matcher == null) {
            matcher = PACKAGE_PATTERN.matcher(string);
        }
        return (matcher.find() && matcher.groupCount() == 3);
    }
}


text:
<?php namespace Scriptotek\Ncip\Test;

use Danmichaelo\QuiteSimpleXMLElement\QuiteSimpleXMLElement;
use Scriptotek\Ncip\CheckInResponse;

class CheckInResponseTest extends \PHPUnit_Framework_TestCase {

	protected $dummy_response_success = '
 		<ns1:NCIPMessage xmlns:ns1="http://www.niso.org/2008/ncip">
 		   <ns1:CheckInItemResponse>
 			  <ns1:ItemId>
 				 <ns1:AgencyId>q</ns1:AgencyId>
 				 <ns1:ItemIdentifierValue>xxxxxxxxx</ns1:ItemIdentifierValue>
 			  </ns1:ItemId>
 			  <ns1:ItemOptionalFields>
 				 <ns1:BibliographicDescription>
 					<ns1:Author>DuCharme, Bob</ns1:Author>
 					<ns1:BibliographicRecordId>
 					   <ns1:BibliographicRecordIdentifier>11447981x</ns1:BibliographicRecordIdentifier>
 					   <ns1:BibliographicRecordIdentifierCode>Accession Number</ns1:BibliographicRecordIdentifierCode>
 					</ns1:BibliographicRecordId>
 					<ns1:Edition/>
 					<ns1:Pagination>XIII, 235 s., ill.</ns1:Pagination>
 					<ns1:PublicationDate>2011</ns1:PublicationDate>
 					<ns1:Publisher>O\'Reilly</ns1:Publisher>
 					<ns1:Title>Learning SPARQL : querying and updating with SPARQL 1.1</ns1:Title>
 					<ns1:Language>eng</ns1:Language>
 					<ns1:MediumType>Book</ns1:MediumType>
 				 </ns1:BibliographicDescription>
 			  </ns1:ItemOptionalFields>
 			  <ns1:Ext>
 				 <ns1:UserOptionalFields>
 					<ns1:UserLanguage>eng</ns1:UserLanguage>
 				 </ns1:UserOptionalFields>
 			  </ns1:Ext>
 		   </ns1:CheckInItemResponse>
 		</ns1:NCIPMessage>';

 	protected $dummy_response_fail = '
 		<ns1:NCIPMessage xmlns:ns1="http://www.niso.org/2008/ncip">
 		   <ns1:CheckInItemResponse>
 		      <ns1:Problem>
 		         <ns1:ProblemType>Ukjent feil</ns1:ProblemType>
 		         <ns1:ProblemDetail>Ukjent feil.</ns1:ProblemDetail>
 		      </ns1:Problem>
 			  <ns1:Ext>
 				 <ns1:UserOptionalFields>
 					<ns1:UserLanguage>eng</ns1:UserLanguage>
 				 </ns1:UserOptionalFields>
 			  </ns1:Ext>
 		   </ns1:CheckInItemResponse>
 		</ns1:NCIPMessage>';

	public function testParseDummySuccessResponse() {
		$dummy_response = new QuiteSimpleXMLElement($this->dummy_response_success);
		$response = new CheckInResponse($dummy_response);

		$this->assertInstanceOf('Scriptotek\Ncip\CheckInResponse', $response);
		$this->assertTrue($response->success);
		$this->assertEquals('xxxxxxxxx', $response->id);
		$this->assertEquals('q', $response->agencyId);
	}

	public function testParseDummySuccessFailure() {
		$dummy_response = new QuiteSimpleXMLElement($this->dummy_response_fail);
		$response = new CheckInResponse($dummy_response);

		$this->assertInstanceOf('Scriptotek\Ncip\CheckInResponse', $response);
		$this->assertFalse($response->success);
		$this->assertEquals('Ukjent feil', $response->error);
		$this->assertEquals('Ukjent feil.', $response->errorDetails);
	}

}