text:
<?php

namespace Obokaman\StockForecast\Application\Service;

use Obokaman\StockForecast\Domain\Service\Predict\Predict;
use Obokaman\StockForecast\Infrastructure\Http\StockMeasurement\Collector;

final class PredictStockValue
{
    private $stock_measurement_collector;
    private $prediction_service;

    public function __construct(Collector $a_stock_measurement_collector, Predict $a_prediction_service)
    {
        $this->stock_measurement_collector = $a_stock_measurement_collector;
        $this->prediction_service = $a_prediction_service;
    }

    public function predict(PredictStockValueRequest $a_request): PredictStockValueResponse
    {
        $long_term_measurements = $this->stock_measurement_collector->getMeasurements($a_request->currency(), $a_request->stock(), $a_request->dateInterval());

        return new PredictStockValueResponse(
            $long_term_measurements,
            $this->prediction_service->predict($long_term_measurements->filterByPeriod('short')),
            $this->prediction_service->predict($long_term_measurements->filterByPeriod('medium')),
            $this->prediction_service->predict($long_term_measurements)
        );
    }
}


text:
(function () {
  'use strict';
  angular.module('RightAnglesShowcase').
    controller('AppController', [
      "$scope",
      "$state",
      "rightAngles.appInfo",
      "theme.themeService",
      "rightAngles.navbarService",
      function ($scope, $state, appInfo, themeService, navbarService) {
        $scope.appInfo = appInfo;
        $scope.showMenu = false;
        $scope.nav = {
          items: navbarService.getItems(),
          brand: navbarService.getBrand()
        };
        $scope.hasDropdownMenu = function (navItem) {
          return navbarService.hasDropdownMenu(navItem);
        };
        $scope.getDropdownMenuTemplateUrl = function (navItem) {
          return navbarService.getDropdownMenuTemplateUrl(navItem);
        };

        $scope.navItemSelected = function (navItem) {
          if (!$scope.hasDropdownMenu(navItem)) {
            navbarService.selectItem(navItem);
            $state.go(navItem.name);
          }
        };
        $scope.$on('theme:chosen', function () {
          $scope.selectedThemeName = themeService.getSelectedTheme().name;
        });
        $scope.selectedThemeName = themeService.getSelectedTheme().name;
        $state.go('home');
      }
    ])
    .config(function ($stateProvider) {
      $stateProvider
        .state('showcases', {//todo use constant "rightAngles.showcase.STATES".ROOT,
          url: "/showcase",
          views: {
            "appBody": {
              templateUrl: 'showcase/showcase.html'
            }
          }
        })
        .state('home', {
          url: "/home",
          views: {
            "appBody": {
              templateUrl: 'home/home.html'
            }
          }
        })
        .state('coverage', {
          url: "/coverage",
          views: {
            "appBody": {
              templateUrl: 'reports/coverage/PhantomJS 1.9.7 (Linux)/index.html'
            }
          }
        });
    });
})();

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hdfs.protocolPB;

import java.io.IOException;

import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToAddJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToAddJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToRemoveJNRequestProto;;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToRemoveJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToRemoveJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToRemoveJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToAddJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToAddJNResponseProto;

import org.apache.hadoop.hdfs.server.protocol.MomoNamenodeProtocol;
//import org.apache.hadoop.hdfs.server.protocol.*;

import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;

/**
 * Created by kangkai on 17/6/12.
 */
/**
 * Implementation for protobuf service that forwards requests
 * received on {@link MomoNamenodeProtocolPB} to the
 * {@link MomoNamenodeProtocol} server implementation.
 */
