text:
typedef Table_T chops_context;

chops_context ic_init();
void cc_add(chops_context ic, char *k, void *v);
void *cc_find(chops_context ic, const char *k);
void cc_free(chops_context cc);
void chops_cc_add_string(chops_context cc, char *k, char *v);
struct buf *chops_template_render(crustache_template ** t, chops_context cc);

enum type_tag {CC_LIST, CC_CONTEXT, CC_STR, CC_FALSE, CC_LAMBDA};

typedef struct chops_context_value chops_context_value;

struct chops_context_value {
    enum type_tag tag;
    void *data;
};


text:
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and / or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The below copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Vulkan Cookbook
// ISBN: 9781786468154
// © Packt Publishing Limited
//
// Author:   Pawel Lapinski
// LinkedIn: https://www.linkedin.com/in/pawel-lapinski-84522329
//
// Chapter: 09 Command Recording and Drawing
// Recipe:  18 Preparing a single frame of animation

#ifndef PREPARING_A_SINGLE_FRAME_OF_ANIMATION
#define PREPARING_A_SINGLE_FRAME_OF_ANIMATION

#include "03 Command Buffers and Synchronization/11 Submitting command buffers to the queue.h"
#include "Common.h"

namespace VulkanCookbook {

  bool PrepareSingleFrameOfAnimation( VkDevice                                                        logical_device,
                                      VkQueue                                                         graphics_queue,
                                      VkQueue                                                         present_queue,
                                      VkSwapchainKHR                                                  swapchain,
                                      VkExtent2D                                                      swapchain_size,
                                      std::vector<VkImageView> const                                & swapchain_image_views,
                                      VkImageView                                                     depth_attachment,
                                      std::vector<WaitSemaphoreInfo> const                          & wait_infos,
                                      VkSemaphore                                                     image_acquired_semaphore,
                                      VkSemaphore                                                     ready_to_present_semaphore,
                                      VkFence                                                         finished_drawing_fence,
                                      std::function<bool(VkCommandBuffer, uint32_t, VkFramebuffer)>   record_command_buffer,
                                      VkCommandBuffer                                                 command_buffer,
                                      VkRenderPass                                                    render_pass,
                                      VkDestroyer(VkFramebuffer)                                    & framebuffer );

} // namespace VulkanCookbook

#endif // PREPARING_A_SINGLE_FRAME_OF_ANIMATION

redpajama_set_name: RedPajamaGithub


text:
$ReleaseVersionNumber = $env:APPVEYOR_BUILD_VERSION
$PreReleaseName = ''

If($env:APPVEYOR_PULL_REQUEST_NUMBER -ne $null) {
  $PreReleaseName = '-PR-' + $env:APPVEYOR_PULL_REQUEST_NUMBER
} ElseIf($env:APPVEYOR_REPO_BRANCH -ne 'master') {
  $PreReleaseName = '-' + $env:APPVEYOR_REPO_BRANCH
} Else {
  $PreReleaseName = '-CI'
}

$PSScriptFilePath = (Get-Item $MyInvocation.MyCommand.Path).FullName
$ScriptDir = Split-Path -Path $PSScriptFilePath -Parent
$SolutionRoot = Split-Path -Path $ScriptDir -Parent

 $ProjectJsonPath = Join-Path -Path $SolutionRoot -ChildPath "src\NUnit.Portable.Agent\project.json"
 (gc -Path $ProjectJsonPath) `
 	-replace "(?<=`"version`":\s`")[.\w-]*(?=`",)", "$ReleaseVersionNumber$PreReleaseName" |
 	sc -Path $ProjectJsonPath -Encoding UTF8


text:
from logdissect.parsers.type import ParseModule as OurModule

class ParseModule(OurModule):
    def __init__(self, options=[]):
        """Initialize a gentoo emerge log parsing module"""
        self.name = 'emerge'
        self.desc = 'gentoo emerge log parsing module'
        self.format_regex = '^(\d+\.?\d*):\s(.*)$'
        # fractional seconds added for future-proofing
        self.fields = ['date_stamp', 'prefix', 'message']
        self.backup_format_regex = None
        self.backup_fields = []
        self.tzone = None
        self.datestamp_type = 'unix'


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

<TITLE>
PDFEmbeddedFileExtensionAttachment (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.render.pdf.extensions

Class PDFEmbeddedFileExtensionAttachment

java.lang.Object
  org.apache.fop.render.pdf.extensions.PDFExtensionAttachment
      org.apache.fop.render.pdf.extensions.PDFEmbeddedFileExtensionAttachment

All Implemented Interfaces:
ExtensionAttachment, org.apache.xmlgraphics.util.XMLizable

public class PDFEmbeddedFileExtensionAttachment
extends PDFExtensionAttachment

This is the pass-through value object for the PDF extension.

Field Summary

protected static java.lang.String
ELEMENT

          element name

Fields inherited from class org.apache.fop.render.pdf.extensions.PDFExtensionAttachment

CATEGORY

Constructor Summary

PDFEmbeddedFileExtensionAttachment()

          No-argument contructor.

PDFEmbeddedFileExtensionAttachment(java.lang.String filename,
                                   java.lang.String src,
                                   java.lang.String desc)

          Default constructor.

Method Summary

 java.lang.String
getCategory()

          This method returns a category URI that allows a processor (layout manager or renderer)
 to determine if it supports this object.

 java.lang.String
getDesc()

          Returns the file description.

protected  java.lang.String
getElement()

 java.lang.String
getFilename()

          Returns the file name.

 java.lang.String
getSrc()

          Returns the source URI of the file.

 void
setDesc(java.lang.String desc)

          Sets the description of the file.

 void
setFilename(java.lang.String name)

          Sets the file name.

 void
setSrc(java.lang.String src)

          Sets the source URI of the file.

 void
toSAX(org.xml.sax.ContentHandler handler)

 java.lang.String
toString()

Methods inherited from class org.apache.fop.render.pdf.extensions.PDFExtensionAttachment

getType

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

ELEMENT

protected static final java.lang.String ELEMENT

element name

See Also:
Constant Field Values

Constructor Detail

PDFEmbeddedFileExtensionAttachment

public PDFEmbeddedFileExtensionAttachment()

No-argument contructor.

PDFEmbeddedFileExtensionAttachment

public PDFEmbeddedFileExtensionAttachment(java.lang.String filename,
                                          java.lang.String src,
                                          java.lang.String desc)

Default constructor.

Parameters:
filename - the name of the file
src - the location of the file
desc - the description of the file

Method Detail

getFilename

public java.lang.String getFilename()

Returns the file name.

Returns:
the file name

setFilename

public void setFilename(java.lang.String name)

Sets the file name.

Parameters:
name - The file name to set.

getDesc

public java.lang.String getDesc()

Returns the file description.

Returns:
the description

setDesc

public void setDesc(java.lang.String desc)

Sets the description of the file.

Parameters:
desc - the description to set

getSrc

public java.lang.String getSrc()

Returns the source URI of the file.

Returns:
the source URI

setSrc

public void setSrc(java.lang.String src)

Sets the source URI of the file.

Parameters:
src - the source URI

getCategory

public java.lang.String getCategory()

This method returns a category URI that allows a processor (layout manager or renderer)
 to determine if it supports this object.

Specified by:
getCategory in interface ExtensionAttachment
Overrides:
getCategory in class PDFExtensionAttachment

Returns:
the category URI
See Also:
ExtensionAttachment.getCategory()

toString

public java.lang.String toString()

Overrides:
toString in class PDFExtensionAttachment

Returns:
a string representation of this object
See Also:
Object.toString()

getElement

protected java.lang.String getElement()

Specified by:
getElement in class PDFExtensionAttachment

Returns:
the element name

toSAX

public void toSAX(org.xml.sax.ContentHandler handler)
           throws org.xml.sax.SAXException

Throws:

org.xml.sax.SAXException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

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


text:
def client_id
  ENV['CLIENT_ID']
end

def client_secret
  ENV['CLIENT_SECRET']
end

get '/oauth' do
  current_user
  redirect '/player' if @current_user
  client = Player.initiate_client_with_secret_and_redirect('http://localhost:9393/callback')
  redirect client.authorize_url()

end

get '/callback' do
  client = Player.initiate_client_with_secret_and_redirect('http://localhost:9393/callback')

  code = params[:code]
  access_token = client.exchange_token(:code => code)[:access_token]

  client = Player.initiate_client_access_token(access_token)

  # make an authenticated call
  begin
    current_user = client.get('/me')
  rescue Soundcloud::ResponseError => e
    puts "ERROR: #{e.message}, Status Code: #{e.response.code}"
  end

  user = User.create({
      first_name: current_user.first_name,
      last_name: current_user.last_name,
      username: current_user.username,
      soundcloud_token: access_token,
      avatar_link: current_user.avatar_url,
      soundcloud_uri: current_user.uri
    })

  current_user = user

  session[:user_id] = user.id

  redirect '/users/new'
end


text: export * from "./ConnectionToolbarContainer";


text:
#ifndef BMICONTROLLER_H
#define BMICONTROLLER_H

#include "cwf/controller.h"
#include "cwf/request.h"
#include "cwf/response.h"
#include "model/user.h"

class BmiController : public CWF::Controller
{
public:
    void doGet(CWF::Request &request, CWF::Response &response) const override;
};

#endif // BMICONTROLLER_H


text: from django.db.backends.mysql.client import *


text:
'use strict';

require('angular');
require('angular-ui-router');
require('angular-ui-bootstrap');
var jsonld = require('jsonld');

angular.module('app', [
    'app.config',
    'ui.router',
    'ui.bootstrap'
]);

require('../tmp/templateCache.js');
require('../tmp/config.js');
require('./routes/app.js');
require('./components/search.js');
require('./components/results-area.js');
require('./components/spinner.js');
require('./services/data.js');
require('./services/transform.js');
require('./services/url.js');


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="com.app.demos.theme.login" parent="android:Theme.Light">
		<item name="android:windowNoTitle">true</item>
	</style>
	<style name="com.app.demos.theme.light" parent="android:Theme.Light">
		<item name="android:windowNoTitle">true</item>
	</style>
	<style name="com.app.weibo.theme.dialog" parent="android:Theme.Dialog">
		<!--<item name="android:windowFrame">@null</item> -->
		<!--<item name="android:windowIsFloating">true</item> -->
		<!--<item name="android:windowIsTranslucent">false</item> -->
		<item name="android:windowNoTitle">true</item>
		<item name="android:windowBackground">@null</item>
		<!--<item name="android:backgroundDimEnabled">false</item> -->
	</style>
	<style name="loading_small" parent="@android:style/Widget.ProgressBar.Small">
		<item name="android:indeterminateDrawable">@anim/loading</item>
		<item name="android:layout_width">21dip</item>
		<item name="android:layout_height">21dip</item>
		<item name="android:layout_gravity">center_vertical</item>
	</style>
    <style name="widget_listview">
        <item name="android:layout_width">fill_parent</item>
   		<item name="android:layout_height">fill_parent</item>
       	<item name="android:layout_weight">1</item>
       	<item name="android:listSelector">@drawable/listview_item_selector</item>
       	<item name="android:divider">@drawable/listview_divider_line</item>
       	<item name="android:dividerHeight">1.0dip</item>
       	<item name="android:fadingEdge">none</item>
       	<item name="android:scrollingCache">false</item>
    </style>
    <style name="square_listview">
        <item name="android:layout_width">fill_parent</item>
   		<item name="android:layout_height">fill_parent</item>
       	<item name="android:layout_weight">1</item>
       	<item name="android:listSelector">@drawable/listview_item_selector</item>
       	<item name="android:divider">#00ffffff</item>
       	<item name="android:dividerHeight">1.0dip</item>
       	<item name="android:fadingEdge">none</item>
       	<item name="android:scrollingCache">false</item>
    </style>
</resources>


text:
function init {
  RELEASE_DIR=$HOME/ionic-release
  ../clone/clone.sh --repository="driftyco/ionic" \
    --directory="$RELEASE_DIR" \
    --branch="master"
}

echo "##### "
echo "##### release/publish.sh"
echo "#####"

function run {
  cd ../..

  node_modules/.bin/gulp build --release --dist="$RELEASE_DIR/release"
  node_modules/.bin/gulp changelog --dest="$RELEASE_DIR/CHANGELOG.md"

  cp package.json $RELEASE_DIR

  cd $RELEASE_DIR

  VERSION=$(readJsonProp "package.json" "version")
  CODENAME=$(readJsonProp "package.json" "codename")

  replaceJsonProp "bower.json" "version" "$VERSION"
  replaceJsonProp "component.json" "version" "$VERSION"

  replaceJsonProp "bower.json" "codename" "$CODENAME"
  replaceJsonProp "component.json" "codename" "$CODENAME"

  git add -A
  git commit -am "release: v$VERSION \"$CODENAME\""
  git tag -f -m v$VERSION v$VERSION

  git push -q origin master
  git push -q origin v$VERSION

  echo "-- Published ionic v$VERSION \"$CODENAME\" successfully!"
}

source $(dirname $0)/../utils.inc


text:
		<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="stylesheet" type="text/css" href="/css/socialicious.css">
		<link rel="stylesheet" type="text/css" href="/css/main.css">
		<link rel="stylesheet" type="text/css" href="/css/monokai.css">
		<link href="/blog/rss.xml" rel="alternate" type="application/rss+xml" title="Title" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Another boy was sliding down the hallway - Title</title>

		Just
		Me

Another boy was sliding down the hallway

Horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses, horses.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Also some foxes jumped over stuff mate

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			Saigon Jekyll Theme - 2016


text:
"""Training script for the WaveNet network."""

from __future__ import print_function

import argparse
from datetime import datetime
import json
import os
import sys
import time

import tensorflow as tf

from wavenet import WaveNetModel, TextReader

BATCH_SIZE = 1
DATA_DIRECTORY = './data'
LOGDIR_ROOT = './logdir'
CHECKPOINT_EVERY = 500
NUM_STEPS = 4000
LEARNING_RATE = 0.001
WAVENET_PARAMS = './wavenet_params.json'
STARTED_DATESTRING = "{0:%Y-%m-%dT%H-%M-%S}".format(datetime.now())
SAMPLE_SIZE = 1000
L2_REGULARIZATION_STRENGTH = 0

def get_arguments():
    parser = argparse.ArgumentParser(description='WaveNet example network')
    parser.add_argument('--batch_size', type=int, default=BATCH_SIZE,
                        help='How many wav files to process at once.')
    parser.add_argument('--data_dir', type=str, default=DATA_DIRECTORY,
                        help='The directory containing the VCTK corpus.')
    parser.add_argument('--logdir', type=str, default=None,
                        help='Directory in which to store the logging '
                        'information for TensorBoard. '
                        'If the model already exists, it will restore '
                        'the state and will continue training. '
                        'Cannot use with --logdir_root and --restore_from.')
    parser.add_argument('--logdir_root', type=str, default=None,
                        help='Root directory to place the logging '
                        'output and generated model. These are stored '
                        'under the dated subdirectory of --logdir_root. '
                        'Cannot use with --logdir.')
    parser.add_argument('--restore_from', type=str, default=None,
                        help='Directory in which to restore the model from. '
                        'This creates the new model under the dated directory '
                        'in --logdir_root. '
                        'Cannot use with --logdir.')
    parser.add_argument('--checkpoint_every', type=int, default=CHECKPOINT_EVERY,
                        help='How many steps to save each checkpoint after')
    parser.add_argument('--num_steps', type=int, default=NUM_STEPS,
                        help='Number of training steps.')
    parser.add_argument('--learning_rate', type=float, default=LEARNING_RATE,
                        help='Learning rate for training.')
    parser.add_argument('--wavenet_params', type=str, default=WAVENET_PARAMS,
                        help='JSON file with the network parameters.')
    parser.add_argument('--sample_size', type=int, default=SAMPLE_SIZE,
                        help='Concatenate and cut text samples to this many '
                        'samples.')
    parser.add_argument('--l2_regularization_strength', type=float,
                        default=L2_REGULARIZATION_STRENGTH,
                        help='Coefficient in the L2 regularization. '
                        'Disabled by default')
    return parser.parse_args()

def save(saver, sess, logdir, step):
    model_name = 'model.ckpt'
    checkpoint_path = os.path.join(logdir, model_name)
    print('Storing checkpoint to {} ...'.format(logdir), end="")
    sys.stdout.flush()

    if not os.path.exists(logdir):
        os.makedirs(logdir)

    saver.save(sess, checkpoint_path, global_step=step)
    print(' Done.')

def load(saver, sess, logdir):
    print("Trying to restore saved checkpoints from {} ...".format(logdir),
          end="")

    ckpt = tf.train.get_checkpoint_state(logdir)
    if ckpt:
        print("  Checkpoint found: {}".format(ckpt.model_checkpoint_path))
        global_step = int(ckpt.model_checkpoint_path
                          .split('/')[-1]
                          .split('-')[-1])
        print("  Global step was: {}".format(global_step))
        print("  Restoring...", end="")
        saver.restore(sess, ckpt.model_checkpoint_path)
        print(" Done.")
        return global_step
    else:
        print(" No checkpoint found.")
        return None

def get_default_logdir(logdir_root):
    logdir = os.path.join(logdir_root, 'train', STARTED_DATESTRING)
    return logdir

def validate_directories(args):
    """Validate and arrange directory related arguments."""

    # Validation
    if args.logdir and args.logdir_root:
        raise ValueError("--logdir and --logdir_root cannot be "
                         "specified at the same time.")

    if args.logdir and args.restore_from:
        raise ValueError(
            "--logdir and --restore_from cannot be specified at the same "
            "time. This is to keep your previous model from unexpected "
            "overwrites.\n"
            "Use --logdir_root to specify the root of the directory which "
            "will be automatically created with current date and time, or use "
            "only --logdir to just continue the training from the last "
            "checkpoint.")

    # Arrangement
    logdir_root = args.logdir_root
    if logdir_root is None:
        logdir_root = LOGDIR_ROOT

    logdir = args.logdir
    if logdir is None:
        logdir = get_default_logdir(logdir_root)
        print('Using default logdir: {}'.format(logdir))

    restore_from = args.restore_from
    if restore_from is None:
        # args.logdir and args.restore_from are exclusive,
        # so it is guaranteed the logdir here is newly created.
        restore_from = logdir

    return {
        'logdir': logdir,
        'logdir_root': args.logdir_root,
        'restore_from': restore_from
    }

def main():
    args = get_arguments()

    try:
        directories = validate_directories(args)
    except ValueError as e:
        print("Some arguments are wrong:")
        print(str(e))
        return

    logdir = directories['logdir']
    restore_from = directories['restore_from']

    # Even if we restored the model, we will treat it as new training
    # if the trained model is written into an arbitrary location.
    is_overwritten_training = logdir != restore_from

    with open(args.wavenet_params, 'r') as f:
        wavenet_params = json.load(f)

    # Create coordinator.
    coord = tf.train.Coordinator()

    # Load raw text.
    with tf.name_scope('create_inputs'):
        reader = TextReader(
            args.data_dir,
            coord,
            sample_size=args.sample_size)
        text_batch = reader.dequeue(args.batch_size)

    # Create network.
    net = WaveNetModel(
        batch_size=args.batch_size,
        dilations=wavenet_params["dilations"],
        filter_width=wavenet_params["filter_width"],
        residual_channels=wavenet_params["residual_channels"],
        dilation_channels=wavenet_params["dilation_channels"],
        skip_channels=wavenet_params["skip_channels"],
        quantization_channels=wavenet_params["quantization_channels"],
        use_biases=wavenet_params["use_biases"])
    if args.l2_regularization_strength == 0:
        args.l2_regularization_strength = None
    loss = net.loss(text_batch, args.l2_regularization_strength)
    optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate)
    trainable = tf.trainable_variables()
    optim = optimizer.minimize(loss, var_list=trainable)

    # Set up session
    sess = tf.Session(config=tf.ConfigProto(log_device_placement=False))
    init = tf.initialize_all_variables()
    sess.run(init)

    # Saver for storing checkpoints of the model.
    saver = tf.train.Saver()

    try:
        saved_global_step = load(saver, sess, restore_from)
        if is_overwritten_training or saved_global_step is None:
            # The first training step will be saved_global_step + 1,
            # therefore we put -1 here for new or overwritten trainings.
            saved_global_step = -1

    except:
        print("Something went wrong while restoring checkpoint. "
              "We will terminate training to avoid accidentally overwriting "
              "the previous model.")
        raise

    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    reader.start_threads(sess)

    try:
        last_saved_step = saved_global_step
        for step in range(saved_global_step + 1, args.num_steps):
            start_time = time.time()
            loss_value, _ = sess.run([loss, optim])
            print("fin step", step)
            duration = time.time() - start_time
            print('step {:d} - loss = {:.3f}, ({:.3f} sec/step)'
                  .format(step, loss_value, duration))

            if step % args.checkpoint_every == 0:
                save(saver, sess, logdir, step)
                last_saved_step = step

    except KeyboardInterrupt:
        # Introduce a line break after ^C is displayed so save message
        # is on its own line.
        print()
    finally:
        if step > last_saved_step:
            save(saver, sess, logdir, step)
        coord.request_stop()
        coord.join(threads)

if __name__ == '__main__':
    main()


text:
<nav style="display: flex; justify-content: center; align-items: center;">
  <button>Prev</button>
  <button>Next</button>
</nav>


text:
"""Constants for interpreting the results of os.statvfs() and os.fstatvfs()."""
from warnings import warnpy3k
warnpy3k("the statvfs module has been removed in Python 3.0", stacklevel=2)
del warnpy3k

# Indices for statvfs struct members in the tuple returned by
# os.statvfs() and os.fstatvfs().