public class MomoNamenodeProtocolServerSideTranslatorPB implements
        MomoNamenodeProtocolPB {

    private final MomoNamenodeProtocol impl;

    public MomoNamenodeProtocolServerSideTranslatorPB(MomoNamenodeProtocol impl) {
        this.impl = impl;
    }

       @Override
    public InformActiveToAddJNResponseProto informActiveToAddJN(RpcController controller,
                                            InformActiveToAddJNRequestProto req) throws ServiceException {
        try {
            return PBHelper.convertInformActiveToAddJNResponse(impl.informActiveToAddJN(
                    PBHelper.convertUpdateJournalNodes(req.getJournalNodesList()), req.getIsFormatted()));
        } catch (IOException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public InformActiveToRemoveJNResponseProto informActiveToRemoveJN(RpcController unused,
					InformActiveToRemoveJNRequestProto request) throws ServiceException {
        try {
            return PBHelper.convertInformActiveToRemoveJNResponse(impl.informActiveToRemoveJN(
                    PBHelper.convertUpdateJournalNodes(request.getJournalNodesList())));
        } catch (IOException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public InformStandbyToAddJNResponseProto informStandbyToAddJN(RpcController controller,
                                        InformStandbyToAddJNRequestProto req) throws ServiceException {
        try {
            return PBHelper.convertInformStandbyToAddJNResponse(impl.informStandbyToAddJN(
                    PBHelper.convertUpdateJournalNodes(req.getJournalNodesList())));
        } catch (IOException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public InformStandbyToRemoveJNResponseProto informStandbyToRemoveJN(RpcController unused,
					InformStandbyToRemoveJNRequestProto request) throws ServiceException {
        try {
            return PBHelper.convertInformStandbyToRemoveJNResponse(impl.informStandbyToRemoveJN(
                    PBHelper.convertUpdateJournalNodes(request.getJournalNodesList())));
        } catch (IOException e) {
            throw new ServiceException(e);
        }
    }
}


text:
package com.dynastymasra.tour.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/**
 * Author   : @dynastymasra
 * User     : Dimas Ragil T
 * Email    : dynastymasra@gmail.com
 * LinkedIn : http://www.linkedin.com/in/dynastymasra
 * Blogspot : dynastymasra.wordpress.com | dynastymasra.blogspot.com
 */
public class Data {

    @JsonProperty("data")
    private List<Content> contents;

    public List<Content> getContents() {
        return contents;
    }

    public void setContents(List<Content> contents) {
        this.contents = contents;
    }
}


text:
<?php

/* AdminBundle:Shop:editArticle.html.twig */
class __TwigTemplate_20376ead087facb85c1ac2b4f6df997eb6c12656da3cd31d85ebf20bb410b7ad extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("AdminBundle::layout.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "AdminBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_title($context, array $blocks = array())
    {
        echo "Izdelki";
    }

    // line 5
    public function block_content($context, array $blocks = array())
    {
        // line 6
        echo "
Dodajanje in urejanje Artiklov

<form class=\"border artice_form\" action=\"";
        // line 7
        echo twig_escape_filter($this->env, (($this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "id")) ? ($this->env->getExtension('routing')->getPath("_admin_edit_article", array("id" => $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "id")))) : ($this->env->getExtension('routing')->getPath("_admin_add_article"))), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo " novalidate>
    ";
        // line 8
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "

        <input type=\"submit\" name=\"save\" value=\"Shrani\" class=\"btn btn-primary\">

</form>

";
    }

    public function getTemplateName()
    {
        return "AdminBundle:Shop:editArticle.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  47 => 8,  41 => 7,  38 => 6,  35 => 5,  29 => 3,);
    }
}


text:
/*
 * basic CSS reset
 * TODO(mc, 2019-03-12): copied from Opentrons/opentrons-website; merge somehow
*/

/* use border-box because it's more sane */
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* prevent adjustments of font size after mobile orientation changes */
html {
  text-size-adjust: 100%;
}

/* remove margin from body and set sane font-size + line-height */
body {
  margin: 0;
  font-size: 16px;
  line-height: 1;
  font-family: 'Open Sans', sans-serif;
}

/* ensure <main> works in IE 9, 10, and 11 */
main {
  display: block;
}

/* make images responsive */
img {
  max-width: 100%;
  max-height: 100%;
  border-style: none;
}

/* strip margin and padding from text elements */
h1,
h2,
h3,
h4,
h5,
h6,
p,
ul,
ol,
button {
  margin: 0;
  padding: 0;
}

/* no list style by default */
ul,
ol {
  list-style: none;
}

/* no underline on links by default */
a {
  text-decoration: none;
}

/* no styles on buttons by default */
button {
  border: none;
  background-color: transparent;
}


text:
require 'net/http'
require File.expand_path('../fixtures/classes', __FILE__)

describe "Net::HTTPHeader#to_hash" do
  before(:each) do
    @headers = NetHTTPHeaderSpecs::Example.new
  end

  it "returns a Hash representing all Header entries (keys in lower case, values as arrays)" do
    @headers.to_hash.should == {}

    @headers["My-Header"] = "test"
    @headers.to_hash.should == { "my-header" => ["test"] }

    @headers.add_field("My-Header", "another test")
    @headers.to_hash.should == { "my-header" => ["test", "another test"] }
  end

  it "does not allow modifying the headers from the returned hash" do
    @headers.to_hash["my-header"] = ["test"]
    @headers.to_hash.should == {}
    @headers.key?("my-header").should be_false
  end
end


text:
package org.jasig.cas.support.openid.web.support;

import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.support.openid.authentication.principal.OpenIdService;
import org.jasig.cas.web.support.AbstractArgumentExtractor;

import javax.servlet.http.HttpServletRequest;

/**
 * Constructs an OpenId Service.
 *
 * @author Scott Battaglia
 * @since 3.1
 */
public class OpenIdArgumentExtractor extends AbstractArgumentExtractor {

    @Override
    protected WebApplicationService extractServiceInternal(final HttpServletRequest request) {
        return OpenIdService.createServiceFrom(request);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/video_error_normal" android:state_pressed="false" />
    <item android:drawable="@drawable/video_error_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/video_error_normal" />
</selector>


text:
<link href="/fixtures/src/test1.css?101" media="screen" rel="stylesheet" type="text/css" />
<link href="/fixtures/src/test2.css?101" media="screen" rel="stylesheet" type="text/css" />
<link href="/fixtures/src/test_fonts.css?101" media="screen" rel="stylesheet" type="text/css" />


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

<title>ServiceResponse (Abstract Service Library)</title>
<meta name="date" content="2013-12-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.nise.ux.asl.data

Class ServiceResponse

java.lang.Object

org.nise.ux.asl.data.ServiceResponse

public class ServiceResponse
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

java.lang.String
data

java.lang.Throwable
throwable

Constructor Summary

Constructors

Constructor and Description

ServiceResponse(java.lang.Object data)

ServiceResponse(java.lang.Object data,
               java.lang.Throwable throwable)

ServiceResponse(java.lang.Throwable throwable)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
toString()

Methods inherited from class java.lang.Object

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

Field Detail

data

public java.lang.String data

throwable

public java.lang.Throwable throwable

Constructor Detail

ServiceResponse

public ServiceResponse(java.lang.Object data)

ServiceResponse

public ServiceResponse(java.lang.Throwable throwable)

ServiceResponse

public ServiceResponse(java.lang.Object data,
               java.lang.Throwable throwable)

Method Detail

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				This library is a work of NISE organization User-eXperience team.


text:
from __future__ import print_function, division

import numpy as np
import os
import argparse

from scipy.io.wavfile import read as wavread
from scipy.signal import resample

import kmodels

from keras.callbacks import EarlyStopping

def load_features(filename):
    if filename.endswith('.npy'):
        feats = np.load(filename)
    else:
        feats = np.loadtxt(filename)
    # feats=feats-np.mean(feats,axis=0)
    # feats=feats/np.std(feats,axis=0)
    return feats

def load_wav(filename):
    if filename.endswith('.wav'):
        fs, x = wavread(filename)
        if fs != 8000:
            x = resample(x, int(16000/fs*len(x)))
        return x
    return np.array([])

def save_model_weights(filename, model):
    np.savez(filename, list(model.get_weights()))

def load_model_weights(filename):
    weights = np.load(filename)
    weights = [weights[i] for i in range(weights.shape[0])]
    return weights

def prep_train(data, chunk_size=6000):
    train_x = []
    train_y = []

    for i in range(0, len(data)-chunk_size):
        end = min(len(data)-1, i+chunk_size)
        train_x.append(data[i:end])
        train_y.append(data[i+1:end+1])

    train_x = np.array(train_x)
    train_y = np.array(train_y)
    return train_x, train_y

class StatefulDataGenerator:

    def __init__(
        self,
        data,
        span,
        batch_size,
        skip_constants=False,
        model=None
    ):
        self.files = data
        np.random.shuffle(self.files)
        self.file = np.random.randint(0, len(data), size=(batch_size))
        self.idxs = np.zeros(batch_size)
        self.n = len(data)
        self.batch_size = batch_size
        self.span = span
        self.model = model

    def __iter__(self):
        return self

    def next(self):
        for i in range(self.batch_size):
            if self.idxs[i]+self.span+1 >= len(self.files[self.file[i]]):
                self.idxs[i] = 0
                self.file[i] = (self.file[i]+1) % self.n
                if self.model is not None:
                    self.model.reset_states()

        x = np.array([
            self.files[self.file[i]][self.idxs[i]:self.idxs[i]+self.span]
            for i in range(self.batch_size)
        ])
        y = np.array([
            self.files[self.file[i]][self.idxs[i]+self.span+1]
            for i in range(self.batch_size)
        ])

        self.idxs[i] += self.span
        return (x, y)

    def get(self):
        return self.next()

    def size(self):
        return sum(len(f) for f in self.files)

class DataGenerator:

    def __init__(
        self,
        data,
        span,
        batch_size,
        skip_constants=False,
        model=None
    ):
        self.data = data

        self.instances = []
        for i, f in enumerate(data):
            for j in range(len(f)-span-1):
                idx1 = np.argmax(data[i][j+span-1])
                idx2 = np.argmax(data[i][j+span])
                p = np.random.uniform()
                if not skip_constants or idx1 != idx2 or p > 0.8:
                    self.instances.append([i, j, j+span])

        self.instances = np.array(self.instances)
        self.n = len(self.instances)
        self.idxs = np.array([
            np.random.permutation(self.n)
            for i in range(batch_size)
        ])
        self.span = span
        self.batch_size = batch_size
        self.i = 0

    def __iter__(self):
        return self

    def next(self):
        x = np.array([
            self.data[f][start:end]
            for [f, start, end] in self.instances[self.idxs[:, self.i]]
        ])
        y = np.array([
            self.data[f][end]
            for [f, start, end] in self.instances[self.idxs[:, self.i]]
        ])
        self.i = (self.i+1) % self.n
        return (x, y)

    def get(self):
        return self.next()

    def size(self):
        return self.n

def train(
    train_list,
    out_dir,
    train_model_weights=None,
    train_model_type='simple_rnn',
    embed_dim=10,
    hidden_dim=20,
    optim='sgd',
    loss='mse',
    stateful=False,
    span=40,
    batch_size=128,
    skip_constants=False,
    verbose=False
):
    '''
    Runs the whole training/testing pipeline
    '''
    if verbose:
        print('----------------------------------------')
        print('            Creating model              ')
        print(' - input dim :', embed_dim)
        print(' - hidden dim :', hidden_dim)
        print(' - output dim :', embed_dim)
        print('----------------------------------------')

    else:
        if verbose:
            print(' Initializing model with random weights')

    if hasattr(kmodels, 'build_' + train_model_type):
        build_model = getattr(kmodels, 'build_' + train_model_type)
    else:
        print('Unknown model type :/ you\'ll have to code it yourself')
        exit()
    model = build_model(
        embed_dim,
        hidden_dim,
        embed_dim,
        span,
        train_model_weights,
        batch_size
    )
    if verbose:
        print(' Compiling model with ')
        print(' - optimizer : ' + optim)
        print(' - loss function : ' + loss)
    model.compile(
        optimizer=optim,
        loss=loss  # kmodels.last_mse
    )

    if verbose:
        print('----------------------------------------')
        print('       Running training on corpus       ')
        print('----------------------------------------')

    train_files = []

    with open(train_list, 'r') as f:
        train_files = [l for l in f.read().split('\n') if l.endswith('.npy')]
    train_data = []
    valid_data = []
    raw_data = []
    for tf in train_files:
        if verbose:
            print('         Loading training file          ')
            print(' - file :', tf)
            print('----------------------------------------')

        current_inputs = load_features(tf)
        if current_inputs.shape[1] != embed_dim:
            print('Wrong input dim :', current_inputs.shape[1],
                  ', expected', embed_dim,
                  'in file', f, ', skipping to next file.')
            continue
        raw_data.append(current_inputs)
    np.random.shuffle(raw_data)
    valid_split = int(0.1*len(train_files))
    valid_data = raw_data[:valid_split]
    train_data = raw_data[valid_split:]

    if stateful:
        datagen = StatefulDataGenerator
    else:
        datagen = DataGenerator
    batch_generator = datagen(
        train_data,
        span,
        batch_size,
        skip_constants,
        model
    )
    validation_generator = datagen(valid_data, span, batch_size, model)
    print(next(batch_generator)[0].shape, next(batch_generator)[1].shape)
    model.fit_generator(
        batch_generator,
        batch_generator.size(),  # Sample per epoch
        2,  # epoch
        validation_data=validation_generator,
        nb_val_samples=validation_generator.size(),
        callbacks=[
            EarlyStopping(
                monitor='val_loss',
                patience=1,
                verbose=1,
                mode='auto'
            )
        ],
        verbose=1
    )

    save_model_weights(out_dir+"/dump_model", model)

    return model.get_weights()

def test(
    test_list,
    out_dir,
    trained_model_weights=None,
    test_model_type='simple_rnn',
    embed_dim=10,
    hidden_dim=20,
    optim='sgd',
    error='mse',
    verbose=False
):
    if verbose:
        print('----------------------------------------')
        print('       Running testing on corpus        ')
        print('----------------------------------------')

    if hasattr(kmodels, 'build_' + test_model_type):
        build_model = getattr(kmodels, 'build_' + test_model_type)
    else:
        print('Unknown model type :/ you\'ll have to code it yourself')
        exit()
    test_model = build_model(
        embed_dim, hidden_dim, embed_dim, trained_model_weights)
    test_model.compile(
        optimizer=optim,
        loss=error
    )

    # get_hidden=kmodels.get_hidden(test_model)

    test_files = []

    with open(test_list, 'r') as f:
        test_files = [l for l in f.read().split('\n') if l.endswith('.npy')]

    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    for i, f in enumerate(test_files):
        current_inputs = load_features(f)
        if current_inputs.shape[1] != embed_dim:
            print('Wrong input dim :', current_inputs.shape[1],
                  ', expected', embed_dim,
                  'in file', f, ', skipping to next file.')
            continue
        if verbose:
            print('Running through file', f, '(', i, '/', len(test_files), ')')
        y = np.zeros((len(current_inputs), embed_dim))
        hidden = np.zeros((len(current_inputs), hidden_dim))
        loss = np.zeros(len(current_inputs))
        test_x = np.array(current_inputs[:-1])
        test_x = test_x.reshape(1, len(test_x), -1)
        test_y = current_inputs[1:]

        y[1:] = test_model.predict_on_batch(test_x)
        #hidden[1:] = get_hidden(test_x)

        if error == 'mse':
            loss = np.sqrt(np.sum(np.square(y-current_inputs), axis=-1))
        elif error == 'categorical_crossentropy':
            # 1-(current_inputs*y).sum(axis=-1)
            loss = -(current_inputs*np.log(y+0.0000001)).sum(axis=-1)
        elif error == 'cosine_proximity':
            dotprod = np.sum(current_inputs*y, axis=-1)
            norm_y = np.linalg.norm(y, ord=2, axis=-1)
            norm_gold = np.linalg.norm(current_inputs, ord=2, axis=-1)
            cosine = dotprod/(norm_y*norm_gold + 0.000001)
            loss = 1-cosine

        out_file = out_dir + '/' + os.path.basename(f)[:-4] + '_loss.npy'
        hidden_file = out_dir + '/' + os.path.basename(f)[:-4] + '_hid.npy'
        np.save(out_dir + '/' + os.path.basename(f), y)
        #np.save(hidden_file, hidden)
        np.save(out_file, loss)


text:
<?php
namespace Cygnite\Database\Service;

use Illuminate\Database\Eloquent\Model;

/**
 * If you want to use Eloquent ORM register EloquentServiceProvider
 * as Service and extend \Cygnite\Database\Service\Eloquent in your
 * model class
 *
 * <code>
 * class User extends \Cygnite\Database\Service\Eloquent
 * {
 *
 * }
 * </code>
 *
 * Class Eloquent
 *
 * @package Cygnite\Database\Service\Eloquent
 */
class Eloquent extends Model
{
}


text:
package org.auraframework.impl.validation.http;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.auraframework.test.AuraHttpTestCase;
import org.auraframework.test.annotation.UnAdaptableTest;
import org.auraframework.util.AuraFiles;
import org.auraframework.util.json.Json;
import org.auraframework.util.validation.ValidationError;
import org.auraframework.util.validation.ValidationTestUtil;

import com.google.common.base.Charsets;

/**
 * Testing validation tool functionality. UnAdaptableTest because requires source to check present in file system.
 */
@UnAdaptableTest
public final class AuraValidationServletHttpTest extends AuraHttpTestCase {

    private HttpRequestBase method;

    public AuraValidationServletHttpTest(String name) {
        super(name);
    }

    @Override
    public void tearDown() throws Exception {
        try {
            if (method != null) {
                method.releaseConnection();
                method = null;
            }
        } finally {
            super.tearDown();
        }
    }

    public void testServlet() throws Exception {
        String path = AuraFiles.Core.getPath() + "/aura-components/src/test/components/validationTest/basic";
        assertTrue(path, new File(path).exists());
        method = obtainGetMethod("/qa/auraValidation?path=" + path);
        HttpResponse response = perform(method);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertDefaultAntiClickjacking(response, true, false);
        String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
        assertTrue(contentType, contentType.contains(Json.MIME_TYPE));
        assertTrue(contentType, contentType.contains(Charsets.UTF_8.toString()));

        String content = getResponseBody(response);
        List<String> errors = ValidationError.parseErrors(content);

        ValidationTestUtil.verifyValidationTestBasicErrors(errors);
    }

    /**
     * Same as testServlet(), but only uses JDK classes
     */
    public void testServletStandalone() throws Exception {
        String path = AuraFiles.Core.getPath() + "/aura-components/src/test/components/validationTest/basic";
        assertTrue(path, new File(path).exists());
        String url = getTestServletConfig().getBaseUrl().toURI().resolve("/qa/auraValidation?path=" + path).toString();
        InputStream stream = new URL(url).openStream();
        List<String> errors = ValidationError.parseErrors(new InputStreamReader(stream));

        ValidationTestUtil.verifyValidationTestBasicErrors(errors);
    }
}


text:
<?xml version='1.0' encoding='windows-1252' ?>

<!--L
  Copyright Oracle inc, SAIC-F

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cadsr-util/LICENSE.txt for details.
L-->

<!DOCTYPE Association SYSTEM "jbo_03_01.dtd">

<Association
   Name="QcCotFkAssoc" >
   <DesignTime>
      <Attr Name="_isCodegen" Value="true" />
      <Attr Name="_version" Value="9.0.5.16.0" />
   </DesignTime>
   <AssociationEnd
      Name="Contexts"
      Cardinality="0"
      Source="true"
      Owner="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.Contexts" >
      <AttrArray Name="Attributes">
         <Item Value="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.Contexts.ConteIdseq" />
      </AttrArray>
      <DesignTime>
         <Attr Name="_aggregation" Value="0" />
         <Attr Name="_isUpdateable" Value="true" />
         <Attr Name="_finderName" Value="Contexts" />
         <Attr Name="_foreignKey" Value="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.Contexts.ContePk" />
      </DesignTime>
   </AssociationEnd>
   <AssociationEnd
      Name="QuestContentsExt"
      Cardinality="-1"
      Owner="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.QuestContentsExt" >
      <AttrArray Name="Attributes">
         <Item Value="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.QuestContentsExt.ConteIdseq" />
      </AttrArray>
      <DesignTime>
         <Attr Name="_aggregation" Value="0" />
         <Attr Name="_isUpdateable" Value="true" />
         <Attr Name="_finderName" Value="QuestContentsExt" />
         <Attr Name="_foreignKey" Value="gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.QuestContentsExt.QcCotFk" />
      </DesignTime>
   </AssociationEnd>
</Association>


text:
namespace Sentinel.OAuth.Client.Mvc5.Models.Http
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;

    using Microsoft.Owin;

    internal class QueryBuilder : IEnumerable<KeyValuePair<string, string>>
    {
        private IList<KeyValuePair<string, string>> parameters;

        public QueryBuilder()
        {
            this.parameters = new List<KeyValuePair<string, string>>();
        }

        public QueryBuilder(IEnumerable<KeyValuePair<string, string>> parameters)
        {
            this.parameters = new List<KeyValuePair<string, string>>(parameters);
        }

        public void Add(string key, IEnumerable<string> values)
        {
            foreach (var value in values)
            {
                this.parameters.Add(new KeyValuePair<string, string>(key, value));
            }
        }

        public void Add(string key, string value)
        {
            this.parameters.Add(new KeyValuePair<string, string>(key, value));
        }

        public override string ToString()
        {
            var builder = new StringBuilder();
            var first = true;

            foreach (var pair in this.parameters)
            {
                builder.Append(first ? "?" : "&");
                first = false;

                builder.Append(Uri.EscapeDataString(pair.Key));
                builder.Append("=");
                builder.Append(pair.Value != null ? Uri.EscapeDataString(pair.Value) : string.Empty);
            }

            return builder.ToString();
        }

        public QueryString ToQueryString()
        {
            return new QueryString(this.ToString());
        }

        public override int GetHashCode()
        {
            return this.ToQueryString().GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return this.ToQueryString().Equals(obj);
        }

        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
        {
            return this.parameters.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.parameters.GetEnumerator();
        }
    }
}


text:
class SubjectCombinationDetail < ActiveRecord::Base
  attr_accessible :standard_id, :subject_combination_id, :subject_id

  belongs_to :subject_combination
  belongs_to :standard
  belongs_to :subject

  validates :standard_id, presence: true
  validates :subject_id, presence: true
  validates :subject_combination_id, presence: true
end


text:
/**
 * `useCoreLearn` composable function mock.
 *
 * If default values are sufficient for tests,
 * you only need call `jest.mock('<useCoreLearn file path>')`
 * at the top of a test file.
 *
 * If you need to override some default values from some tests,
 * you can import a helper function `useCoreLearnMock` that accepts
 * an object with values to be overriden and use it together
 * with  `mockImplementation` as follows:
 *
 * ```
 * // eslint-disable-next-line import/named
 * import useCoreLearn, { useCoreLearnMock } from '<useCoreLearn file path>';
 *
 * jest.mock('<useCoreLearn file path>')
 *
 * it('test', () => {
 *   useCoreLearn.mockImplementation(
 *    () => useCoreLearnMock({ inClasses: true })
 *   );
 * })
 * ```
 *
 * You can reset your mock implementation back to default values
 * for other tests by calling the following in `beforeEach`:
 *
 * ```
 * useCoreLearn.mockImplementation(() => useCoreLearnMock())
 * ```
 */

export let inClasses = false;
export let canDownload = true;

const MOCK_DEFAULTS = {
  inClasses,
  canDownload,
};

export function useCoreLearnMock(overrides = {}) {
  return {
    ...MOCK_DEFAULTS,
    ...overrides,
  };
}

export default jest.fn(() => useCoreLearnMock());


text:
package org.hippoecm.repository.dataprovider;

import java.util.UUID;
import javax.jcr.InvalidItemStateException;

import javax.jcr.RepositoryException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.spi.Name;

/**
 * THIS CLASS IS NOT PART OF THE PUBLIC API.  DO NOT USE.
 */
public class HippoNodeId extends NodeId
{

    private static final long serialVersionUID = 1L;

    private static final Logger log = LoggerFactory.getLogger(HippoNodeId.class);

    public NodeId parentId;
    public Name name;
    private final HippoVirtualProvider provider;
    private StateProviderContext context;

    public HippoNodeId(HippoVirtualProvider provider, NodeId parent, StateProviderContext context, Name name) {
        super(provider.getDataProviderContext().generateUuid(context, null));
        this.provider = provider;
        if(context != null) {
            this.context = context;
        } else if (parent instanceof HippoNodeId && ((HippoNodeId)parent).context != null) {
            this.context = ((HippoNodeId)parent).context;
        } else {
            this.context = null;
        }
        parentId = parent;
        this.name = name;
    }

    public NodeState populate(StateProviderContext context) {
        if (context == null) {
            context = this.context;
        } else if (this.context == null) {
            this.context = context;
        }
        try {
            NodeState nodeState = provider.populate(context, this, parentId);
            return nodeState;
        } catch (RepositoryException ex) {
            log.error(ex.getClass().getName() + ": " + ex.getMessage(), ex);
            return null;
        }
    }

    public final NodeState populate(StateProviderContext context, NodeState state) throws InvalidItemStateException {
        if (context == null) {
            context = this.context;
        } else if (this.context == null) {
            this.context = context;
        }
        if (context == null) {
            context = new StateProviderContext();
        }
        try {
            return provider.populate(context, state);
        } catch (InvalidItemStateException ex) {
            throw ex;
        } catch (RepositoryException ex) {
            log.error(ex.getClass().getName() + ": " + ex.getMessage(), ex);
            return null;
        }
    }

    public final NodeState populate(HippoVirtualProvider provider, NodeState state) throws InvalidItemStateException, ItemStateException {
        try {
            if (provider != null) {
                provider.populate((context != null ? context : new StateProviderContext()), state);
            } else {
                state = populate(context, state);
            }
        } catch (InvalidItemStateException ex) {
            throw ex;
        } catch (RepositoryException ex) {
            log.error(ex.getClass().getName() + ": " + ex.getMessage(), ex);
            throw new ItemStateException("Failed to populate node state", ex);
        }
        return state;
    }

    protected final HippoVirtualProvider getProvider() {
        return provider;
    }

}


text:
exports.Parser = require("./parser");
exports.Serialiser = require("./serialiser");
exports.Numerics = require("./numerics");


text:
(function($) {
  var count=0;

  $.isSmartStickyHeader = function(elem) {
    return !!$(elem).data('SmartStickyHeader');
  };

  $.SmartStickyHeader = function(elem, options) {

    options = options || {};
    options.railClass = (options.railClass ? options.railClass + ' ' : '') + 'sticky-header-rail';

    var $window = $(window);
    var $elem = $(elem);
    $elem.data('SmartStickyHeader', true).css({'pointer-events':'all'});
    var railId = 'ssh' + (++count);

    var width, height, offset, $rail, $replacement , $shadow;

    init();

    $window.on('scroll', scrollHandler);
    $window.on('resize', debounce(function(){
      unmount();
      init();
    }, 500));

    function init() {
      setTimeout(function(){
        mount();
        setTimeout(scrollHandler,10);
      }, 10);
    }

    function mount() {
      offset = $elem.offset();
      width = $elem.outerWidth();
      height = $elem.outerHeight(true);

      $rail = $('

').css({
        top:0,
        padding:0,
        left: offset.left + 'px',
        width: width + 'px',
        height: height + 'px',
        overflow:'hidden',
        position:'fixed',
        'pointer-events': 'none'
      });

      $shadow = $('

').css({
        height: height + 'px',
        'pointer-events': 'none'
      });

      $replacement = $('

').css({
        height: height + 'px'
      });

      $elem.before($replacement);
      $elem.before($rail);
      $rail.append($elem);
      $rail.append($shadow);
    }

    function unmount() {
      $replacement.remove();
      $rail.replaceWith($elem);
    }

    var lastScroll;
    function scrollHandler(){
      if (!$rail) {
        return;
      }
      if (!exists()) {
        return $window.off('scroll', scrollHandler);
      }
      lastScroll = lastScroll || 0;
      // avoid negative values when scroll bouncing (eg. safari)
      var scroll = Math.max(0, $(window).scrollTop());
      var diff = scroll - lastScroll;
      lastScroll = scroll;

      // if header has a top margin, only reveal it when visible at the top
      var marginTop = parseInt($elem.css('margin-top'));

      var railScrollTop = $rail.scrollTop() + diff;
      railScrollTop = Math.max(Math.min(scroll, marginTop), railScrollTop);
      $rail.scrollTop(railScrollTop);

    }

    function exists() {
      return $('#'+railId).length;
    }

    function debounce(func, milliseconds) {
      var args, self, debouncing=0;
      return function() {
        debouncing++;
        args = Array.prototype.slice.call(arguments);
        self = this;
        if (debouncing===1) {
          executeFunc(0);
        }
      };
      function executeFunc(current) {
        if(current===debouncing) {
          func.apply(self, args);
          debouncing=0;
        } else {
          setTimeout(function(){ executeFunc(debouncing); }, milliseconds);
        }
      }
    }
  };

  $.fn.smartStickyHeader = function(options) {
    return this.each(function() {
      return $.SmartStickyHeader(this, options);
    });
  };
})(jQuery);


text:
module Tim
  class ProviderImageObserver < ActiveRecord::Observer
    observe ::Tim::ProviderImage
    include ::Tim::StateMachine::ProviderImage::FSMCreate
    include ::Tim::StateMachine::ProviderImage::FSMDelete

    def after_save(pi)
      handle_factory_callback(pi) if !pi.new_record? && pi.status_changed?
    end

    private
    # We ensure that the state is correctly transitioned through the state
    # machine. This will ensure all the correct events are fired.
    def handle_factory_callback(pi)
      case pi.status.upcase
        when "COMPLETE"
          pi.fsm_create_start    if pi.fsm_create_state == "queued"
          pi.fsm_create_complete unless pi.fsm_create_state == "complete"
        when "BUILDING"
          pi.fsm_create_start    unless pi.fsm_create_state == "in_progress"
        when "FAILED"
          pi.fsm_create_start    if pi.fsm_create_state == "queued"
          pi.fsm_create_fail     unless pi.fsm_create_state == "failed"
        when "DELETING"
          pi.fsm_delete_start    unless pi.fsm_delete_state == "in_progress"
        when "DELETEFAILED"
          pi.fsm_delete_start    if pi.fsm_delete_state == "queued"
          pi.fsm_delete_fail     unless pi.fsm_delete_state == "failed"
        when "DELETED"
          pi.fsm_delete_start    if pi.fsm_delete_state == "queued"
          pi.fsm_delete_complete unless pi.fsm_delete_state == "complete"
      end
    end
  end
end


text:
module Mahjong.Kyoku.Flags where

import           Import
import           Mahjong.Tiles

-- | Extendable data type which defines flags that can be used in the game
-- engine.
data Flag = FirstRoundUninterrupted -- ^ Tenhou, chiihou and renhou are yielded if someone goes out when this flag is in effect.
          | OpenedUraDora [TileEq]
          deriving (Eq, Ord, Read, Show)

$(deriveSafeCopy 0 'base ''Flag)


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.min.html">

Redirecting to fn.min.html...


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.DesignDemo">
        <!-- Customize your theme here. -->
    </style>

    <style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#6d4c41</item>
        <item name="colorPrimaryDark">#0ba823</item>
        <item name="colorAccent">#FF4081</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>

    <style name="chocolateToolBarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <!--<style name="chocolateToolBarTheme" parent="Base.Widget.AppCompat.Light.ActionBar">-->
        <!--<item name="actionBarSize">20dp</item>-->
       <item name="actionOverflowButtonStyle">@style/chocolateActionOverflowButtonStyle</item>
    </style>

    <style name="chocolateActionOverflowButtonStyle" parent="Widget.AppCompat.ActionButton.Overflow">
        <item name="android:src">@drawable/actionbar_add_icon</item>

    </style>

    <style name="FabStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">@dimen/fab_compat_margin</item>
        <item name="android:layout_gravity">bottom|end</item>
        <item name="android:src">@drawable/ic_add_black</item>
        <item name="borderWidth">0dp</item>
        <item name="elevation">6dp</item>
        <item name="pressedTranslationZ">12dp</item>
        <item name="rippleColor">@android:color/white</item>
    </style>

    <style name="Theme.Splash" parent="android:Theme.Black.NoTitleBar.Fullscreen">
        <!--<item name="android:windowBackground">@drawable/welcome</item>-->
        <item name="android:windowNoTitle">true</item>
    </style>

    <!-- 菜单ImageView的样式 -->
    <style name="MenuItemImageViewStyle">
        <item name="android:layout_width">24dip</item>
        <item name="android:layout_height">24dip</item>
        <item name="android:layout_marginRight">15dip</item>
    </style>

    <!-- 菜单TextView的样式 -->
    <style name="MenuItemTextViewStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#0b751e</item>
        <item name="android:drawablePadding">10dp</item>
        <item name="android:textSize">16sp</item>
    </style>

    <!-- 加载滚动条样式 -->
    <style name="loading">
        <item name="android:indeterminate">true</item>
        <item name="android:indeterminateDrawable">@drawable/progressloading</item>
        <item name="android:indeterminateDuration">1000</item>
        <item name="android:indeterminateOnly">true</item>
    </style>

</resources>


text:
package gov.va.hmp.web.servlet.view;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.View;

import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

/**
 *  Implementation of {@link org.springframework.web.servlet.ViewResolver} that resolves views with the default view name
 *  (contentNegotiatedView), in addition to the view names configured via the Application Context.
 *
 *  @see org.springframework.web.servlet.view.ContentNegotiatingViewResolver
 */
public class ContentNegotiatingViewResolver extends org.springframework.web.servlet.view.ContentNegotiatingViewResolver {

    public static final String DEFAULT_VIEW_NAME = "contentNegotiatingView";

    private Set<String> viewNames;

    @Required
    public void setViewNames(Set<String> viewNames) {
        Set<String> mergedViewNames = new HashSet<String>(viewNames);
        mergedViewNames.add(DEFAULT_VIEW_NAME);
        this.viewNames = Collections.unmodifiableSet(mergedViewNames);
    }

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        if (viewNames.contains(viewName)) {
            return super.resolveViewName(viewName, locale);
        } else {
            return null;
        }
    }
}


text:
package sarama

// OffsetMethod is passed in ConsumerConfig to tell the consumer how to determine the starting offset.
type OffsetMethod int

const (
	// OffsetMethodManual causes the consumer to interpret the OffsetValue in the ConsumerConfig as the
	// offset at which to start, allowing the user to manually specify their desired starting offset.
	OffsetMethodManual OffsetMethod = iota
	// OffsetMethodNewest causes the consumer to start at the most recent available offset, as
	// determined by querying the broker.
	OffsetMethodNewest
	// OffsetMethodOldest causes the consumer to start at the oldest available offset, as
	// determined by querying the broker.
	OffsetMethodOldest
)

// ConsumerConfig is used to pass multiple configuration options to NewConsumer.
type ConsumerConfig struct {
	// The default (maximum) amount of data to fetch from the broker in each request. The default of 0 is treated as 1024 bytes.
	DefaultFetchSize int32
	// The minimum amount of data to fetch in a request - the broker will wait until at least this many bytes are available.
	// The default of 0 is treated as 'at least one' to prevent the consumer from spinning when no messages are available.
	MinFetchSize int32
	// The maximum permittable message size - messages larger than this will return MessageTooLarge. The default of 0 is
	// treated as no limit.
	MaxMessageSize int32
	// The maximum amount of time (in ms) the broker will wait for MinFetchSize bytes to become available before it
	// returns fewer than that anyways. The default of 0 causes Kafka to return immediately, which is rarely desirable
	// as it causes the Consumer to spin when no events are available. 100-500ms is a reasonable range for most cases.
	MaxWaitTime int32

	// The method used to determine at which offset to begin consuming messages.
	OffsetMethod OffsetMethod
	// Interpreted differently according to the value of OffsetMethod.
	OffsetValue int64

	// The number of events to buffer in the Events channel. Setting this can let the
	// consumer continue fetching messages in the background while local code consumes events,
	// greatly improving throughput.
	EventBufferSize int
}

// ConsumerEvent is what is provided to the user when an event occurs. It is either an error (in which case Err is non-nil) or
// a message (in which case Err is nil and the other fields are all set).
type ConsumerEvent struct {
	Key, Value []byte
	Offset     int64
	Err        error
}

// Consumer processes Kafka messages from a given topic and partition.
// You MUST call Close() on a consumer to avoid leaks, it will not be garbage-collected automatically when
// it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
type Consumer struct {
	client *Client

	topic     string
	partition int32
	group     string
	config    ConsumerConfig

	offset        int64
	broker        *Broker
	stopper, done chan bool
	events        chan *ConsumerEvent
}

// NewConsumer creates a new consumer attached to the given client. It will read messages from the given topic and partition, as
// part of the named consumer group.
func NewConsumer(client *Client, topic string, partition int32, group string, config *ConsumerConfig) (*Consumer, error) {
	if config == nil {
		config = new(ConsumerConfig)
	}

	if config.DefaultFetchSize < 0 {
		return nil, ConfigurationError("Invalid DefaultFetchSize")
	} else if config.DefaultFetchSize == 0 {
		config.DefaultFetchSize = 1024
	}

	if config.MinFetchSize < 0 {
		return nil, ConfigurationError("Invalid MinFetchSize")
	} else if config.MinFetchSize == 0 {
		config.MinFetchSize = 1
	}

	if config.MaxMessageSize < 0 {
		return nil, ConfigurationError("Invalid MaxMessageSize")
	}

	if config.MaxWaitTime <= 0 {
		return nil, ConfigurationError("Invalid MaxWaitTime")
	} else if config.MaxWaitTime < 100 {
		Logger.Println("ConsumerConfig.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
	}

	if config.EventBufferSize < 0 {
		return nil, ConfigurationError("Invalid EventBufferSize")
	}

	if topic == "" {
		return nil, ConfigurationError("Empty topic")
	}

	broker, err := client.Leader(topic, partition)
	if err != nil {
		return nil, err
	}

	c := &Consumer{
		client:    client,
		topic:     topic,
		partition: partition,
		group:     group,
		config:    *config,
		broker:    broker,
		stopper:   make(chan bool),
		done:      make(chan bool),
		events:    make(chan *ConsumerEvent, config.EventBufferSize),
	}

	switch config.OffsetMethod {
	case OffsetMethodManual:
		if config.OffsetValue < 0 {
			return nil, ConfigurationError("OffsetValue cannot be < 0 when OffsetMethod is MANUAL")
		}
		c.offset = config.OffsetValue
	case OffsetMethodNewest:
		c.offset, err = c.getOffset(LatestOffsets, true)
		if err != nil {
			return nil, err
		}
	case OffsetMethodOldest:
		c.offset, err = c.getOffset(EarliestOffset, true)
		if err != nil {
			return nil, err
		}
	default:
		return nil, ConfigurationError("Invalid OffsetMethod")
	}

	go withRecover(c.fetchMessages)

	return c, nil
}

// Events returns the read channel for any events (messages or errors) that might be returned by the broker.
func (c *Consumer) Events() <-chan *ConsumerEvent {
	return c.events
}

// Close stops the consumer from fetching messages. It is required to call this function before
// a consumer object passes out of scope, as it will otherwise leak memory. You must call this before
// calling Close on the underlying client.
func (c *Consumer) Close() error {
	close(c.stopper)
	<-c.done
	return nil
}

// helper function for safely sending an error on the errors channel
// if it returns true, the error was sent (or was nil)
// if it returns false, the stopper channel signaled that your goroutine should return!
func (c *Consumer) sendError(err error) bool {
	if err == nil {
		return true
	}

	select {
	case <-c.stopper:
		close(c.events)
		close(c.done)
		return false
	case c.events <- &ConsumerEvent{Err: err}:
		return true
	}

	// For backward compatibility with go1.0
	return true
}

func (c *Consumer) fetchMessages() {

	fetchSize := c.config.DefaultFetchSize

	for {
		request := new(FetchRequest)
		request.MinBytes = c.config.MinFetchSize
		request.MaxWaitTime = c.config.MaxWaitTime
		request.AddBlock(c.topic, c.partition, c.offset, fetchSize)

		response, err := c.broker.Fetch(c.client.id, request)
		switch {
		case err == nil:
			break
		case err == EncodingError:
			if c.sendError(err) {
				continue
			} else {
				return
			}
		default:
			Logger.Printf("Unexpected error processing FetchRequest; disconnecting broker %s: %s\n", c.broker.addr, err)
			c.client.disconnectBroker(c.broker)
			for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
				if !c.sendError(err) {
					return
				}
			}
			continue
		}

		block := response.GetBlock(c.topic, c.partition)
		if block == nil {
			if c.sendError(IncompleteResponse) {
				continue
			} else {
				return
			}
		}

		switch block.Err {
		case NoError:
			break
		case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
			err = c.client.RefreshTopicMetadata(c.topic)
			if c.sendError(err) {
				for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
					if !c.sendError(err) {
						return
					}
				}
				continue
			} else {
				return
			}
		default:
			if c.sendError(block.Err) {
				continue
			} else {
				return
			}
		}

		if len(block.MsgSet.Messages) == 0 {
			// We got no messages. If we got a trailing one then we need to ask for more data.
			// Otherwise we just poll again and wait for one to be produced...
			if block.MsgSet.PartialTrailingMessage {
				if c.config.MaxMessageSize == 0 {
					fetchSize *= 2
				} else {
					if fetchSize == c.config.MaxMessageSize {
						if c.sendError(MessageTooLarge) {
							continue
						} else {
							return
						}
					} else {
						fetchSize *= 2
						if fetchSize > c.config.MaxMessageSize {
							fetchSize = c.config.MaxMessageSize
						}
					}
				}
			}
			select {
			case <-c.stopper:
				close(c.events)
				close(c.done)
				return
			default:
				continue
			}
		} else {
			fetchSize = c.config.DefaultFetchSize
		}

		for _, msgBlock := range block.MsgSet.Messages {
			for _, msg := range msgBlock.Messages() {
				select {
				case <-c.stopper:
					close(c.events)
					close(c.done)
					return
				case c.events <- &ConsumerEvent{Key: msg.Msg.Key, Value: msg.Msg.Value, Offset: msg.Offset}:
					c.offset++
				}
			}
		}
	}
}

func (c *Consumer) getOffset(where OffsetTime, retry bool) (int64, error) {
	request := &OffsetRequest{}
	request.AddBlock(c.topic, c.partition, where, 1)

	response, err := c.broker.GetAvailableOffsets(c.client.id, request)
	switch err {
	case nil:
		break
	case EncodingError:
		return -1, err
	default:
		if !retry {
			return -1, err
		}
		Logger.Printf("Unexpected error processing OffsetRequest; disconnecting broker %s: %s\n", c.broker.addr, err)
		c.client.disconnectBroker(c.broker)
		c.broker, err = c.client.Leader(c.topic, c.partition)
		if err != nil {
			return -1, err
		}
		return c.getOffset(where, false)
	}

	block := response.GetBlock(c.topic, c.partition)
	if block == nil {
		return -1, IncompleteResponse
	}

	switch block.Err {
	case NoError:
		if len(block.Offsets) < 1 {
			return -1, IncompleteResponse
		}
		return block.Offsets[0], nil
	case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
		if !retry {
			return -1, block.Err
		}
		err = c.client.RefreshTopicMetadata(c.topic)
		if err != nil {
			return -1, err
		}
		c.broker, err = c.client.Leader(c.topic, c.partition)
		if err != nil {
			return -1, err
		}
		return c.getOffset(where, false)
	}

	return -1, block.Err
}


text:
<TITLE>Review for Truman Show, The (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Truman Show, The (1998)

reviewed by
Bob Bloom

The Truman Show (1998) 4 stars out of 4

 The Truman Show is a thought-provoking, original movie that works on many
levels.

 It has you questioning your concepts of reality - and even God.

 The movie can be viewed as a parable on the amount of control we have over
our lives, or as an allegory about the exploitation so rampant in today's
world.

 But what is most amazing about The Truman Show is the performance of Jim
Carrey.

 Linking the words Jim Carrey and drama have been considered an oxymoron.
But in The Truman Show, Carrey gives a breakthrough turn as a man who
slowly comes to realize that his life is really not his own.

 Shucking his familiar manic mannerisms, Carrey is subtle, winsome,
innocent, in control and wise as Truman Burbank, whose life, from the
moment of his birth, has kept television audiences enthralled worldwide.

 Truman lives and works in Seahaven, a perfect little community in which
all the people are friendly and life is a series of product placements.

 But gradually Truman becomes aware that something is amiss. A klieg light
falls from the sky, the same people perform the same tasks on a regular
schedule, an open elevator wall reveals a set filled with technicians.

 Most disturbing is the unexpected reappearance of Truman's father, whom he
believed drowned years earlier in a boating accident. But everyone tries to
convince Truman that the homeless man he saw could not be his father.

 Truman begins questioning the reality of his world and of those in it.

 He tells his friend, Marlon, that sometimes "it feels like the whole world
revolves around me."

 And in a sense, it does. From the outset we, the audience, know that
Truman's world is a fraud, a gigantic set created by Christof, the Godlike
director pulling Truman's strings.

 Christof has designed the ultimate reality-based television show. "We
accept the reality of the world we are presented," he advises his staff
about Truman.

 Later when Truman has discovered the truth, Christof tells him that "in my
world, you have nothing to fear."

 Ed Harris is brilliant as Christof, establishing a character who should be
considered reprehensible and loathsome and making him a figure, if not
worthy of respect than at least understanding.

 Noah Emmerich is fine as Marlon, crying on cue as Christof uses him to try
to distract some of Truman's suspicions.

 Laura Linney as Meryl, Truman's "wife," gives a deft comic turn as an
actress who goes ballistic when Truman begins to ad-lib.

 Director Peter Weir's biblical symbolism may offend some. But it is not
meant to be sacrilegious. Rather it questions the status of God in today's
world.

 Is He, like Christof, that omnipotent director scripting our every action,
or is He merely one of the viewers sitting back and watching as events
unfold?

 Weir's setting and staging of the confrontation between Truman and
Christof is loaded with biblical implications.

 It also is one of the strongest scenes in the film.

 Weir leaves his ending a bit ambiguous, forcing the viewer to think about
Truman's future.

 That's the way smart movies work. They refuse to cater to an audience's
lowest common denominator.

 The Truman Show is a very effective and touching movie. It may leave you
questioning the concept of reality.

 Even if you can't find a hidden message the film will remain an enjoyable
and unforgetable experience.

 At this stage of the movie season, it may be premature to talk about
Academy Award nominations. But don't be surprised come February if The
Truman Show is among the handful of films receiving multiple honors.

 Bob Bloom is the film critic at the Journal and Courier in Lafayette, Ind.
He can be reached by e-mail at bloom@journal-courier.com or at
cbloom@iquest.net

cb

Carol Bloom of Bloom Ink Publishing Professionals
3312 Indian Rock Lane  West Lafayette, IN 47906-1203
765-497-9320   fax 765-497-3112  cbloom@iquest.net

Committed to Lifelong Learning through Effective Communication

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package bonjour

import (
	"errors"
	"fmt"
	"net"
	"strings"
	"time"

	"github.com/socketplane/go-fastping"
)

type response struct {
	addr *net.IPAddr
	rtt  time.Duration
}

const (
	// EchoReply indicates that a reply was received
	EchoReply = iota
	// NoReply indicates that no reply was received
	NoReply
	// Error indicates that there was an error with the request
	Error
)

func echo(address string, ip *net.IP) (int, error) {
	p := fastping.NewPinger()
	p.Debug = false
	netProto := "ip4:icmp"
	if strings.Index(address, ":") != -1 {
		netProto = "ip6:ipv6-icmp"
	}
	ra, err := net.ResolveIPAddr(netProto, address)
	if err != nil {
		return Error, err
	}

	if ip != nil && ip.To4() != nil {
		p.ListenAddr, _ = net.ResolveIPAddr("ip4", ip.To4().String())
	}

	results := make(map[string]*response)
	results[ra.String()] = nil
	p.AddIPAddr(ra)

	onRecv, onIdle, onErr := make(chan *response), make(chan bool), make(chan int)

	p.OnRecv = func(addr *net.IPAddr, t time.Duration) {
		onRecv <- &response{addr: addr, rtt: t}
	}
	p.OnIdle = func() {
		onIdle <- true
	}

	p.OnErr = func(addr *net.IPAddr, t int) {
		onErr <- t
	}

	p.MaxRTT = time.Second
	go p.Run()

	ret := NoReply
	select {
	case <-onRecv:
		ret = EchoReply
	case <-onIdle:
		ret = NoReply
	case res := <-onErr:
		errID := fmt.Sprintf("%d", res)
		err = errors.New(errID)
		ret = Error
	}

	p.Stop()
	return ret, err
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/user_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginRight="8dp"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name"
            style="@style/Base.TextAppearance.AppCompat.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:drawableLeft="@drawable/phone" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
#ifndef CDSTATE_H
#define	CDSTATE_H

class CDState {

public:
    virtual void onCreate() = 0;
    virtual void onLoop() = 0;
};

#endif


text:
namespace rappor {

TEST(RapporServiceTest, Update) {
  TestRapporService rappor_service;
  EXPECT_LT(base::TimeDelta(), rappor_service.next_rotation());
  EXPECT_TRUE(rappor_service.test_uploader()->is_running());

  rappor_service.Update(RECORDING_DISABLED, false);
  EXPECT_EQ(base::TimeDelta(), rappor_service.next_rotation());
  EXPECT_FALSE(rappor_service.test_uploader()->is_running());

  rappor_service.Update(FINE_LEVEL, false);
  EXPECT_LT(base::TimeDelta(), rappor_service.next_rotation());
  EXPECT_FALSE(rappor_service.test_uploader()->is_running());

  rappor_service.Update(COARSE_LEVEL, true);
  EXPECT_LT(base::TimeDelta(), rappor_service.next_rotation());
  EXPECT_TRUE(rappor_service.test_uploader()->is_running());
}

// Check that samples can be recorded and exported.
TEST(RapporServiceTest, RecordAndExportMetrics) {
  TestRapporService rappor_service;

  // Multiple samples for the same metric should only generate one report.
  rappor_service.RecordSample("MyMetric", ETLD_PLUS_ONE_RAPPOR_TYPE, "foo");
  rappor_service.RecordSample("MyMetric", ETLD_PLUS_ONE_RAPPOR_TYPE, "bar");

  RapporReports reports;
  rappor_service.GetReports(&reports);
  EXPECT_EQ(1, reports.report_size());

  const RapporReports::Report& report = reports.report(0);
  EXPECT_TRUE(report.name_hash());
  // ETLD_PLUS_ONE_RAPPOR_TYPE has 128 bits
  EXPECT_EQ(16u, report.bits().size());
}

// Check that the reporting level is respected.
TEST(RapporServiceTest, RecordingLevel) {
  TestRapporService rappor_service;
  rappor_service.Update(COARSE_LEVEL, false);

  // ETLD_PLUS_ONE_RAPPOR_TYPE is a FINE_LEVEL metric
  rappor_service.RecordSample("FineMetric", ETLD_PLUS_ONE_RAPPOR_TYPE, "foo");

  RapporReports reports;
  rappor_service.GetReports(&reports);
  EXPECT_EQ(0, reports.report_size());
}

// Check that the incognito is respected.
TEST(RapporServiceTest, Incognito) {
  TestRapporService rappor_service;
  rappor_service.set_is_incognito(true);

  rappor_service.RecordSample("MyMetric", COARSE_RAPPOR_TYPE, "foo");

  RapporReports reports;
  rappor_service.GetReports(&reports);
  EXPECT_EQ(0, reports.report_size());
}

}  // namespace rappor


text:
var app = angular.module('noteTake',['ngRoute','appRoutes','loginControl','ngCookies']);

app.controller('mainController',['$scope','$http','$document','$window',function($scope,$http,$document,$window){
    $scope.btnShow = false;  //default delete button not showing
    $scope.index = -1; //index of current note selected by user
    $scope.noteExists = false; //boolean for whether or not a note exists

    $scope.open = function(i,index){
        $scope.editMode = true;
        window.frames['richTextField'].document.body.innerHTML = i.text;
        $scope.index = index;
        $scope.noteExists = true;
    };

    $scope.backToMenu = function(){
        $scope.editMode = false;
        $scope.noteExists = false;
        $http.get('/api/notes')
            .success(function(data){
                $scope.allNotes = data;
                console.log('LOADING');
            })
            .error(function(data){
                console.log("Error: " + data);
            });
        window.frames['richTextField'].document.body.innerHTML = "";         //clears field after we go back
    };

    $scope.selected = 'normal'; //default font size
    $scope.selectedFont = 'Times New Roman'; //default font text

    $scope.formData = { //notes model we are passing in
        subject: "",
        text: ""
    };

    $scope.editMode = false;
    //when landing on the page, get all todos and show
    //INITIAL LOAD UP
    $http.get('/api/notes')
        .success(function(data){
            $scope.allNotes = data;
            console.log(data);
        })
        .error(function(data){
            console.log("Error: " + data);
        });

    //when submitting the add form, send the text to node API
    //use http put or patch
    $scope.createNote = function(){

        if ($scope.noteExists){
            //todo: http put to specific id and body
            console.log('note exists');
            $( "#dialog" ).dialog('close');

            var text = document.getElementById("theTextArea");
            text.value = window.frames['richTextField'].document.body.innerHTML; //transfers rich text field to text area

            window.frames['richTextField'].document.body.innerHTML = "";         //clears field after it is saved

            $scope.formData.text = text.value;
            $scope.formData.subject = $scope.noteSubject;
            console.log($scope.index);

            $http.put('/api/notes/'+$scope.allNotes[$scope.index]._id,$scope.formData)
                .success(function(data){
                $scope.formData = {};
                $scope.allNotes = data;

                    $http.get('/api/notes')
                        .success(function(data){
                            $scope.allNotes = data;
                            console.log('SAVING');
                        })
                        .error(function(data){
                            console.log("Error: " + data);
                        });
                })
                .error(function(data){
                    console.log("Error: " + data);
                });

            $scope.noteExists = false;
            $scope.editMode = false;

        }
        else {
            $( "#dialog" ).dialog('close');
            $scope.editMode = false;

            var text = document.getElementById("theTextArea");
            text.value = window.frames['richTextField'].document.body.innerHTML; //transfers rich text field to text area
            window.frames['richTextField'].document.body.innerHTML = ""; //clears field after it is saved
            //console.log(text.value);
            $scope.formData.text = text.value;
            $scope.formData.subject = $scope.noteSubject;
            //console.log($scope.noteSubject);
            $http.post('/api/notes',$scope.formData)
                .success(function(data){
                $scope.formData = {};
                $scope.allNotes = data;
                console.log(data);
                })
                .error(function(data){
                    console.log("Error: " + data);
                });
                noteExist = false;

            $http.get('/api/notes')
                .success(function(data){
                    $scope.allNotes = data;
                    console.log('CREATING');
                })
                .error(function(data){
                    console.log("Error: " + data);
                });
        }
    };

    //deleting a todo after checking it
    $scope.deleteNote = function(id){
        $http.delete('/api/notes/'+id)
            .success(function(data){
                $scope.allNotes = data;
                console.log(data);
                $scope.hovering = false;
            })
            .error(function(data){
                console.log("Error" + data);
            });
    };

    $scope.popUp = function() {          //popup function
        $( "#dialog" ).dialog();
        var theNote = document.getElementById("noteEditor");
    };

    $scope.insertImage = function(){     //insert image function
        var imageURL = prompt("Enter the image URL");
        if (imageURL != ""){
            $scope.doFormat('insertImage',imageURL);
        }
        else {
            alert("Image Error");
        }
    };

    $scope.insertLink = function(){        //insert link function
      var linkURL = prompt("Enter the Link URL");
      if (linkURL != ""){
          $scope.doFormat('createLink',linkURL);
      }
      else {
          alert("Link Error");
      }
    };

    $scope.changeFontSize = function (){      //font sizes
        switch($scope.selected){
            case 'xlarge':
                $scope.doFormat('fontSize',6);
                break;
            case 'xxlarge':
                $scope.doFormat('fontSize',7);
                break;
            case 'large':
                $scope.doFormat('fontSize',5);
                break;
            case 'small':
                $scope.doFormat('fontSize',3);
                break;
            case 'xsmall':
                $scope.doFormat('fontSize',2);
                break;
            case 'xxsmall':
                $scope.doFormat('fontSize',1);
                break;
            default:
                $scope.doFormat('fontSize',4);
                break;
        };
    };

    $scope.changeFontType = function(){           //font types
        switch($scope.selectedFont){
            case 'Times New Roman':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Palatino Linotype':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Georgia':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Arial':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Arial Black':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Comic Sans MS':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Impact':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Lucida Sans Unicode':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Tahoma':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Verdana':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Helvetica':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Lucida Console':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            case 'Courier New':
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
            default:
                $scope.doFormat('fontName',$scope.selectedFont);
                break;
        };
    };

    $scope.changeFontColor = function(){
        switch($scope.selectedColor){
            case 'red':
                $scope.doFormat('foreColor',$scope.selectedFont);
                break;
        };
    };

}]);

//scope is inherited from parent scope
app.directive('editor',function(){
   return{
       restrict: 'E',
       templateUrl:"/js/templates/editor.html",
       replace: true,
       link: function(scope,elem,attrs){
            richTextField.document.designMode = 'on';
            scope.doFormat = function(cmd,val) {
                richTextField.document.execCommand(cmd,false,val);
            };
       }
   };
});

//directive to remove HTML
app.filter('removeHTML', function(){
    return function(text){
        return text ? String(text).replace(/<[^>]+>/gm, '') : '';
    }
});