F_BSIZE   = 0           # Preferred file system block size
F_FRSIZE  = 1           # Fundamental file system block size
F_BLOCKS  = 2           # Total number of file system blocks (FRSIZE)
F_BFREE   = 3           # Total number of free blocks
F_BAVAIL  = 4           # Free blocks available to non-superuser
F_FILES   = 5           # Total number of file nodes
F_FFREE   = 6           # Total number of free file nodes
F_FAVAIL  = 7           # Free nodes available to non-superuser
F_FLAG    = 8           # Flags (see your local statvfs man page)
F_NAMEMAX = 9           # Maximum file name length


text:
#include "BitParameter.h"
#include "BitParameterType.h"
#include "ParameterAccessContext.h"
#include "ConfigurationAccessContext.h"
#include "ParameterBlackboard.h"
#include "BitParameterBlock.h"
#include "BitwiseAreaConfiguration.h"

#define base CBaseParameter

using std::string;

CBitParameter::CBitParameter(const string& strName, const CTypeElement* pTypeElement) : base(strName, pTypeElement)
{
}

// Type
CInstanceConfigurableElement::Type CBitParameter::getType() const
{
    return EBitParameter;
}

// Size
uint32_t CBitParameter::getBelongingBlockSize() const
{
    return static_cast<const CBitParameterBlock*>(getParent())->getSize();
}

// Instantiation, allocation
uint32_t CBitParameter::getFootPrint() const
{
    // Allocation done at parent level
    return 0;
}

// Actual parameter access (tuning)
bool CBitParameter::doSetValue(const string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const
{
    return doSet(strValue, uiOffset, parameterAccessContext);
}

void CBitParameter::doGetValue(string& strValue, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const
{
    doGet(strValue, uiOffset, parameterAccessContext);
}

/// Value access
// Boolean access
bool CBitParameter::accessAsBoolean(bool& bValue, bool bSet, CParameterAccessContext& parameterAccessContext) const
{
    // Check boolean access validity here
    if (static_cast<const CBitParameterType*>(getTypeElement())->getBitSize() != 1) {

        parameterAccessContext.setError("Type mismatch");
        appendParameterPathToError(parameterAccessContext);

        return false;
    }

    // Rely on integer access
    uint64_t uiValue;

    if (bSet) {

        uiValue = bValue;
    }

    if (!accessAsInteger(uiValue, bSet, parameterAccessContext)) {

        return false;
    }

    if (!bSet) {

        bValue = uiValue != 0;
    }

    return true;
}

// Integer Access
bool CBitParameter::accessAsInteger(uint64_t& uiValue, bool bSet, CParameterAccessContext& parameterAccessContext) const
{
    uint32_t uiOffset = getOffset();

    if (bSet) {

        // Set Value
        if (!doSet(uiValue, uiOffset, parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
        // Synchronize
        if (!sync(parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    } else {

        // Convert
        doGet(uiValue, uiOffset, parameterAccessContext);
    }
    return true;
}

template <typename type>
bool CBitParameter::doSet(type value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const
{
    uint64_t uiData = 0;

    // Read/modify/write
    CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->readInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem());

    // Convert
    if (!static_cast<const CBitParameterType*>(getTypeElement())->toBlackboard(value, uiData, parameterAccessContext)) {

        return false;
    }
    // Write blackboard
    pBlackboard->writeInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem());

    return true;
}

template <typename type>
void CBitParameter::doGet(type& value, uint32_t uiOffset, CParameterAccessContext& parameterAccessContext) const
{
    uint64_t uiData = 0;

    // Read blackboard
    const CParameterBlackboard* pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->readInteger(&uiData, getBelongingBlockSize(), uiOffset, parameterAccessContext.isBigEndianSubsystem());

    // Convert
    static_cast<const CBitParameterType*>(getTypeElement())->fromBlackboard(value, uiData, parameterAccessContext);
}

// AreaConfiguration creation
CAreaConfiguration* CBitParameter::createAreaConfiguration(const CSyncerSet* pSyncerSet) const
{
    return new CBitwiseAreaConfiguration(this, pSyncerSet);
}

// Access from area configuration
uint64_t CBitParameter::merge(uint64_t uiOriginData, uint64_t uiNewData) const
{
    // Convert
    return static_cast<const CBitParameterType*>(getTypeElement())->merge(uiOriginData, uiNewData);
}


text:
class User < ActiveRecord::Base
  has_many :posts

  attr_accessible :email
end


text:
  /**
   * 文件上传,HTML5 ONLY
   *
   * @module Upload
   */

  'use strict';

  var Widget = require('pandora-widget');

  /**
   * Progress
   *
   * @class Progress
   * @extends {Class} Widget
   * @constructor
   */
  var Progress = Widget.extend({

    type: 'Progress',

    defaults: {
      classPrefix: 'progress wait'
    },

    setup: function() {
      this.render();
    },

    set: function(progress) {
      this.element
        .removeClass('wait done fail')
        .width(progress * 100 + '%');
    },

    wait: function(text) {
      this.element
        .removeClass('done fail')
        .addClass('wait')
        .text(text);
    },

    done: function(text) {
      this.element
        .removeClass('wait fail')
        .addClass('done')
        .text(text);
    },

    fail: function(text) {
      this.element
        .removeClass('wait done')
        .addClass('fail')
        .text(text);
    }

  });

  module.exports = Progress;


text:
""" Contains chatbot functionality.
"""

import requests
import re
import random
import config as c
import logging
import functools
logger = logging.getLogger(__name__)

__registered_handlers = {}

def regex_handler(regex, regex_opts):
    """ Internal regex decorator maker.
    """
    def regex_handler_decorator(func):
        """ Internal decorator for regex handlers
        """
        @functools.wraps(func)
        def wrapped(message):
            """ Apply a regex against the message's text.
                If it matches, call the decorated func passing
                the original message and the regex's matched groups.
                Return None if no match.
            """
            match_obj = re.search(regex, message.text, regex_opts)
            if match_obj:
                result = func(message, match_obj.groups())
                if result:
                    return result
            return None

        __registered_handlers[regex] = wrapped
        return wrapped

    return regex_handler_decorator

@regex_handler(r'prokrast', re.I)
def _prokrast(message, groups):
    """ Return a random reddit image link.
    """
    logger.debug("getting link")

    headers = {'User-Agent': 'prokrastibot/1.0'}
    subreddit = {
        True: 'http://www.reddit.com/r/funny/rising.json',
        False: 'http://www.reddit.com/r/Motivational/rising.json'
    }[random.randint(1, 10) > 1]

    data = requests.get(subreddit, headers=headers).json()
    posts = data['data']['children']
    if len(posts) > 1:
        i = random.randint(0, len(posts)-1)
        title = posts[i]['data']['title']
        url = posts[i]['data']['url']
        logger.debug("title: %s url: %s", title, url)

        return [{'text': url}, {'text': title}]
    else:
        return []

@regex_handler(r'^wo ist (.+)', re.I)
def _find_position(message, groups):
    """Lookup an address at Google Maps and return the result
        as dict.
    """
    logger.debug('_find_position: %s, %s', message, groups)

    if len(groups) > 0:
        address = groups[0].strip().lower().replace(' ', '+')
        params = {
            'address': address,
            'sensor': 'false'
        }

        req = requests.post(c.config['gmaps_url'], params=params).json()

        if req['status'] == 'OK':
            formatted_address = req['results'][0]['formatted_address']
            location = req['results'][0]['geometry']['location']
            lat, lng = location['lat'], location['lng']
            return [{
                'text': '',
                'location': {
                    'lat': lat,
                    'lng': lng,
                    'name': formatted_address
                }}]
    return []

@regex_handler(r'^!meme (.+)\|(.+)\|(.*)', re.I)
def _meme(message, groups):
    """Use imgflip to create a meme and return its URL.
    """
    logger.debug('_meme: %s, %s', message, groups)

    if len(groups) > 0:
        meme_id = groups[0].strip().lower().replace(' ', '_')
        if meme_id in c.known_memes:
            params = {
                'template_id': c.known_memes[meme_id],
                'username': c.config['imgflip_username'],
                'password': c.config['imgflip_password'],
                'text0': groups[1] if len(groups) > 1 else '',
                'text1': groups[2] if len(groups) > 2 else '',
            }

            logger.debug("_meme: imgflip meme (%s)", str(params))
            req = requests.post(
                c.config['imgflip_caption_image'], params=params).json()
            if req['success']:
                return [{'text': req['data']['url']}]
    return []

@regex_handler(r'^(y u no) (.+)', re.I)
def _y_u_no(message, groups):
    """Use imgflip to create a Y U NO meme and return its URL.
    """
    meme_id = c.known_memes['y_u_no']
    params = {
        'template_id': meme_id,
        'username': c.config['imgflip_username'],
        'password': c.config['imgflip_password'],
        'text0': groups[0] if len(groups) > 0 else '',
        'text1': groups[1] if len(groups) > 1 else '',
    }

    req = requests.post(
        c.config['imgflip_caption_image'], params=params).json()

    if req['success']:
        return [{'text': req['data']['url']}]
    else:
        return []

@regex_handler(r'^!help', re.I)
def _bang_help(message, groups):
    """Return a help text for all bang commands.
    """
    return [
        {'text': '!memelist: Bekannte Memes'},
        {'text': '!meme <id>|text0|text1: Erzeugt das Meme <id> mit den'
                 'angegebenen Texten. Die | sind mandatorisch, auch wenn'
                 ' nur text0 übergeben werden soll.'}
    ]

@regex_handler(r'^!memelist', re.I)
def _bang_memelist(message, groups):
    """Return the URL of a list of supported memes.
    """
    return [
        {'text': 'https://dl.dropboxusercontent.com/'
                 'u/2530719/memelist.html'}
    ]

@regex_handler(r'^awesome', re.I)
def _awesome(message, groups):
    """Tell everyone they're awesome!
    """
    return [
        {'text': 'http://ownyourawesome.files.wordpress.com/'
                 '2012/09/awesome-meter.jpg'}
    ]

@regex_handler(r'kann[\w ]*nicht', re.I)
def _kann_nicht(message, groups):
    """Return a certain quip referring to a specific user.
    """
    return [
        {'text': 'kann-nicht wohnt in der will-nicht-straße,'
                 ' {}'.format(message.sender)}
    ]

def answer(message):
    """ Lookup and execute the first matching handler for a message.
        Return the result.
    """
    for regex, handler in __registered_handlers.items():
        result = handler(message)
        if result:
            return result
    return []


text:
<Record>
<Term>Perastine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Histamine-1 Receptor Antagonist</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Histamine-1 Receptor Antagonist/Perastine</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Histamine-1 Receptor Antagonist</BroaderTerm>
<BroaderTerm>Perastine</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>PERASTINE</Synonym>
<Synonym>Perastine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
<!DOCTYPE html>
<html>
<head>
	<title>Seriously.js Camera Demo</title>
</head>
<body>
	<!-- page content goes here -->

	<video id="source" width="320" height="240"></video>
	<canvas id="target" width="640" height="480"></canvas>

	<script src="../../seriously.js"></script>
	<script src="../../effects/seriously.edge.js"></script>
	<script>
	(function() {
		//main code goes here

		// declare our variables
		var seriously, // the main object that holds the entire composition
			gUM, // will reference getUserMedia or whatever browser-prefixed version we can find
			URL, // will reference window.URL or whatever browser-prefixed version we can find
			video, // video element
			source, // wrapper object for source video
			edge, // edge detection effect
			target; // a wrapper object for our target canvas

		// detect browser-prefixed getUserMedia
		gUM = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

		// detect browser-prefixed window.URL
		URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

		// grab the video element
		video = document.getElementById('source');

		// construct our seriously object
		seriously = new Seriously();

		// grab the video stream
		if (gUM) {
			gUM.call(navigator,
				{video: true},
				// success callback
				function(stream){
					// check for firefox
					if (video.mozCaptureStream) {
						video.mozSrcObject = stream;
					} else {
						video.src = (URL && URL.createObjectURL(stream)) || stream;
					}
					video.play();
				},
				// error callback
				function(error){
					console.log('An error occurred: ' + (error.message || error.name));
				}
			);
		}

		// wait until video is ready
		video.addEventListener('canplay', function(){

			// time to get serious
			source = seriously.source(video);
			target = seriously.target('#target');
			edge = seriously.effect('edge');

			// connect all our nodes in the right order
			edge.source = source;
			target.source = edge;

			seriously.go();
		});

	}());
	</script>
</body>
</html>


text:
package tubame.portability.util;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;

/**
 * Utility class to color (Color) management.

 */
public class ColorUtil {

    /**
     * Display
     */
    private static final Display DISPLAY = PluginUtil.getStandardDisplay();

    /**
     * Color (red)
     */
    private static final Color RED = new Color(DISPLAY, 255, 0, 0);;
    /**
     * Color (blue)
     */
    private static final Color BLUE = new Color(DISPLAY, 0, 0, 255);;
    /**
     * Color (yellow-green)
     */
    private static final Color YELLOW_GREEN = new Color(DISPLAY, 187, 241, 186);;
    /**
     * Color (white)
     */
    private static final Color WHITE = new Color(DISPLAY, 255, 255, 255);
    /**
     * Color (green)
     */
    private static final Color GREEN = new Color(DISPLAY, 68, 155, 4);
    /**
     * Color (green)
     */
    private static final Color POP_GREEN = new Color(DISPLAY, 100, 225, 6);
    /**
     * Check items OKColor
     */
    private static final Color OK_STATUS = new Color(DISPLAY, 255, 102, 152);
    /**
     * Check items NGColor
     */
    private static final Color NG_STATUS = new Color(DISPLAY, 180, 177, 179);

    /**
     * Constructor.

     * Another class can not be instantiated.

     *
     */
    private ColorUtil() {
        // no operation
    }

    /**
     * Get the red.

     *
     * @return Red
     */
    public static Color getRed() {
        return ColorUtil.RED;
    }

    /**
     * Get the blue.

     *
     * @return Blue
     */
    public static Color getBule() {
        return ColorUtil.BLUE;
    }

    /**
     * Get yellow-green.

     *
     * @return Yellow-green
     */
    public static Color getYellowGreen() {
        return ColorUtil.YELLOW_GREEN;
    }

    /**
     * Get white.

     *
     * @return White
     */
    public static Color getWhite() {
        return ColorUtil.WHITE;
    }

    /**
     * Get the green.

     *
     * @return Green
     */
    public static Color getGreen() {
        return ColorUtil.GREEN;
    }

    /**
     * Get the green.

     *
     * @return Green
     */
    public static Color getPopGreen() {
        return ColorUtil.POP_GREEN;
    }

    /**
     * Get the color of the OK status of confirmation item.

     *
     * @return Color OK status
     */
    public static Color getConfirmItemStatusOkColor() {
        return ColorUtil.OK_STATUS;
    }

    /**
     * Get the color of the NG status of confirmation item.

     *
     * @return Color NG status
     */
    public static Color getConfirmItemStatusNgColor() {
        return ColorUtil.NG_STATUS;
    }

    /**
     * Get the color of the unconfirmed status of confirmation item.

     *
     * @return Color unconfirmed status
     */
    public static Color getConfirmItemStatusNonColor() {
        return ColorUtil.WHITE;
    }
}


text:
install:
	@npm install

server:
	@./node_modules/.bin/serv .


text:
TEST(BlacklistTest, Generic) {
  // Get path relative to test data dir.
  FilePath input;
  PathService::Get(chrome::DIR_TEST_DATA, &input);
  input = input.AppendASCII("blacklist_small.pbr");

  Blacklist blacklist;
  ASSERT_TRUE(BlacklistIO::ReadBinary(&blacklist, input));

  Blacklist::EntryList entries(blacklist.entries_begin(),
                               blacklist.entries_end());

  ASSERT_EQ(5U, entries.size());

  EXPECT_EQ(Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
            entries[0]->attributes());
  EXPECT_TRUE(entries[0]->MatchesType("application/x-shockwave-flash"));
  EXPECT_FALSE(entries[0]->MatchesType("image/jpeg"));
  EXPECT_EQ("@", entries[0]->pattern());

  // All entries include global attributes.
  // NOTE: Silly bitwise-or with zero to workaround a Mac compiler bug.
  EXPECT_EQ(Blacklist::kBlockUnsecure|0, entries[1]->attributes());
  EXPECT_FALSE(entries[1]->MatchesType("application/x-shockwave-flash"));
  EXPECT_FALSE(entries[1]->MatchesType("image/jpeg"));
  EXPECT_EQ("@poor-security-site.com", entries[1]->pattern());

  EXPECT_EQ(Blacklist::kDontSendCookies|Blacklist::kDontStoreCookies,
            entries[2]->attributes());
  EXPECT_FALSE(entries[2]->MatchesType("application/x-shockwave-flash"));
  EXPECT_FALSE(entries[2]->MatchesType("image/jpeg"));
  EXPECT_EQ("@.ad-serving-place.com", entries[2]->pattern());

  EXPECT_EQ(Blacklist::kDontSendUserAgent|Blacklist::kDontSendReferrer,
            entries[3]->attributes());
  EXPECT_FALSE(entries[3]->MatchesType("application/x-shockwave-flash"));
  EXPECT_FALSE(entries[3]->MatchesType("image/jpeg"));
  EXPECT_EQ("www.site.com/anonymous/folder/@", entries[3]->pattern());

  // NOTE: Silly bitwise-or with zero to workaround a Mac compiler bug.
  EXPECT_EQ(Blacklist::kBlockAll|0, entries[4]->attributes());
  EXPECT_FALSE(entries[4]->MatchesType("application/x-shockwave-flash"));
  EXPECT_FALSE(entries[4]->MatchesType("image/jpeg"));
  EXPECT_EQ("www.site.com/bad/url", entries[4]->pattern());

  Blacklist::ProviderList providers(blacklist.providers_begin(),
                                    blacklist.providers_end());

  ASSERT_EQ(1U, providers.size());
  EXPECT_EQ("Sample", providers[0]->name());
  EXPECT_EQ("http://www.google.com", providers[0]->url());

  // No match for chrome, about or empty URLs.
  EXPECT_FALSE(blacklist.findMatch(GURL()));
  EXPECT_FALSE(blacklist.findMatch(GURL("chrome://new-tab")));
  EXPECT_FALSE(blacklist.findMatch(GURL("about:blank")));

  // Expected rule matches.
  Blacklist::Match* match;
  match = blacklist.findMatch(GURL("http://www.google.com"));
  EXPECT_TRUE(match);
  if (match) {
    EXPECT_EQ(Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
              match->attributes());
    EXPECT_EQ(1U, match->entries().size());
    delete match;
  }

  match = blacklist.findMatch(GURL("http://www.site.com/bad/url"));
  EXPECT_TRUE(match);
  if (match) {
    EXPECT_EQ(Blacklist::kBlockAll|
              Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
              match->attributes());
    EXPECT_EQ(2U, match->entries().size());
    delete match;
  }

  match = blacklist.findMatch(GURL("http://www.site.com/anonymous"));
  EXPECT_TRUE(match);
  if (match) {
    EXPECT_EQ(Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
              match->attributes());
    EXPECT_EQ(1U, match->entries().size());
    delete match;
  }

  match = blacklist.findMatch(GURL("http://www.site.com/anonymous/folder"));
  EXPECT_TRUE(match);
  if (match) {
    EXPECT_EQ(Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
      match->attributes());
    EXPECT_EQ(1U, match->entries().size());
    delete match;
  }

  match = blacklist.findMatch(
      GURL("http://www.site.com/anonymous/folder/subfolder"));
  EXPECT_TRUE(match);
  if (match) {
    EXPECT_EQ(Blacklist::kDontSendUserAgent|Blacklist::kDontSendReferrer|
              Blacklist::kBlockByType|Blacklist::kDontPersistCookies,
              match->attributes());
    EXPECT_EQ(2U, match->entries().size());
    delete match;
  }

  // StripCookieExpiry Tests
  std::string cookie1(
      "PREF=ID=14a549990453e42a:TM=1245183232:LM=1245183232:S=Occ7khRVIEE36Ao5;"
      " expires=Thu, 16-Jun-2011 20:13:52 GMT; path=/; domain=.google.com");
  std::string cookie2(
      "PREF=ID=14a549990453e42a:TM=1245183232:LM=1245183232:S=Occ7khRVIEE36Ao5;"
      " path=/; domain=.google.com");
  std::string cookie3(
    "PREF=ID=14a549990453e42a:TM=1245183232:LM=1245183232:S=Occ7khRVIEE36Ao5;"
    " expires=Thu, 17-Jun-2011 02:13:52 GMT; path=/; domain=.google.com");
  std::string cookie4("E=MC^2; path=relative;  expires=never;");
  std::string cookie5("E=MC^2; path=relative;");

  // No expiry, should be equal to itself after stripping.
  EXPECT_EQ(cookie2, Blacklist::StripCookieExpiry(cookie2));
  EXPECT_EQ(cookie5, Blacklist::StripCookieExpiry(cookie5));

  // Expiry, should be equal to non-expiry version after stripping.
  EXPECT_EQ(cookie2, Blacklist::StripCookieExpiry(cookie1));
  EXPECT_EQ(cookie5, Blacklist::StripCookieExpiry(cookie4));

  // Same cookie other than expiry should be same after stripping.
  EXPECT_EQ(Blacklist::StripCookieExpiry(cookie2),
            Blacklist::StripCookieExpiry(cookie3));

  // Edge cases.
  std::string invalid("#$%^&*()_+");
  EXPECT_EQ(invalid, Blacklist::StripCookieExpiry(invalid));
  EXPECT_EQ(std::string(), Blacklist::StripCookieExpiry(std::string()));

  // StripCookies Test. Note that "\r\n" line terminators are used
  // because the underlying net util uniformizes those when stripping
  // headers.
  std::string header1("Host: www.example.com\r\n");
  std::string header2("Upgrade: TLS/1.0, HTTP/1.1\r\n"
                      "Connection: Upgrade\r\n");
  std::string header3("Date: Mon, 12 Mar 2001 19:20:33 GMT\r\n"
                      "Expires: Mon, 12 Mar 2001 19:20:33 GMT\r\n"
                      "Content-Type: text/html\r\n"
                      "Set-Cookie: B=460soc0taq8c1&b=2; "
                      "expires=Thu, 15 Apr 2010 20:00:00 GMT; path=/;\r\n");
  std::string header4("Date: Mon, 12 Mar 2001 19:20:33 GMT\r\n"
                      "Expires: Mon, 12 Mar 2001 19:20:33 GMT\r\n"
                      "Content-Type: text/html\r\n");

  EXPECT_TRUE(header1 == Blacklist::StripCookies(header1));
  EXPECT_TRUE(header2 == Blacklist::StripCookies(header2));
  EXPECT_TRUE(header4 == Blacklist::StripCookies(header3));
}

TEST(BlacklistTest, PatternMatch) {
  // @ matches all but empty strings.
  EXPECT_TRUE(Blacklist::Matches("@", "foo.com"));
  EXPECT_TRUE(Blacklist::Matches("@", "path"));
  EXPECT_TRUE(Blacklist::Matches("@", "foo.com/path"));
  EXPECT_TRUE(Blacklist::Matches("@", "x"));
  EXPECT_FALSE(Blacklist::Matches("@", ""));
  EXPECT_FALSE(Blacklist::Matches("@", std::string()));

  // Prefix match.
  EXPECT_TRUE(Blacklist::Matches("prefix@", "prefix.com"));
  EXPECT_TRUE(Blacklist::Matches("prefix@", "prefix.com/path"));
  EXPECT_TRUE(Blacklist::Matches("prefix@", "prefix/path"));
  EXPECT_TRUE(Blacklist::Matches("prefix@", "prefix/prefix"));
  EXPECT_FALSE(Blacklist::Matches("prefix@", "prefix"));
  EXPECT_FALSE(Blacklist::Matches("prefix@", "Xprefix"));
  EXPECT_FALSE(Blacklist::Matches("prefix@", "Y.Xprefix"));
  EXPECT_FALSE(Blacklist::Matches("prefix@", "Y/Xprefix"));

  // Postfix match.
  EXPECT_TRUE(Blacklist::Matches("@postfix", "something.postfix"));
  EXPECT_TRUE(Blacklist::Matches("@postfix", "something/postfix"));
  EXPECT_TRUE(Blacklist::Matches("@postfix", "foo.com/something/postfix"));
  EXPECT_FALSE(Blacklist::Matches("@postfix", "postfix"));
  EXPECT_FALSE(Blacklist::Matches("@postfix", "postfixZ"));
  EXPECT_FALSE(Blacklist::Matches("@postfix", "postfixZ.Y"));

  // Infix matches.
  EXPECT_TRUE(Blacklist::Matches("@evil@", "www.evil.com"));
  EXPECT_TRUE(Blacklist::Matches("@evil@", "www.evil.com/whatever"));
  EXPECT_TRUE(Blacklist::Matches("@evil@", "www.whatever.com/evilpath"));
  EXPECT_TRUE(Blacklist::Matches("@evil@", "www.evil.whatever.com"));
  EXPECT_FALSE(Blacklist::Matches("@evil@", "evil"));
  EXPECT_FALSE(Blacklist::Matches("@evil@", "evil/"));
  EXPECT_FALSE(Blacklist::Matches("@evil@", "/evil"));

  // Outfix matches.
  EXPECT_TRUE(Blacklist::Matches("really@bad", "really/bad"));
  EXPECT_TRUE(Blacklist::Matches("really@bad", "really.com/bad"));
  EXPECT_TRUE(Blacklist::Matches("really@bad", "really.com/path/bad"));
  EXPECT_TRUE(Blacklist::Matches("really@bad", "really.evil.com/path/bad"));
  EXPECT_FALSE(Blacklist::Matches("really@bad", "really.bad.com"));
  EXPECT_FALSE(Blacklist::Matches("really@bad", "reallybad"));
  EXPECT_FALSE(Blacklist::Matches("really@bad", ".reallybad"));
  EXPECT_FALSE(Blacklist::Matches("really@bad", "reallybad."));
  EXPECT_FALSE(Blacklist::Matches("really@bad", "really.bad."));
  EXPECT_FALSE(Blacklist::Matches("really@bad", ".really.bad"));
}


text:
package frame

import (
	"bytes"
	"encoding/binary"
	"errors"
)

const (
	// HeaderData is a byte for a data frame.
	HeaderData byte = 0x01
	// HeaderAck is a byte for a ack frame.
	HeaderAck = 0x06
	// HeaderNak is a byte for a nak frame.
	HeaderNak = 0x15
	// HeaderCan is a byte for a can frame.
	HeaderCan = 0x18

	// TypeRequest is for a request frame.
	TypeRequest byte = 0x00
	// TypeResponse is for a response frame.
	TypeResponse = 0x01
)

// Frame contains a frame.
type Frame struct {

	// Header is one of FrameHeader*
	Header byte

	// Length = byte length of all fields, excluding Header and Checksum
	Length byte

	// Type is one of FrameType*
	Type byte

	// Payload is the command id and command payload
	Payload []byte

	// Checksum = 0xff XOR Type XOR Length XOR payload[0] XOR [...payload[n]]
	Checksum byte
}

// NewRequestFrame will build  a new request frame.
func NewRequestFrame(payload []byte) *Frame {
	return &Frame{
		Header:  HeaderData,
		Type:    TypeRequest,
		Payload: payload,
	}
}

// NewNakFrame returns a new  nak frame.
func NewNakFrame() *Frame {
	return &Frame{
		Header: HeaderNak,
	}
}

// NewAckFrame returns a new ack frame.
func NewAckFrame() *Frame {
	return &Frame{
		Header: HeaderAck,
	}
}

// NewCanFrame returns a new can frame.
func NewCanFrame() *Frame {
	return &Frame{
		Header: HeaderCan,
	}
}

// IsRequest checks if the frame is a request frame.
func (z *Frame) IsRequest() bool {
	return z.Type == TypeRequest
}

// IsResponse checks if the frame is a response frame.
func (z *Frame) IsResponse() bool {
	return z.Type == TypeResponse
}

// IsAck returns whether this is an ack frame.
func (z *Frame) IsAck() bool {
	return z.Header == HeaderAck
}

// IsNak returns whether this is an nak frame.
func (z *Frame) IsNak() bool {
	return z.Header == HeaderNak
}

// IsCan returns whether this is an can frame.
func (z *Frame) IsCan() bool {
	return z.Header == HeaderCan
}

// IsData returns whether this is a data frame.
func (z *Frame) IsData() bool {
	return z.Header == HeaderData
}

// CalcChecksum calculates the checksum for this frame, given the current data.
// The Z-Wave checksum is calculated by taking 0xFF XOR Length XOR Type XOR Payload[0:n].
func (z *Frame) CalcChecksum() byte {
	var csum byte = 0xff
	csum ^= z.Length
	csum ^= z.Type

	for i := 0; i < len(z.Payload); i++ {
		csum ^= z.Payload[i]
	}

	return csum
}

// SetChecksum calculates the frame checksum and saves it into the frame.
func (z *Frame) SetChecksum() {
	z.Checksum = z.CalcChecksum()
}

// VerifyChecksum calculates a checksum for the frame and compares it to the
// frame's checksum, returning an error if they do not agree.
func (z *Frame) VerifyChecksum() error {
	if z.Header != HeaderData {
		return nil
	}

	if z.Checksum != z.CalcChecksum() {
		return errors.New("Invalid checksum")
	}

	return nil
}

// MarshalBinary will marshal this frame into a byte slice.
func (z *Frame) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	z.Length = byte(len(z.Payload) + 2)
	z.SetChecksum()

	switch z.Header {
	case HeaderData:
		// Data frames have the whole kit and caboodle
		binary.Write(buf, binary.BigEndian, byte(z.Header))
		binary.Write(buf, binary.BigEndian, byte(z.Length))
		binary.Write(buf, binary.BigEndian, byte(z.Type))
		buf.Write(z.Payload)
		binary.Write(buf, binary.BigEndian, byte(z.Checksum))
	default:
		// Non-data frames are just a single byte
		binary.Write(buf, binary.BigEndian, byte(z.Header))
	}

	return buf.Bytes(), nil
}

// UnmarshalFrame turns a byte slice into a Frame.
func UnmarshalFrame(frame []byte) *Frame {
	if frame[0] != HeaderData {
		return &Frame{
			Header: frame[0],
		}
	}

	return &Frame{
		Header:   frame[0],
		Length:   frame[1],
		Type:     frame[2],
		Payload:  frame[3 : len(frame)-1],
		Checksum: frame[len(frame)-1],
	}
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
	    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	    <meta http-equiv="keywords" content="<%= WCMUtils.getKeywords(currentPage) %>">
    	<meta name="viewport" content="user-scalable=no">

		<title>${properties.jcr:title}</title>
        <output data-sly-call="${clientLib.css @ categories='aemdemo'}" data-sly-unwrap>

        <output data-sly-call="${clientLib.js @ categories='aemdemo'}" data-sly-unwrap>


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.songm.common</groupId>
		<artifactId>songm-common</artifactId>
		<version>1.0</version>
	</parent>
	<artifactId>songm-common-web</artifactId>
	<version>0.1</version>
	<name>${project.artifactId}</name>
	<url>http://maven.apache.org</url>

	<dependencies>
		<dependency>
			<groupId>cn.songm.common</groupId>
			<artifactId>songm-common-utils</artifactId>
		</dependency>
		<dependency>
			<groupId>cn.songm.common</groupId>
			<artifactId>songm-common-service</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
		</dependency>

		<dependency>
		    <groupId>com.thetransactioncompany</groupId>
		    <artifactId>cors-filter</artifactId>
		</dependency>

		<dependency>
		    <groupId>com.thetransactioncompany</groupId>
		    <artifactId>java-property-utils</artifactId>
		</dependency>

		<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
	</dependencies>
</project>


text:
package org.apache.nifi.provenance.index.lucene;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.SearchableFields;
import org.apache.nifi.provenance.search.Query;
import org.apache.nifi.provenance.search.SearchTerm;
import org.apache.nifi.provenance.serialization.StorageSummary;
import org.apache.nifi.util.RingBuffer;

public class LatestEventsPerProcessorQuery implements CachedQuery {
    private static final String COMPONENT_ID_FIELD_NAME = SearchableFields.ComponentID.getSearchableFieldName();
    private final ConcurrentMap<String, RingBuffer<Long>> latestRecords = new ConcurrentHashMap<>();

    @Override
    public void update(final ProvenanceEventRecord event, final StorageSummary storageSummary) {
        final String componentId = event.getComponentId();
        final RingBuffer<Long> ringBuffer = latestRecords.computeIfAbsent(componentId, id -> new RingBuffer<>(1000));
        ringBuffer.add(storageSummary.getEventId());
    }

    @Override
    public Optional<List<Long>> evaluate(final Query query) {
        if (query.getMaxResults() > 1000) {
            // If query max results > 1000 then we know we don't have enough results. So just return empty.
            return Optional.empty();
        }

        final List<SearchTerm> terms = query.getSearchTerms();
        if (terms.size() != 1) {
            return Optional.empty();
        }

        final SearchTerm term = terms.get(0);
        if (!COMPONENT_ID_FIELD_NAME.equals(term.getSearchableField().getSearchableFieldName())) {
            return Optional.empty();
        }

        if (query.getEndDate() != null || query.getStartDate() != null) {
            return Optional.empty();
        }

        final RingBuffer<Long> ringBuffer = latestRecords.get(term.getValue());
        if (ringBuffer == null || ringBuffer.getSize() < query.getMaxResults()) {
            return Optional.empty();
        }

        List<Long> eventIds = ringBuffer.asList();
        if (eventIds.size() > query.getMaxResults()) {
            eventIds = eventIds.subList(0, query.getMaxResults());
        }

        return Optional.of(eventIds);
    }

}


text:
package org.plasma.metamodel.adapter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.plasma.common.exception.ProvisioningException;
import org.plasma.metamodel.Alias;
import org.plasma.metamodel.Class;
import org.plasma.metamodel.ClassRef;
import org.plasma.metamodel.Enumeration;
import org.plasma.metamodel.EnumerationRef;
import org.plasma.metamodel.Model;
import org.plasma.metamodel.Package;
import org.plasma.metamodel.Property;

public class ModelAdapter implements ProvisioningModel {
  private static Log log = LogFactory.getLog(ModelAdapter.class);

  private Model model;
  private Map<String, TypeAdapter> typeMap = new HashMap<String, TypeAdapter>();
  private Map<String, TypeAdapter> physicalNameTypeMap = new HashMap<String, TypeAdapter>();
  private List<Package> leafPackages = new ArrayList<Package>();
  private List<Package> allPackages = new ArrayList<Package>();
  private Map<TypeAdapter, Package> packageTypeMap = new HashMap<TypeAdapter, Package>();

  @SuppressWarnings("unused")
  private ModelAdapter() {
  }

  public ModelAdapter(Model model) {
    this.model = model;
    construct();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.plasma.provisioning.adapter.MetamodelAdapter#getModel()
   */
  @Override
  public Model getModel() {
    return model;
  }

  @Override
  public List<Package> getPackages() {
    return Collections.unmodifiableList(this.allPackages);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.plasma.provisioning.adapter.MetamodelAdapter#getLeafPackages()
   */
  @Override
  public List<Package> getLeafPackages() {
    return Collections.unmodifiableList(this.leafPackages);
  }

  @Override
  public Package getPackage(TypeAdapter type) {
    return this.packageTypeMap.get(type);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.plasma.provisioning.adapter.MetamodelAdapter#getTypes()
   */
  @Override
  public Collection<TypeAdapter> getTypes() {
    return typeMap.values();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.plasma.provisioning.adapter.MetamodelAdapter#getTypesArray()
   */
  @Override
  public TypeAdapter[] getTypesArray() {
    TypeAdapter[] result = new TypeAdapter[typeMap.size()];
    typeMap.values().toArray(result);
    return result;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.plasma.provisioning.adapter.MetamodelAdapter#getTypesArray()
   */
  @Override
  public Map<String, TypeAdapter> getTypeMap() {
    return Collections.unmodifiableMap(typeMap);
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.plasma.provisioning.adapter.MetamodelAdapter#findType(java.lang.String)
   */
  @Override
  public TypeAdapter findType(String key) {
    TypeAdapter result = typeMap.get(key);
    return result;
  }

  private void findPackages(Package parent, List<Package> packages) {
    packages.add(parent);
    for (Package childPkg : parent.getPackages()) {
      findPackages(childPkg, packages);
    }
  }

  private void construct() {
    if (log.isDebugEnabled())
      log.debug("constructing...");

    findPackages(this.model, this.allPackages);

    for (Package pkg : this.allPackages)
      if (pkg.getPackages().size() == 0)
        this.leafPackages.add(pkg);

    Map<String, Package> packageMap = new HashMap<>();
    for (Package pkg : this.leafPackages) {
      String key = pkg.getName();
      if (packageMap.containsKey(key))
        throw new PackageNameCollisionException("detected multiple (leaf) packages named '" + key
            + "' within the same provisioning context");
      packageMap.put(key, pkg);
    }
    Map<String, Package> packagePhysicalMap = new HashMap<>();
    for (Package pkg : this.leafPackages) {
      if (pkg.getAlias() != null && pkg.getAlias().getPhysicalName() != null) {
        String physicalName = pkg.getAlias().getPhysicalName();
        String key = physicalName;
        if (packagePhysicalMap.containsKey(key))
          throw new PackageNameCollisionException(
              "detected multiple (leaf) packages with physical name '" + key
                  + "' within the same provisioning context");
        packagePhysicalMap.put(key, pkg);
      }
    }

    for (Package pkg : this.allPackages)
      mapEnumerations(pkg);

    for (Package pkg : this.allPackages)
      mapClasses(pkg);

    for (TypeAdapter adapter : typeMap.values()) {
      if (adapter.getType() instanceof Class) {
        if (log.isDebugEnabled())
          log.debug("constructing class: " + adapter.getKey());
        construct(adapter, null);
      }
    }

    for (TypeAdapter adapter : typeMap.values()) {
      if (adapter.getType() instanceof Class) {
        for (ClassRef baseClassRef : ((Class) adapter.getType()).getSuperClasses()) {
          String key = baseClassRef.getUri() + "#" + baseClassRef.getName();
          TypeAdapter baseAdapter = typeMap.get(key);
          if (baseAdapter == null)
            throw new IllegalStateException("no mapping found for base type: " + key);

          if (log.isDebugEnabled())
            log.debug("construct deep: " + adapter.getKey());
          constructDeep(adapter, baseAdapter);
        }
      }
    }
  }

  private void mapEnumerations(Package pkg) {
    if (log.isDebugEnabled())
      log.debug("mapping enumerations for package " + pkg.getUri() + " (" + pkg.getName() + ")");
    for (Enumeration enm : pkg.getEnumerations()) {
      String key = enm.getUri() + "#" + enm.getName();
      if (log.isDebugEnabled())
        log.debug("mapping enumeration: " + key);
      if (typeMap.get(key) != null)
        throw new TypeNameCollisionException("detected multiple types named '" + enm.getName()
            + "' under the same URI '" + enm.getUri() + "'");
      TypeAdapter adapter = new TypeAdapter(enm);
      this.typeMap.put(key, adapter);
      this.packageTypeMap.put(adapter, pkg);
      if (enm.getAlias() != null && enm.getAlias().getPhysicalName() != null) {
        String physicalName = enm.getAlias().getPhysicalName();
        key = enm.getUri() + "#" + physicalName;
        TypeAdapter existing = physicalNameTypeMap.get(key);
        if (existing != null)
          throw new TypeNameCollisionException("detected multiple types [" + existing.getName()
              + "," + enm.getName() + "] with the same types name '" + physicalName
              + "' under the same URI '" + enm.getUri() + "'");
        this.physicalNameTypeMap.put(key, adapter);
      }
    }
  }

  private void mapClasses(Package pkg) {
    for (Class cls : pkg.getClazzs()) {
      String key = cls.getUri() + "#" + cls.getName();
      if (log.isDebugEnabled())
        log.debug("mapping class: " + key);
      if (typeMap.get(key) != null)
        throw new TypeNameCollisionException("detected multiple types named '" + cls.getName()
            + "' under the same URI '" + cls.getUri() + "'");

      TypeAdapter adapter = new TypeAdapter(cls);
      this.typeMap.put(key, adapter);
      this.packageTypeMap.put(adapter, pkg);
      if (log.isDebugEnabled())
        log.debug("map: " + adapter.getKey());

      if (cls.getAlias() != null && cls.getAlias().getPhysicalName() != null) {
        String physicalName = cls.getAlias().getPhysicalName();
        key = cls.getUri() + "#" + physicalName;
        TypeAdapter existing = physicalNameTypeMap.get(key);
        if (existing != null)
          throw new TypeNameCollisionException("detected multiple types [" + existing.getName()
              + "," + cls.getName() + "] with the same physical name '" + physicalName
              + "' under the same URI '" + cls.getUri() + "'");
        this.physicalNameTypeMap.put(key, adapter);
      }
    }
  }

  private void construct(TypeAdapter adapter, TypeAdapter source) {
    for (Property prop : ((Class) adapter.getType()).getProperties()) {
      if (adapter.getDeclaredProperty(prop.getName()) != null)
        throw new PropertyNameCollisionException(
            "detected multiple properties with the same logical name '" + prop.getName()
                + "' defined for class '" + adapter.getKey()
                + "' the set of logical names for a class " + "must be unique");
      adapter.putDeclaredProperty(prop.getName(), prop);
      adapter.putProperty(prop.getName(), prop); // note: all property
                                                 // collection not declared only
      if (prop.getAlias() != null) {
        Alias alias = prop.getAlias();
        if (alias.getPhysicalName() != null && alias.getPhysicalName().trim().length() > 0) {
          String physicalName = alias.getPhysicalName().trim();
          if (adapter.getAliasedProperty(physicalName) != null)
            throw new PropertyNameCollisionException(
                "detected multiple properties with the same physical name '" + alias
                    + "' defined for class '" + adapter.getKey()
                    + "' the set of physical names for a class " + "must be unique");
          adapter.putAliasedProperty(physicalName, prop);
        }
        if (alias.getLocalName() != null && alias.getLocalName().trim().length() > 0) {
          String localName = prop.getAlias().getLocalName().trim();
          if (adapter.getAliasedProperty(localName) != null)
            throw new PropertyNameCollisionException(
                "detected multiple properties with the same local name '" + alias
                    + "' defined for class '" + adapter.getKey()
                    + "' the set of local names for a class " + "must be unique");
          adapter.putAliasedProperty(localName, prop);
        }
      }
    }
  }

  private void constructDeep(TypeAdapter adapter, TypeAdapter baseAdapter) {

    for (Property prop : ((Class) adapter.getType()).getProperties()) {
      validate(adapter, prop);
    }
    // copy base properties into subclass
    for (Property prop : ((Class) baseAdapter.getType()).getProperties()) {
      if (adapter.getProperty(prop.getName()) != null)
        throw new PropertyNameCollisionException(
            "detected multiple properties with the same logical name '" + prop.getName()
                + "' defined for class '" + adapter.getKey() + "' as well as its superclass '"
                + baseAdapter.getKey() + "' - the set of logical names for a class and "
                + "superclasses must be unique");
      validate(baseAdapter, prop);
      adapter.putProperty(prop.getName(), prop); // note: all property
                                                 // collection not declared only
      if (prop.getAlias() != null && prop.getAlias().getPhysicalName() != null
          && prop.getAlias().getPhysicalName().trim().length() > 0) {
        String alias = prop.getAlias().getPhysicalName().trim();
        if (adapter.getAliasedProperty(alias) != null)
          throw new PropertyNameCollisionException(
              "detected multiple properties with the same physical name '" + alias
                  + "' defined for class '" + adapter.getKey() + "' as well as its superclass '"
                  + baseAdapter.getKey() + "' - the set of logical names for a class and "
                  + "superclasses must be unique");
        adapter.putAliasedProperty(alias, prop);
      }
    }

    for (ClassRef baseClassRef : ((Class) baseAdapter.getType()).getSuperClasses()) {
      String key2 = baseClassRef.getUri() + "#" + baseClassRef.getName();
      TypeAdapter baseTypeAdapter = typeMap.get(key2);
      if (baseTypeAdapter == null)
        throw new IllegalStateException("no mapping found for base type: " + key2);

      constructDeep(adapter, baseTypeAdapter);
    }
  }

  private void validate(TypeAdapter adapter, Property prop) {
    if (prop.getType() instanceof ClassRef) {
      ClassRef ref = (ClassRef) prop.getType();
      String refkey = ref.getUri() + "#" + ref.getName();
      if (typeMap.get(refkey) == null)
        throw new ProvisioningException("invalid type reference detected for property '"
            + adapter.getKey() + "." + prop.getName() + "' no class or enumeration '" + refkey
            + "' is defined");
      if (prop.getOpposite() != null) {
        Class oppositeClass = (Class) typeMap.get(refkey).getType();
        Property oppositeProperty = findPropertyByName(oppositeClass, prop.getOpposite());
        if (oppositeProperty == null)
          throw new ProvisioningException("invalid opposite reference detected for property '"
              + adapter.getKey() + "." + prop.getName() + "' no opposite property '"
              + prop.getOpposite() + "' is defined for class '" + refkey + "'");
      }
    }
    if (prop.getType() instanceof EnumerationRef) {
      EnumerationRef ref = (EnumerationRef) prop.getType();
      String refkey = ref.getUri() + "#" + ref.getName();
      if (typeMap.get(refkey) == null)
        throw new ProvisioningException("invalid type reference detected for property '"
            + prop.getName() + "' defined for class '" + adapter.getKey() + "'");
    }
  }

  private Property findPropertyByName(Class clss, String name) {
    for (Property prop : clss.getProperties()) {
      if (name.equals(prop.getName()))
        return prop;
    }
    return null;
  }

}


text:
package org.apache.hadoop.hbase.regionserver;

import java.io.IOException;
import java.util.List;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;

/**
 * Interface to Map of online regions.  In the  Map, the key is the region's
 * encoded name and the value is an {@link Region} instance.
 */
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
@InterfaceStability.Evolving
public interface OnlineRegions extends Server {
  /**
   * Add to online regions.
   * @param r
   */
  void addToOnlineRegions(final Region r);

  /**
   * This method removes Region corresponding to hri from the Map of onlineRegions.
   *
   * @param r Region to remove.
   * @param destination Destination, if any, null otherwise.
   * @return True if we removed a region from online list.
   */
  boolean removeFromOnlineRegions(final Region r, ServerName destination);

  /**
   * Return {@link Region} instance.
   * Only works if caller is in same context, in same JVM. Region is not
   * serializable.
   * @param encodedRegionName
   * @return Region for the passed encoded encodedRegionName or
   * null if named region is not member of the online regions.
   */
  Region getFromOnlineRegions(String encodedRegionName);

   /**
    * Get all online regions of a table in this RS.
    * @param tableName
    * @return List of Region
    * @throws java.io.IOException
    */
   List<Region> getOnlineRegions(TableName tableName) throws IOException;
}


text:
define([
  'page_config'
],
function (PageConfig) {
  describe('PageConfig', function () {

    var req;
    beforeEach(function () {
      var get = jasmine.createSpy();
      get.plan = function (prop) {
        return {
          assetPath: '/path/to/assets/',
          govukHost: 'www.gov.uk',
          bigScreenBaseURL: 'https://www.performance.service.gov.uk'
        }[prop];
      };
      var headers = jasmine.createSpy();
      headers.plan = function(prop) {
        return {
          'Request-Id': 'a-uuid',
          'GOVUK-Request-Id': '1231234123'
        }[prop];
      };
      req = {
        app: {
          get: get
        },
        get: headers,
        protocol: 'http',
        originalUrl: '/performance/foo'
      };
    });

    describe('getGovUkUrl', function () {
      it('returns the equivalent page location on GOV.UK', function () {
        expect(PageConfig.getGovUkUrl(req)).toEqual('https://www.gov.uk/performance/foo');
      });
    });

    describe('commonConfig', function () {
      it('contains assetPath property', function () {
        var commonConfig = PageConfig.commonConfig(req);
        expect(commonConfig.assetPath).toEqual('/path/to/assets/');
      });
      it('contains bigScreenBaseURL property', function () {
        var commonConfig = PageConfig.commonConfig(req);
        expect(commonConfig.bigScreenBaseURL).toEqual('https://www.performance.service.gov.uk');
      });
      it('contains assetPath property', function () {
        var commonConfig = PageConfig.commonConfig(req);
        expect(commonConfig.url).toEqual('/performance/foo');
      });
      it('contains requestId property', function() {
        var commonConfig = PageConfig.commonConfig(req);
        expect(commonConfig.requestId).toEqual('a-uuid');
      });
    });
  });
});


text:
<!DOCTYPE html>

<meta content="text/html; charset=IBM437" http-equiv="Content-Type">

<title>Gemfile</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

Gemfile

LICENCE

README

Rakefile

Class and Module Index

FedEx

FedEx::Mailing

Fedex

source "rubygems.org"

# Specify your gem's dependencies in fedex.gemspec gemspec

[Validate]

Generated by RDoc 3.11.

Generated with the Darkfish Rdoc Generator 3.


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>站点配置</title>
<link href="{Saivi::RES}/images/main.css" type="text/css" rel="stylesheet">
<link href="{Saivi::RES}/images/jquery-1.7.2.min.js" type="text/css" rel="stylesheet">
<link href="{Saivi::RES}/images/jquery.form.js" type="text/css" rel="stylesheet">
<meta http-equiv="x-ua-compatible" content="ie=7" />

<include file="Site:public" />

 <form id="myform" action="{Saivi::U('Site/qianmoban_up')}" method="post">

      选择前台模版:

        <select name="beer" id="beer" onChange="setBeerIcon();">
        <option  value="weiqianlong">官网风格</option>
           <option value="qianlan">ROCK风格</option>
           <option value="baiyin">银白风格</option>
		   <option value="weiwin">微赢风格</option>
           <option value="weixiang">微享风格</option>
		   <option value="Saivi">小猪风格</option>
        </select>

      <input type="submit" value="保存设置" />

  </form>


text:
InEngine.NET is a plugin-based software application that allows [commands](commands) to be [queued](queuing), [scheduled](scheduling), and run directly.

## How does it work?

InEngine.NET uses a plugin system to dynamically load .NET assemblies and execute code.
It also has a built-in command for launching external non-.NET programs.

Get started by pulling the binaries from the [latest release](https://github.com/InEngine-NET/InEngine.NET/releases) on GitHub.

Then run the **echo** command from the core plugin:

```bash
inengine.exe echo --text"Hello, world"
```
Or if you're a Linux or Mac OS X fan (like me!), use the **inengine** shell script ([Mono](http://www.mono-project.com/download/) is required):

```bash
inengine echo --text"Hello, world"
```

Instead of downloading binaries and runtimes, you can pull the latest Docker image:

```bash
docker pull ethanhann/inengine:latest
```

Now run a command in a container:

```bash
docker run --rm inengine echo --text"Hello, world"
```

## How does queueing work?

Want to queue our example echo command to run in the background or possibly on another server?

Use the core plugin's **queue:publish** command:

```bash
inengine.exe queue:publish --plugin=InEngine.Core --command=echo --args "text=Hello, world"
```

How do we consume that queued echo command?

Use the core plugin's **queue:consume** command:

```bash
inengine.exe queue:consume
```

## How do I run non-.NET commands?

There is a special **exec** command in the core plugin that allows for the execution of any program you can run at the command line.

For example, create a python script called **helloworld.py**, make it executable, and add this to it:

```python
#!/usr/bin/env python

print 'Hello, world!'
```

Whitelist the "helloworld" executable in the [appsettings.json](configuration) file:

```json
{
  "InEngine": {
    // ...
    "ExecWhitelist": {
      "helloworld": "/path/to/helloworld.py"
    }
    // ...
  }
}
```

Now execute it with the **exec** command:

```bash
inengine exec --executable="helloworld"
```

Why would you want to do this?
It opens up the possibility of running shell scripts, ETLs, Java programs, etc. in the background or on a schedule.

The example python script can be queued:

```bash
inengine queue:publish --plugin=InEngine.Core --command=exec --args="executable=helloworld"
```


text:
import './_notifications';
import './_analytics';
import {
  fetchAndCache,
  loadExternalCacheFirst,
  loadCacheFirst,
  loadCacheFirstAndUpdate,
  removeOldCaches
} from './_utilities';

const APP_SHELL_PAGE = '/_/app_shell';
const OFFLINE_PAGE = '/_/offline/';
const PRECACHE = ['/', OFFLINE_PAGE];

self.addEventListener('install', function(event) {
  console.log('[SW] Install service worker.');

  // Activate the service worker as soon as the app shell page is cached.
  event.waitUntil(loadCacheFirst(APP_SHELL_PAGE).then(() => {
    self.skipWaiting();
  }));

  // Precache/update a few other non-essential urls asynchronously.
  PRECACHE.forEach(path => loadCacheFirst(path));
});

self.addEventListener('activate', function(event) {
  console.log('[SW] Activate service worker.');

  // Activate the service worker and claim all open windows.
  let activationPromise = self.clients.claim();
  event.waitUntil(activationPromise);

  // Precache the content of all open windows. It might not yet be in our cache,
  // if the window were opened before the service worker was installed.
  activationPromise.then(() => self.clients.matchAll().then(clients => {
    clients.forEach(client => {
      loadCacheFirst(client.url);
    });
  }));

  // Remove all previous cache versions.
  removeOldCaches();
});

self.addEventListener('fetch', function(event) {
  let url = new URL(event.request.url);

  // We only intercept GET requests to the current domain..
  if (event.request.method != 'GET' || url.host != location.host) return;

  // We don't certain intercept internal requests.
  if (url.pathname.startsWith('/_/')) return;

  // For AMP navigation requests, return the app shell but immediately start
  // loading/updating the requested cached page in the background.
  if (event.request.mode == 'navigate') {
    fetchAndCache(url.href);
    return event.respondWith(loadCacheFirst(APP_SHELL_PAGE));
  }

  // These should only be AJAX requests made by the app shell. We immediately
  // return them from cache, if possible, and show the offline page as fallback.
  // We need to ensure that the offline page is returned with an error code.
  event.respondWith(loadCacheFirstAndUpdate(url.href)
    .catch(() => loadCacheFirst(OFFLINE_PAGE)
      .then(response => response.clone().text())
      .then(text => new Response(text, {
        ok: false,
        status: 503,
        headers: {'content-type': 'text/html'}
      }))
    )
  );
});

self.addEventListener('sync', function(event) {
  let [name, data] = event.tag.split(':');
  if (name == 'notifyarticle') {
    console.log('[SW] Handle sync event:', event.tag);
    return event.waitUntil(fetchAndCache(data).then(function() {
      // TODO(plegner) Get article title, body and thumbnail for notification.
      self.registration.showNotification('Your article is ready!', {
        body: 'Body',
        icon: 'Icon',
        data: {url: location.origin + data}
      });
    }));
  }
});


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace OpenSim.ScriptEngine.Shared
{
    public interface IScriptEventProvider : IScriptEngineComponent, IScriptEngineRegionComponent
    {

    }
}


text:
class CartsController < ApplicationController
  # Is this being used?
  service_class ServiceRequest
  resource_class ServiceRequest
end


text:
case node['platform_family']
when 'rhel', 'fedora', 'amazon'
  yum_repository 'blackfire' do
    description 'blackfire'
    baseurl "#{node[cookbook_name]['repository']}/fedora/$releasever/$basearch"
    gpgkey "#{node[cookbook_name]['repository']}/gpg.key"
    gpgcheck false
    sslverify true
    sslcacert '/etc/pki/tls/certs/ca-bundle.crt'
    action [:create, :makecache]
    only_if { node['blackfire']['install_repository'] }
  end
else
  r = apt_repository 'blackfire' do
    uri "#{node[cookbook_name]['repository']}/#{node['platform']}"
    distribution 'any'
    key "#{node[cookbook_name]['repository']}/gpg.key"
    components ['main']
    action :nothing
    only_if { node['blackfire']['install_repository'] }
  end
  r.run_action(:add)

  unless r.updated?
    execute 'blackfire repository update' do
      command "apt-get update -o Dir::Etc::sourcelist='sources.list.d/#{r.name}.list' -o Dir::Etc::sourceparts='-' -o APT::Get::List-Cleanup='0'"
      ignore_failure true
      action :run
    end
  end
end


text:
/*
 * Component, abstraction for leafs and composites
 */
public interface Employee {
    void getEmployeeInformation();
}


text:
Source and binary distributions can be found on our
[downloads](https://aurora.apache.org/downloads/) page.  Installing from binary packages is
recommended for most.

- [Installing the scheduler](#installing-the-scheduler)
- [Installing worker components](#installing-worker-components)
- [Installing the client](#installing-the-client)
- [Installing Mesos](#installing-mesos)
- [Troubleshooting](#troubleshooting)

If our binay packages don't suite you, our package build toolchain makes it easy to build your
own packages. See the [instructions](https://github.com/apache/aurora-packaging) to learn how.

## Machine profiles

Given that many of these components communicate over the network, there are numerous ways you could
assemble them to create an Aurora cluster.  The simplest way is to think in terms of three machine
profiles:

### Coordinator
**Components**: ZooKeeper, Aurora scheduler, Mesos master

A small number of machines (typically 3 or 5) responsible for cluster orchestration.  In most cases
it is fine to co-locate these components in anything but very large clusters (> 1000 machines).
Beyond that point, operators will likely want to manage these services on separate machines.
In particular, you will want to use separate ZooKeeper ensembles for leader election and
service discovery. Otherwise a service discovery error or outage can take down the entire cluster.

In practice, 5 coordinators have been shown to reliably manage clusters with tens of thousands of
machines.

### Worker
**Components**: Aurora executor, Aurora observer, Mesos agent

The bulk of the cluster, where services will actually run.

### Client
**Components**: Aurora client, Aurora admin client

Any machines that users submit jobs from.

## Installing the scheduler
### Ubuntu Trusty

1. Install Mesos
   Skip down to [install mesos](#mesos-on-ubuntu-trusty), then run:

        sudo start mesos-master

2. Install ZooKeeper

        sudo apt-get install -y zookeeperd

3. Install the Aurora scheduler

        sudo add-apt-repository -y ppa:openjdk-r/ppa
        sudo apt-get update
        sudo apt-get install -y openjdk-8-jre-headless wget

        sudo update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

        wget -c https://apache.bintray.com/aurora/ubuntu-trusty/aurora-scheduler_0.17.0_amd64.deb
        sudo dpkg -i aurora-scheduler_0.17.0_amd64.deb

### CentOS 7

1. Install Mesos
   Skip down to [install mesos](#mesos-on-centos-7), then run:

        sudo systemctl start mesos-master

2. Install ZooKeeper

        sudo rpm -Uvh https://archive.cloudera.com/cdh4/one-click-install/redhat/6/x86_64/cloudera-cdh-4-0.x86_64.rpm
        sudo yum install -y java-1.8.0-openjdk-headless zookeeper-server

        sudo service zookeeper-server init
        sudo systemctl start zookeeper-server

3. Install the Aurora scheduler

        sudo yum install -y wget

        wget -c https://apache.bintray.com/aurora/centos-7/aurora-scheduler-0.17.0-1.el7.centos.aurora.x86_64.rpm
        sudo yum install -y aurora-scheduler-0.17.0-1.el7.centos.aurora.x86_64.rpm

### Finalizing
By default, the scheduler will start in an uninitialized mode.  This is because external
coordination is necessary to be certain operator error does not result in a quorum of schedulers
starting up and believing their databases are empty when in fact they should be re-joining a
cluster.

Because of this, a fresh install of the scheduler will need intervention to start up.  First,
stop the scheduler service.
Ubuntu: `sudo stop aurora-scheduler`
CentOS: `sudo systemctl stop aurora`

Now initialize the database:

    sudo -u aurora mkdir -p /var/lib/aurora/scheduler/db
    sudo -u aurora mesos-log initialize --path=/var/lib/aurora/scheduler/db

Now you can start the scheduler back up.
Ubuntu: `sudo start aurora-scheduler`
CentOS: `sudo systemctl start aurora`

## Installing worker components
### Ubuntu Trusty

1. Install Mesos
   Skip down to [install mesos](#mesos-on-ubuntu-trusty), then run:

        start mesos-slave

2. Install Aurora executor and observer

        sudo apt-get install -y python2.7 wget

        # NOTE: This appears to be a missing dependency of the mesos deb package and is needed
        # for the python mesos native bindings.
        sudo apt-get -y install libcurl4-nss-dev

        wget -c https://apache.bintray.com/aurora/ubuntu-trusty/aurora-executor_0.17.0_amd64.deb
        sudo dpkg -i aurora-executor_0.17.0_amd64.deb

### CentOS 7

1. Install Mesos
   Skip down to [install mesos](#mesos-on-centos-7), then run:

        sudo systemctl start mesos-slave

2. Install Aurora executor and observer

        sudo yum install -y python2 wget

        wget -c https://apache.bintray.com/aurora/centos-7/aurora-executor-0.17.0-1.el7.centos.aurora.x86_64.rpm
        sudo yum install -y aurora-executor-0.17.0-1.el7.centos.aurora.x86_64.rpm

### Worker Configuration
The executor typically does not require configuration.  Command line arguments can
be passed to the executor using a command line argument on the scheduler.

The observer needs to be configured to look at the correct mesos directory in order to find task
sandboxes. You should 1st find the Mesos working directory by looking for the Mesos agent
`--work_dir` flag. You should see something like:

        ps -eocmd | grep "mesos-slave" | grep -v grep | tr ' ' '\n' | grep "\--work_dir"
        --work_dir=/var/lib/mesos

If the flag is not set, you can view the default value like so:

        mesos-slave --help
        Usage: mesos-slave [options]

          ...
          --work_dir=VALUE      Directory path to place framework work directories
                                (default: /tmp/mesos)
          ...

The value you find for `--work_dir`, `/var/lib/mesos` in this example, should match the Aurora
observer value for `--mesos-root`.  You can look for that setting in a similar way on a worker
node by grepping for `thermos_observer` and `--mesos-root`.  If the flag is not set, you can view
the default value like so:

        thermos_observer -h
        Options:
          ...
          --mesos-root=MESOS_ROOT
                                The mesos root directory to search for Thermos
                                executor sandboxes [default: /var/lib/mesos]
          ...

In this case the default is `/var/lib/mesos` and we have a match. If there is no match, you can
either adjust the mesos-master start script(s) and restart the master(s) or else adjust the
Aurora observer start scripts and restart the observers.  To adjust the Aurora observer:

#### Ubuntu Trusty

    sudo sh -c 'echo "MESOS_ROOT=/tmp/mesos" >> /etc/default/thermos'

#### CentOS 7

Make an edit to add the `--mesos-root` flag resulting in something like:

    grep -A5 OBSERVER_ARGS /etc/sysconfig/thermos
    OBSERVER_ARGS=(
      --port=1338
      --mesos-root=/tmp/mesos
      --log_to_disk=NONE
      --log_to_stderr=google:INFO
    )

## Installing the client
### Ubuntu Trusty

    sudo apt-get install -y python2.7 wget

    wget -c https://apache.bintray.com/aurora/ubuntu-trusty/aurora-tools_0.17.0_amd64.deb
    sudo dpkg -i aurora-tools_0.17.0_amd64.deb

### CentOS 7

    sudo yum install -y python2 wget

    wget -c https://apache.bintray.com/aurora/centos-7/aurora-tools-0.17.0-1.el7.centos.aurora.x86_64.rpm
    sudo yum install -y aurora-tools-0.17.0-1.el7.centos.aurora.x86_64.rpm

### Mac OS X

    brew upgrade
    brew install aurora-cli

### Client Configuration
Client configuration lives in a json file that describes the clusters available and how to reach
them.  By default this file is at `/etc/aurora/clusters.json`.

Jobs may be submitted to the scheduler using the client, and are described with
[job configurations](../reference/configuration.md) expressed in `.aurora` files.  Typically you will
maintain a single job configuration file to describe one or more deployment environments (e.g.
dev, test, prod) for a production job.

## Installing Mesos
Mesos uses a single package for the Mesos master and agent.  As a result, the package dependencies
are identical for both.

### Mesos on Ubuntu Trusty

    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E56151BF
    DISTRO=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
    CODENAME=$(lsb_release -cs)

    echo "deb http://repos.mesosphere.io/${DISTRO} ${CODENAME} main" | \
      sudo tee /etc/apt/sources.list.d/mesosphere.list
    sudo apt-get -y update

    # Use `apt-cache showpkg mesos | grep [version]` to find the exact version.
    sudo apt-get -y install mesos=1.1.0-2.0.107.ubuntu1404_amd64.deb

### Mesos on CentOS 7

    sudo rpm -Uvh https://repos.mesosphere.io/el/7/noarch/RPMS/mesosphere-el-repo-7-1.noarch.rpm
    sudo yum -y install mesos-1.1.0

## Troubleshooting

So you've started your first cluster and are running into some issues? We've collected some common
stumbling blocks and solutions in our [Troubleshooting guide](troubleshooting.md) to help get you moving.