text:
{% if item.content_type.model == 'question' %}

	{{ item.object.user }}
	asked {{ item.object }}

{% else %}{% if item.content_type.model == 'answer' %}

	{{ item.object.user }}
	answered {{ item.object }}

{% endif %}{% endif %}


text:
using System.IO;
using Digipost.Api.Client.Common;
using Digipost.Api.Client.Common.Enums;

namespace Digipost.Api.Client.Send
{
    public class Document : IDocument
    {
        /// <param name="subject">The subject of the document.</param>
        /// <param name="fileType">The file type of the file (e.g pdf,txt.. ).</param>
        /// <param name="contentBytes">The content of file in byteArray.</param>
        /// <param name="authenticationLevel">Required authentication level of the document. Default password.</param>
        /// <param name="sensitivityLevel">Sensitivity level of the document. Default normal.</param>
        /// <param name="smsNotification">Optional notification to receiver of message via SMS. </param>
        /// <param name="dataType">Optional metadata for enriching the document when viewed in Digipost</param>
        public Document(string subject, string fileType, byte[] contentBytes, AuthenticationLevel authenticationLevel = AuthenticationLevel.Password,
            SensitivityLevel sensitivityLevel = SensitivityLevel.Normal, ISmsNotification smsNotification = null, string dataType = null)
        {
            Guid = System.Guid.NewGuid().ToString();
            Subject = subject;
            FileType = fileType;
            ContentBytes = contentBytes;
            AuthenticationLevel = authenticationLevel;
            SensitivityLevel = sensitivityLevel;
            SmsNotification = smsNotification;
            DataType = dataType;
        }

        /// <param name="subject">The subject of the document.</param>
        /// <param name="fileType">The file type of the file (e.g pdf,txt.. ).</param>
        /// <param name="documentStream">Stream of the file.</param>
        /// <param name="authenticationLevel">Required authentication level of the document. Default password.</param>
        /// <param name="sensitivityLevel">Sensitivity level of the document. Default normal.</param>
        /// <param name="smsNotification">Optional notification to receiver of message via SMS. </param>
        /// <param name="dataType">Optional metadata for enriching the document when viewed in Digipost</param>
        public Document(string subject, string fileType, Stream documentStream, AuthenticationLevel authenticationLevel = AuthenticationLevel.Password,
            SensitivityLevel sensitivityLevel = SensitivityLevel.Normal, ISmsNotification smsNotification = null, string dataType = null)
            : this(subject, fileType, new byte[] { }, authenticationLevel, sensitivityLevel, smsNotification, dataType)
        {
            ContentBytes = ExtractBytesFromStream(documentStream);
        }

        /// <param name="subject">The subject of the document.</param>
        /// <param name="fileType">The file type of the file (e.g pdf,txt.. ).</param>
        /// <param name="path">The path to the file. e.g c:\docs\file01.txt</param>
        /// <param name="authenticationLevel">Required authentication level of the document. Default password.</param>
        /// <param name="sensitivityLevel">Sensitivity level of the document. Default normal.</param>
        /// <param name="smsNotification">Optional notification to receiver of message via SMS. </param>
        /// <param name="dataType">Optional metadata for enriching the document when viewed in Digipost</param>
        public Document(string subject, string fileType, string path, AuthenticationLevel authenticationLevel = AuthenticationLevel.Password,
            SensitivityLevel sensitivityLevel = SensitivityLevel.Normal, ISmsNotification smsNotification = null, string dataType = null)
            : this(subject, fileType, new byte[] { }, authenticationLevel, sensitivityLevel, smsNotification, dataType)
        {
            ContentBytes = ExtractBytesFromPath(path);
        }

        /// <param name="subject">The subject of the document.</param>
        /// <param name="fileType">The mime type of the file. e.g pdf,txt..</param>
        /// <param name="authenticationLevel">Required authentication level of the document. Default password.</param>
        /// <param name="sensitivityLevel">Sensitivity level of the document. Default normal.</param>
        /// <param name="smsNotification">Optional notification to receiver of message via SMS. </param>
        /// <param name="dataType">Optional metadata for enriching the document when viewed in Digipost</param>
        internal Document(string subject, string fileType, AuthenticationLevel authenticationLevel = AuthenticationLevel.Password,
            SensitivityLevel sensitivityLevel = SensitivityLevel.Normal, ISmsNotification smsNotification = null, string dataType = null)
            : this(subject, fileType, new byte[] { }, authenticationLevel, sensitivityLevel, smsNotification, dataType)
        {
        }

        public ContentHash ContentHash { get; internal set; }

        public string Guid { get; set; }

        public string Subject { get; set; }

        public string FileType { get; set; }

        public ISmsNotification SmsNotification { get; set; }

        public AuthenticationLevel AuthenticationLevel { get; set; }

        public SensitivityLevel SensitivityLevel { get; set; }

        public byte[] ContentBytes { get; set; }

        public string DataType { get; set; }

        private static byte[] ExtractBytesFromPath(string path)
        {
            using (var fileStream = new FileStream(path, FileMode.Open))
            {
                return ExtractBytesFromStream(fileStream);
            }
        }

        private static byte[] ExtractBytesFromStream(Stream fileStream)
        {
            if (fileStream == null) return null;
            var bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            return bytes;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
cirva
=====

What is this?
-------------

Scripts to grab and parse data from Center for Investigative Reporting's Veterans Affairs backlog API into CSVs.

https://github.com/cirlabs/va-data-dashboard#data-updates

You can see the data at:
http://tdbeta.digitalfirstmedia.com/cirva/

The resulting story ran here, with our interactive chart: http://www.sltrib.com/sltrib/news/56473395-78/claims-veterans-lake-salt.html.csp?page=1

![the chart](screenshots/cirva.png)

Credits
---------

Data from CIR's VA backlog API. Scripts by Tom Meagher. Interactive chart built by Sarah Glen, Vaughn Hagerty, Nelson Hsu and Tom Meagher.

Assumptions
-----------

Requirements for these scripts are simple: You need Python 2.7 and the [Requests library](http://docs.python-requests.org/en/latest/). To install Requests, while inside your [virtualenv](http://virtualenvwrapper.readthedocs.org/en/latest/) type `pip install requests`.

After you run it the first time, it's easy to get updates or even automate the process.
First, run `python updates.py`, which looks at the CSVs you've already grabbed and gets newer data from the API.
Then, run `python makestats.py`, which will create the index.html report page that offers a birds-eye view of the range of the data.

The interactive chart uses the [Highcharts Javascript library](http://www.highcharts.com/).

License
----------

This code is available under the MIT license. For more information, please see the LICENSE file in this repo.


text:
'use strict';

const path = require('path');
const sassTrue = require('sass-true');

let sassFile = path.join(__dirname, '_index.scss');

sassTrue.runSass(
    {
        file: sassFile,
        includePaths: [path.join(__dirname, '../src')]
    },
    describe,
    it
);


text:
// See docs in ../ops/image_ops.cc
#define EIGEN_USE_THREADS

#include <memory>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/public/status.h"
#include "tensorflow/core/public/tensor.h"
#include "tensorflow/core/public/tensor_shape.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;

template <typename Device, typename T>
class ResizeBilinearOp : public OpKernel {
 public:
  explicit ResizeBilinearOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    OP_REQUIRES(context, input.dims() == 4,
                errors::InvalidArgument("input must be 4-dimensional",
                                        input.shape().ShortDebugString()));
    const Tensor& shape_t = context->input(1);
    OP_REQUIRES(context, shape_t.dims() == 1,
                errors::InvalidArgument("shape_t must be 1-dimensional",
                                        shape_t.shape().ShortDebugString()));
    OP_REQUIRES(context, shape_t.NumElements() == 2,
                errors::InvalidArgument("shape_t must have two elements",
                                        shape_t.shape().ShortDebugString()));

    auto Svec = shape_t.vec<int32>();
    // Initialize shape to the batch size of the input, then add
    // the rest of the dimensions
    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                0, TensorShape({input.dim_size(0), Svec(0),
                                                Svec(1), input.dim_size(3)}),
                                &output));

    const int64 batch_size = input.dim_size(0);
    const int64 in_height = input.dim_size(1);
    const int64 in_width = input.dim_size(2);
    const int64 channels = input.dim_size(3);
    const int64 out_height = output->dim_size(1);
    const int64 out_width = output->dim_size(2);

    typename TTypes<T, 4>::ConstTensor input_data = input.tensor<T, 4>();
    typename TTypes<float, 4>::Tensor output_data = output->tensor<float, 4>();

    const float height_scale = in_height / static_cast<float>(out_height);
    const float width_scale = in_width / static_cast<float>(out_width);

    for (int b = 0; b < batch_size; ++b) {
      for (int y = 0; y < out_height; ++y) {
        const float in_y = y * height_scale;
        const int top_y_index = static_cast<int>(floorf(in_y));
        const int bottom_y_index =
            std::min(static_cast<int64>(ceilf(in_y)), (in_height - 1));
        const float y_lerp = in_y - top_y_index;
        const float inverse_y_lerp = (1.0f - y_lerp);
        for (int x = 0; x < out_width; ++x) {
          const float in_x = x * width_scale;
          const int left_x_index = static_cast<int>(floorf(in_x));
          const int right_x_index =
              std::min(static_cast<int64>(ceilf(in_x)), (in_width - 1));
          const float x_lerp = in_x - left_x_index;
          const float inverse_x_lerp = (1.0f - x_lerp);
          for (int c = 0; c < channels; ++c) {
            const float top_left = input_data(b, top_y_index, left_x_index, c);
            const float top_right =
                input_data(b, top_y_index, right_x_index, c);
            const float bottom_left =
                input_data(b, bottom_y_index, left_x_index, c);
            const float bottom_right =
                input_data(b, bottom_y_index, right_x_index, c);
            const float top =
                (top_left * inverse_x_lerp) + (top_right * x_lerp);
            const float bottom =
                (bottom_left * inverse_x_lerp) + (bottom_right * x_lerp);
            output_data(b, y, x, c) =
                (top * inverse_y_lerp) + (bottom * y_lerp);
          }
        }
      }
    }
  }
};

template <typename Device, typename T>
class ResizeBilinearOpGrad : public OpKernel {
 public:
  explicit ResizeBilinearOpGrad(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    // Validate input.
    // First argument is gradient with respect to resized image.
    const Tensor& input = context->input(0);
    OP_REQUIRES(context, input.dims() == 4,
                errors::InvalidArgument("input_grad must be 4-dimensional",
                                        input.shape().ShortDebugString()));
    // ResizeBilinear always produces float images, so the input gradient is
    // always a float.
    OP_REQUIRES(context, input.dtype() == DT_FLOAT,
                errors::InvalidArgument("input_grad must be of type float",
                                        input.dtype()));

    // The second argument is the original input to resize_bilinear.
    const Tensor& original_image = context->input(1);
    OP_REQUIRES(
        context, original_image.dims() == 4,
        errors::InvalidArgument("original_image must be 4-dimensional",
                                original_image.shape().ShortDebugString()));

    // Allocate output and initialize to zeros.
    const int64 batch_size = input.dim_size(0);
    const int64 channels = input.dim_size(3);
    const int64 resized_height = input.dim_size(1);
    const int64 resized_width = input.dim_size(2);
    const int64 original_height = original_image.dim_size(1);
    const int64 original_width = original_image.dim_size(2);
    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                0, TensorShape({batch_size, original_height,
                                                original_width, channels}),
                                &output));

    typename TTypes<float, 4>::ConstTensor input_grad =
        input.tensor<float, 4>();
    typename TTypes<T, 4>::Tensor output_grad = output->tensor<T, 4>();

    for (int c = 0; c < channels; ++c) {
      for (int y = 0; y < original_height; ++y) {
        for (int x = 0; x < original_width; ++x) {
          for (int b = 0; b < batch_size; ++b) {
            output_grad(b, y, x, c) = 0;
          }
        }
      }
    }

    const float height_scale =
        original_height / static_cast<float>(resized_height);
    const float width_scale =
        original_width / static_cast<float>(resized_width);

    // Each resized pixel was computed as a weighted average of four input
    // pixels. Here we find the pixels that contributed to each output pixel
    // and add the corresponding coefficient to the gradient.
    // resized(b, y, x, c) = top_left * (1 - y) * (1 - x)
    //                       +  top_right * (1 - y) * x
    //                       +  bottom_left * y * (1 - x)
    //                       +  bottom_right * y * x
    for (int b = 0; b < batch_size; ++b) {
      for (int y = 0; y < resized_height; ++y) {
        const float in_y = y * height_scale;
        const int top_y_index = static_cast<int>(floorf(in_y));
        const int bottom_y_index =
            std::min(static_cast<int64>(ceilf(in_y)), (original_height - 1));
        const float y_lerp = in_y - top_y_index;
        const float inverse_y_lerp = (1.0f - y_lerp);
        for (int x = 0; x < resized_width; ++x) {
          const float in_x = x * width_scale;
          const int left_x_index = static_cast<int>(floorf(in_x));
          const int right_x_index =
              std::min(static_cast<int64>(ceilf(in_x)), (original_width - 1));
          const float x_lerp = in_x - left_x_index;
          const float inverse_x_lerp = (1.0f - x_lerp);
          for (int c = 0; c < channels; ++c) {
            output_grad(b, top_y_index, left_x_index, c) +=
                input_grad(b, y, x, c) * inverse_y_lerp * inverse_x_lerp;
            output_grad(b, top_y_index, right_x_index, c) +=
                input_grad(b, y, x, c) * inverse_y_lerp * x_lerp;
            output_grad(b, bottom_y_index, left_x_index, c) +=
                input_grad(b, y, x, c) * y_lerp * inverse_x_lerp;
            output_grad(b, bottom_y_index, right_x_index, c) +=
                input_grad(b, y, x, c) * y_lerp * x_lerp;
          }
        }
      }
    }
  }
};

#define REGISTER_KERNEL(T)                            \
  REGISTER_KERNEL_BUILDER(Name("ResizeBilinear")      \
                              .Device(DEVICE_CPU)     \
                              .TypeConstraint<T>("T") \
                              .HostMemory("size"),    \
                          ResizeBilinearOp<CPUDevice, T>);

REGISTER_KERNEL(uint8);
REGISTER_KERNEL(int8);
REGISTER_KERNEL(int32);
REGISTER_KERNEL(float);
REGISTER_KERNEL(double);
#undef REGISTER_KERNEL

REGISTER_KERNEL_BUILDER(Name("ResizeBilinearGrad")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<float>("T"),
                        ResizeBilinearOpGrad<CPUDevice, float>);
REGISTER_KERNEL_BUILDER(Name("ResizeBilinearGrad")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<double>("T"),
                        ResizeBilinearOpGrad<CPUDevice, double>);
}  // namespace tensorflow


text:
package com.hazelcast.client.impl.protocol.codec;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;
import com.hazelcast.client.impl.protocol.codec.custom.*;

import javax.annotation.Nullable;

import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

/*
 * This file is auto-generated by the Hazelcast Client Protocol Code Generator.
 * To change this file, edit the templates or the protocol
 * definitions on the https://github.com/hazelcast/hazelcast-client-protocol
 * and regenerate it.
 */

/**
 * Returns a lazy collection view of the values contained in this map.
 */
@Generated("aafd39501cd7ad2e7d47c992b755d882")
public final class ReplicatedMapValuesCodec {
    //hex: 0x0D1000
    public static final int REQUEST_MESSAGE_TYPE = 856064;
    //hex: 0x0D1001
    public static final int RESPONSE_MESSAGE_TYPE = 856065;
    private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;

    private ReplicatedMapValuesCodec() {
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class RequestParameters {

        /**
         * Name of the ReplicatedMap
         */
        public java.lang.String name;
    }

    public static ClientMessage encodeRequest(java.lang.String name) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        clientMessage.setRetryable(true);
        clientMessage.setOperationName("ReplicatedMap.Values");
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);
        encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);
        clientMessage.add(initialFrame);
        StringCodec.encode(clientMessage, name);
        return clientMessage;
    }

    public static ReplicatedMapValuesCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        RequestParameters request = new RequestParameters();
        //empty initial frame
        iterator.next();
        request.name = StringCodec.decode(iterator);
        return request;
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class ResponseParameters {

        /**
         * A collection view of the values contained in this map.
         */
        public java.util.List<com.hazelcast.internal.serialization.Data> response;
    }

    public static ClientMessage encodeResponse(java.util.Collection<com.hazelcast.internal.serialization.Data> response) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);
        clientMessage.add(initialFrame);

        ListMultiFrameCodec.encode(clientMessage, response, DataCodec::encode);
        return clientMessage;
    }

    public static ReplicatedMapValuesCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        ResponseParameters response = new ResponseParameters();
        //empty initial frame
        iterator.next();
        response.response = ListMultiFrameCodec.decode(iterator, DataCodec::decode);
        return response;
    }

}


text:
#ifndef INK_STROKE_MODELER_INTERNAL_PREDICTION_KALMAN_FILTER_AXIS_PREDICTOR_H_
#define INK_STROKE_MODELER_INTERNAL_PREDICTION_KALMAN_FILTER_AXIS_PREDICTOR_H_

#include <memory>

#include "ink_stroke_modeler/internal/prediction/kalman_filter/kalman_filter.h"

namespace ink {
namespace stroke_model {

// Class to predict on axis.
//
// This predictor use one instance of Kalman filter to predict one dimension of
// stylus movement.
class AxisPredictor {
 public:
  AxisPredictor(double process_noise, double measurement_noise,
                int min_stable_iteration);

  // Return true if the underlying Kalman filter is stable.
  bool Stable() const;

  // Reset the underlying Kalman filter.
  void Reset();

  // Update the predictor with a new observation.
  void Update(double observation);

  // Returns the number of times Update() has been called since the last time
  // the AxisPredictor was reset.
  int NumIterations() const;

  // Get the predicted values from the underlying Kalman filter.
  double GetPosition() const;
  double GetVelocity() const;
  double GetAcceleration() const;
  double GetJerk() const;

 private:
  std::unique_ptr<KalmanFilter> kalman_filter_;
};

}  // namespace stroke_model
}  // namespace ink

#endif  // INK_STROKE_MODELER_INTERNAL_PREDICTION_KALMAN_FILTER_AXIS_PREDICTOR_H_


text:
using System;
using System.Collections.Generic;
using Independentsoft.Office;
using Independentsoft.Office.Word;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            WordDocument doc = new WordDocument("c:\\test\\input.docx");

            IList<IContentElement> elements = doc.GetContentElements();

            foreach (IContentElement element in elements)
            {
                if (element is Hyperlink)
                {
                    Hyperlink link = (Hyperlink)element;

                    Console.WriteLine("Target = " + link.Target);
                }
            }

            Console.Read();
        }
    }
}


text:
<?php

require_once("models/config.php");

setReferralPage(getAbsoluteDocumentPath(__FILE__));

if (!userIdExists('1')){
	addAlert("danger", lang("MASTER_ACCOUNT_NOT_EXISTS"));
	header("Location: install/wizard_root_user.php");
	exit();
}

// If registration is disabled, send them back to the home page with an error message
if (!$can_register){
	addAlert("danger", lang("ACCOUNT_REGISTRATION_DISABLED"));
	header("Location: login.php");
	exit();
}

//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) {
	addAlert("danger", "I'm sorry, you cannot register for an account while logged in.  Please log out first.");
	header("Location: account.php");
	exit();
}

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="css/favicon.ico">

    <title>UserFrosting - Register</title>

	<link rel="icon" type="image/x-icon" href="css/favicon.ico" />

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/jumbotron-narrow.css" rel="stylesheet">

	<link rel="stylesheet" href="css/font-awesome.min.css">
	<link rel="stylesheet" href="css/bootstrap-switch.min.css" type="text/css" />

UserFrosting

Let's get started!

Registration is fast and simple.

		<form name='newUser' id='newUser' class='form-horizontal' role='form' action='api/create_user.php' method='post'>

			Username

					<input type="text" class="form-control" placeholder="Username" name = 'user_name' value='' data-validate='{"minLength": 1, "maxLength": 25, "label": "Username" }'>

			Display Name

					<input type="text" class="form-control" placeholder="Display Name" name='display_name' data-validate='{"minLength": 1, "maxLength": 50, "label": "Display Name" }'>

			Email

					<input type="email" class="form-control" placeholder="Email" name='email' data-validate='{"email": true, "minLength": 1, "maxLength": 150, "label": "Email" }'>

			Password

					<input type="password" class="form-control" placeholder="Password" name='password' data-validate='{"minLength": 8, "maxLength": 50, "passwordMatch": "passwordc", "label": "Password" }'>

			Confirm Password

					<input type="password" class="form-control" placeholder="Confirm Password" name='passwordc' data-validate='{"minLength": 8, "maxLength": 50, "label": "Confirm Password" }'>

			Confirm Security Code

					<input type="text" class="form-control" name='captcha' data-validate='{"minLength": 1, "maxLength": 50, "label": "Confirm Security Code" }'>

			  <button type="submit" class="btn btn-success submit" value='Register'>Register</button>

		</form>

© UserFrosting, 2014


text:
var CustomListItemModel = require('../../../../../../../../../../javascripts/cartodb3/components/custom-list/custom-list-item-model');
var CategoriesListItemView = require('../../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/input-categories/categories-list/categories-list-item-view');
var inputColorCategoriesListItemTemplate = require('../../../../../../../../../../javascripts/cartodb3/components/form-components/editors/fill/input-color/input-categories/input-color-categories-list-item.tpl');

describe('components/form-components/editors/fill/input-color/input-categories/categories-list/categories-list-item-view', function () {
  beforeEach(function () {
    this.model = new CustomListItemModel({
      label: 'hello',
      val: '#FFF',
      image: 'https://s3.amazonaws.com/com.cartodb.users-assets.production/maki-icons/star-stroked-18.svg'
    });

    this.view = new CategoriesListItemView(({
      model: this.model,
      typeLabel: 'column',
      template: inputColorCategoriesListItemTemplate,
      imageEnabled: true
    }));

    spyOn(this.view, '_loadImages');

    this.view.render();
  });

  it('should render properly', function () {
    expect(this.view.$('.CDB-Text').length).toBe(1);
    expect(this.view.$('.CDB-Text').attr('title')).toBe('hello');
    expect(this.view.$('.js-colorPicker').attr('style')).toBe('background-color: #FFF;');
    expect(this.view.$('.js-image-container').length).toBe(1);
  });

  describe('_onClick', function () {
    it('should set js-assetPicker class in model when image is clicked', function () {
      this.view.$('.js-image-container').click();
      expect(this.model.get('selectedClass')).toEqual(['js-assetPicker']);
    });

    it('should set js-assetPicker class in model when IMG label is clicked', function () {
      this.model.unset('image');
      this.view.render();
      this.view.$('.js-assetPicker').click();
      expect(this.model.get('selectedClass')).toEqual(['js-assetPicker']);
    });

    it('should not set js-assetPicker class in model when rest of the item is clicked', function () {
      this.model.unset('image');
      this.view.render();
      this.view.$el.click();
      expect(this.model.get('selectedClass')).toEqual([]);
    });
  });

  it('should not have leaks', function () {
    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function () {
    this.view.remove();
  });
});


text: Rails402::Application.config.session_store :cookie_store, key: '_rails-4_0_2_session'


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//    self.mainViewController = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    self.window.rootViewController = self.mainViewController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end


text:
package com.smcpartners.shape.usecases.find_all_organizations;

import com.smcpartners.shape.crosscutting.security.RequestScopedUserId;
import com.smcpartners.shape.crosscutting.security.annotations.SecureRequireActiveLogActivity;
import com.smcpartners.shape.frameworks.data.dao.shape.OrganizationDAO;
import com.smcpartners.shape.shared.constants.SecurityRoleEnum;
import com.smcpartners.shape.shared.dto.shape.OrganizationDTO;
import com.smcpartners.shape.shared.usecasecommon.UseCaseException;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Responsible:

 * 1. ADMIN and DPH_User roles can see all organizations. ORG_ADMIN and REGISTERED user can see only their organization
 *

 * Created by johndestefano on 11/2/15.
 *

 * Changes:
 */
@RequestScoped
public class FindAllOrganizationsServiceAdapter implements FindAllOrganizationsService {

    @Inject
    private Logger log;

    @EJB
    private OrganizationDAO organizationDAO;

    @Inject
    private RequestScopedUserId requestScopedUserId;

    public FindAllOrganizationsServiceAdapter() {
    }

    @Override
    @SecureRequireActiveLogActivity({SecurityRoleEnum.ADMIN, SecurityRoleEnum.DPH_USER, SecurityRoleEnum.ORG_ADMIN, SecurityRoleEnum.REGISTERED})
    public List<OrganizationDTO> findAllOrganizations() throws UseCaseException {
        try {
            List<OrganizationDTO> retLst = new ArrayList<>();

            // ADMIN role can see all organizations
            // ORG_ADMIN can see only their organization
            SecurityRoleEnum reqUserRole = SecurityRoleEnum.valueOf(requestScopedUserId.getSecurityRole());

            if (SecurityRoleEnum.ADMIN == reqUserRole || SecurityRoleEnum.DPH_USER == reqUserRole) {
                List<OrganizationDTO> lst = organizationDAO.findAll();
                lst.forEach(l -> {
                    OrganizationDTO dto = new OrganizationDTO();
                    dto.setId(l.getId());
                    dto.setName(l.getName());
                    dto.setActive(l.isActive());
                    dto.setAddressStreet(l.getAddressStreet());
                    dto.setAddressCity(l.getAddressCity());
                    dto.setAddressState(l.getAddressState());
                    dto.setAddressZip(l.getAddressZip());
                    dto.setPhone(l.getPhone());
                    dto.setPrimaryContactPhone(l.getPrimaryContactPhone());
                    dto.setPrimaryContactName(l.getPrimaryContactName());
                    dto.setPrimaryContactEmail(l.getPrimaryContactEmail());
                    dto.setPrimaryContactRole(l.getPrimaryContactRole());
                    retLst.add(dto);
                });
            } else if (SecurityRoleEnum.ORG_ADMIN == reqUserRole || SecurityRoleEnum.REGISTERED == reqUserRole){
                // Find the organization
                OrganizationDTO orgDTO = organizationDAO.findById(requestScopedUserId.getOrgId());

                // Add to lst
                OrganizationDTO dto = new OrganizationDTO();
                dto.setId(orgDTO.getId());
                dto.setName(orgDTO.getName());
                dto.setActive(orgDTO.isActive());
                dto.setAddressStreet(orgDTO.getAddressStreet());
                dto.setAddressCity(orgDTO.getAddressCity());
                dto.setAddressState(orgDTO.getAddressState());
                dto.setAddressZip(orgDTO.getAddressZip());
                dto.setPhone(orgDTO.getPhone());
                dto.setPrimaryContactPhone(orgDTO.getPrimaryContactPhone());
                dto.setPrimaryContactName(orgDTO.getPrimaryContactName());
                dto.setPrimaryContactEmail(orgDTO.getPrimaryContactEmail());
                dto.setPrimaryContactRole(orgDTO.getPrimaryContactRole());
                retLst.add(dto);
            }

            return retLst;
        } catch (Exception e) {
            log.logp(Level.SEVERE, this.getClass().getName(), "findAllOrganizations", e.getMessage(), e);
            throw new UseCaseException(e.getMessage());
        }
    }
}


text:
/* Galleria Classic Theme 2012-08-07 | https://raw.github.com/aino/galleria/master/LICENSE | (c) Aino */

#galleria-loader{height:1px!important}

.galleria-container {
    position: relative;
    overflow: hidden;
}
.galleria-container img {
    -moz-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
}
.galleria-stage {
    position: absolute;
    top: 10px;
    bottom: 60px;
    left: 10px;
    right: 10px;
    overflow:hidden;
}
.galleria-thumbnails-container {
    height: 50px;
    bottom: 0;
    position: absolute;
    left: 10px;
    right: 10px;
    z-index: 2;
}
.galleria-carousel .galleria-thumbnails-list {
    margin-left: 30px;
    margin-right: 30px;
}
.galleria-thumbnails .galleria-image {
    height: 40px;
    width: 60px;
    margin: 0 5px 0 0;
    float: left;
    cursor: pointer;
}
.galleria-counter {
    position: absolute;
    bottom: 10px;
    left: 10px;
    text-align: right;
    color: #fff;
    font: normal 11px/1 arial,sans-serif;
    z-index: 1;
}
.galleria-loader {
    width: 20px;
    height: 20px;
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 2;
    display: none;
    background: url(classic-loader.gif) no-repeat 2px 2px;
}
.galleria-info {
    width:90%;
    /*width: 50%;
    top: 15px;
    left: 15px;*/
    position: relative;
    z-index: 5;
    margin:auto;
    display:block;
    background-color: rgba(71,71,71,.5);
}
.galleria-info-text {
    color: #000;
    padding: 5px;
    display: none;
    /* IE7 */ zoom:1;
}
.galleria-info-title {
    font: bold 12px/1.1 arial,sans-serif;
    margin: 0;
    color: #fff;
    text-shadow: 1px, 1px, 1px, black;
    padding:3px;
}
.galleria-info-description {
    font: italic 12px/1.4 georgia,serif;
    margin: 0;
    color: #000;
}
.galleria-info-close {
    width: 9px;
    height: 9px;
    position: absolute;
    top: 5px;
    right: 5px;
    background-position: -753px -11px;
    opacity: .5;
    filter: alpha(opacity=50);
    cursor: pointer;
    display: none;
}
.notouch .galleria-info-close:hover{
    opacity:1;
    filter: alpha(opacity=100);
}
.touch .galleria-info-close:active{
    opacity:1;
    filter: alpha(opacity=100);
}
.galleria-info-link {
    background-position: -669px -5px;
    opacity: .8;
    filter: alpha(opacity=80);
    position: absolute;
    width: 20px;
    height: 20px;
    cursor: pointer;
    background-color: rgba(255,255,255,.2);
    border:1px solid #ccc;
}
.notouch .galleria-info-link:hover {
    opacity: 1;
    filter: alpha(opacity=100);
}
.touch .galleria-info-link:active {
    opacity: 1;
    filter: alpha(opacity=100);
}
.galleria-image-nav {
    position: absolute;
    top: 50%;
    margin-top: -62px;
    width: 100%;
    height: 62px;
    left: 0;
}
.galleria-image-nav-left,
.galleria-image-nav-right {
    opacity: .7;
    filter: alpha(opacity=70);
    cursor: pointer;
    width: 62px;
    height: 124px;
    position: absolute;
    left: 10px;
    z-index: 2;
    background-position: 0 46px;
}
.galleria-image-nav-right {
    left: auto;
    right: 10px;
    background-position: -254px 46px;
    z-index: 2;
}
.notouch .galleria-image-nav-left:hover,
.notouch .galleria-image-nav-right:hover {
    opacity: 1;
    filter: alpha(opacity=100);
}
.touch .galleria-image-nav-left:active,
.touch .galleria-image-nav-right:active {
    opacity: 1;
    filter: alpha(opacity=100);
}
.galleria-thumb-nav-left,
.galleria-thumb-nav-right {
    cursor: pointer;
    display: none;
    background-position: -495px 5px;
    position: absolute;
    left: 0;
    top: 0;
    height: 40px;
    width: 23px;
    z-index: 3;
    opacity: .8;
    filter: alpha(opacity=80);
}
.galleria-thumb-nav-right {
    background-position: -578px 5px;
    border-right: none;
    right: 0;
    left: auto;
}
.galleria-thumbnails-container .disabled {
    opacity: .2;
    filter: alpha(opacity=20);
    cursor: default;
}
.notouch .galleria-thumb-nav-left:hover,
.notouch .galleria-thumb-nav-right:hover {
    opacity: 1;
    filter: alpha(opacity=100);
    color: #000;
}
.touch .galleria-thumb-nav-left:active,
.touch .galleria-thumb-nav-right:active {
    opacity: 1;
    filter: alpha(opacity=100);
    color: #000;
}
.notouch .galleria-thumbnails-container .disabled:hover {
    opacity: .2;
    filter: alpha(opacity=20);
    background-color: transparent;
}

.galleria-carousel .galleria-thumb-nav-left,
.galleria-carousel .galleria-thumb-nav-right {
    display: block;
}
.galleria-thumb-nav-left,
.galleria-thumb-nav-right,
.galleria-info-link,
.galleria-info-close,
.galleria-image-nav-left,
.galleria-image-nav-right {
    background-image: url(classic-map.png);
    background-repeat: no-repeat;
}

.galleria-errors{
    visibility:hidden;
    display:none;
}


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

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 0.98.7-hadoop2 Reference Package org.apache.hadoop.hbase.codec.prefixtree.encode.other</title>
		<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.codec.prefixtree.encode.other

Classes

            	CellTypeEncoder

            	ColumnNodeType

            	LongEncoder


text:
{# Home tab of the app, containing messages. #}

        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 40 40" version="1.1">
            <g transform="translate(-297.14285,-466.64792)">
                <circle cx="317.14285" cy="486.64792" r="19.030317" style="stroke-width:1.93936479;"/>
                <path d="m309.24286 477.14791 14.2 0 1.6 3.9-11.2 11.9 9.6 0 1.6 3.2-14.2 0-1.6-3.9 11.2-11.9-9.6 0z"/>
            </g>
        </svg>

            {% trans %}
            Some older messages are unavailable.
            Upgrade your organization
            to access your full message history.
            {% endtrans %}

{% trans %}Welcome to Zulip.{% endtrans %}

            {% trans %}
            See, the thing about it is... there aren't any messages
            here for you right now. I'm sure someone will eventually send
            you one.
            {% endtrans %}

            {% trans %}
            Or, take matters into your own hands,
            and
            compose a new stream message.
            {% endtrans %}

{{ _("Nothing's been sent here yet!") }}

            {% trans %}
            Why not
            start the conversation?
            {% endtrans %}

{{ _('You have no private messages yet!') }}

            {% trans %}
            Why not
            start the conversation?
            {% endtrans %}

{{ _('You have no private messages with this person yet!') }}

            {% trans %}
            Why not
            start the conversation?
            {% endtrans %}

{{ _('You have not sent any private messages to yourself yet!') }}

            {% trans %}
            Why not
            start a conversation with yourself?
            {% endtrans %}

{{ _('You have no group private messages with this person yet!') }}

            {% trans %}
            Why not
            start the conversation?
            {% endtrans %}

{{ _('You have no private messages with these people yet!') }}

            {% trans %}
            Why not
            start the conversation?
            {% endtrans %}

{{ _("You haven't received any messages sent by this user yet!") }}

{{ _("This user does not exist!") }}

{{ _("One or more of these users do not exist!") }}

{{ _("You aren't subscribed to this stream and nobody has talked about that yet!") }}

            <button class="button white rounded stream_sub_unsub_button sea-green" type="button" name="subscription">
                {{ _('Subscribe') }}
            </button>

{{ _("This stream does not exist or is private.") }}

{{ _("You haven't starred anything yet!") }}

            {% trans %}
            Learn more about starring messages
            here.
            {% endtrans %}

{{ _("You have no unread messages!") }}

{{ _("You haven't been mentioned yet!") }}

            {% trans %}
            Learn more about mentions
            here.
            {% endtrans %}

{{ _('No search results') }}

{% include "zerver/app/message_history.html" %}
{% include "zerver/app/delete_message.html" %}
{% include "zerver/app/compose.html" %}


text:
'use strict';

var React = require('react/addons');
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var blacklist = require('blacklist');
var classNames = require('classnames');

module.exports = React.createClass({
	displayName: 'Modal',
	propTypes: {
		backdropClosesModal: React.PropTypes.bool,
		className: React.PropTypes.string,
		isOpen: React.PropTypes.bool,
		onCancel: React.PropTypes.func,
		top: React.PropTypes.number
	},
	renderDialog: function renderDialog() {
		if (!this.props.isOpen) return null;

		var top = typeof this.props.top !== 'undefined' ? this.props.top : window.pageYOffset;

		return React.createElement(
			'div',
			{ className: 'Modal-dialog', style: { top: top } },
			React.createElement(
				'div',
				{ className: 'Modal-content' },
				this.props.children
			)
		);
	},
	renderBackdrop: function renderBackdrop() {
		if (!this.props.isOpen) return null;

		return React.createElement('div', { className: 'Modal-backdrop', onClick: this.props.backdropClosesModal ? this.props.onCancel : null });
	},
	render: function render() {
		// classes
		var className = classNames('Modal', this.props.className);

		// props
		var props = blacklist(this.props, 'backdropClosesModal', 'className', 'headerHasCloseButton', 'headerTitle', 'isOpen');
		props.className = className;

		return React.createElement(
			'div',
			props,
			React.createElement(
				ReactCSSTransitionGroup,
				{ transitionName: 'Modal-dialog', component: 'div' },
				this.renderDialog()
			),
			React.createElement(
				ReactCSSTransitionGroup,
				{ transitionName: 'Modal-background', component: 'div' },
				this.renderBackdrop()
			)
		);
	}
});

// expose the children to the top level export
module.exports.Body = require('./ModalBody');
module.exports.Footer = require('./ModalFooter');
module.exports.Header = require('./ModalHeader');


text:
battery
=======

Prints out the status of your battery. Percentage and its state.

lowbatteryd
===========

Shell script that checks your battery percentage and executes commands at three
levels.

Run it in the background to get notifications before the battery dies.


text:
<?php

namespace Illuminate\Tests\Blade;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\View\Compilers\BladeCompiler;

class BladeSectionTest extends TestCase
{
    public function tearDown()
    {
        m::close();
    }

    public function testSectionStartsAreCompiled()
    {
        $compiler = new BladeCompiler($this->getFiles(), __DIR__);
        $this->assertEquals('<?php $__env->startSection(\'foo\'); ?>', $compiler->compileString('@section(\'foo\')'));
        $this->assertEquals('<?php $__env->startSection(name(foo)); ?>', $compiler->compileString('@section(name(foo))'));
    }

    protected function getFiles()
    {
        return m::mock('Illuminate\Filesystem\Filesystem');
    }
}


text:
package com.koch.ambeth.merge.transfer;

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

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import com.koch.ambeth.merge.model.ICUDResult;
import com.koch.ambeth.merge.model.IChangeContainer;

@XmlRootElement(name = "CUDResult", namespace = "http://schema.kochdev.com/Ambeth")
@XmlAccessorType(XmlAccessType.FIELD)
public class CUDResult implements ICUDResult {
	@XmlElement(required = true)
	protected List<IChangeContainer> allChanges;

	@XmlTransient
	protected Map<Class<?>, List<IChangeContainer>> typeToModDict;

	@XmlTransient
	protected List<Object> originalRefs;

	public CUDResult() {
		allChanges = new ArrayList<>();
	}

	public CUDResult(List<IChangeContainer> allChanges, List<Object> originalRefs) {
		this.allChanges = new ArrayList<>();
		for (int a = 0, size = allChanges.size(); a < size; a++) {
			this.allChanges.add(allChanges.get(a));
		}
		this.originalRefs = originalRefs;
	}

	public void setAllChanges(List<IChangeContainer> allChanges) {
		this.allChanges = allChanges;
	}

	@Override
	public List<IChangeContainer> getAllChanges() {
		return allChanges;
	}

	@Override
	public List<Object> getOriginalRefs() {
		return originalRefs;
	}

	@Override
	public List<IChangeContainer> getChanges(Class<?> type) {
		if (typeToModDict != null) {
			return typeToModDict.get(type);
		}
		typeToModDict = new HashMap<>();

		for (int a = allChanges.size(); a-- > 0;) {
			IChangeContainer changeContainer = allChanges.get(a);
			Class<?> realType = changeContainer.getReference().getRealType();
			List<IChangeContainer> modList = typeToModDict.get(realType);
			if (modList == null) {
				modList = new ArrayList<>();
				typeToModDict.put(realType, modList);
			}
			modList.add(changeContainer);
		}
		return typeToModDict.get(type);
	}

}


text:
package org.apache.camel.component.cache;

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class ObjectCacheProducerTest extends CamelTestSupport {

    @EndpointInject(uri = "mock:ObjectCacheProducerTest.result")
    protected MockEndpoint resultEndpoint;

    @EndpointInject(uri = "mock:ObjectCacheProducerTest.cacheException")
    protected MockEndpoint cacheExceptionEndpoint;

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    /**
     * Test storing 3 elements into object cache then retrieving them back.
     * We allow cache to store maximum of 2 values to check that overflow to disk not happened (it is not
     * allowed in ehcache object cache (not serializable cache)).
     *
     * @throws Exception
     * @see net.sf.ehcache.Element for information about object cache operations in ehcache
     */
    @Test
    public void testAddingMultipleDataInCacheAndGettingBack() throws Exception {
        context.addRoutes(new RouteBuilder() {
            public void configure() {
                onException(Exception.class).
                        handled(true).
                        to("log:LOGGER").
                        to("mock:ObjectCacheProducerTest.cacheException");

                from("direct:a").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2");
                from("direct:aGet").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_GET)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2").
                        choice().when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNotNull()).
                        to("mock:ObjectCacheProducerTest.result").end();

                from("direct:b").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson_2")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2");
                from("direct:bGet").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_GET)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson_2")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2").
                        choice().when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNotNull()).
                        to("mock:ObjectCacheProducerTest.result").end();

                from("direct:c").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson_3")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2");
                from("direct:cGet").
                        setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_GET)).
                        setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson_3")).
                        to("cache://TestCache1?objectCache=true&overflowToDisk=false&diskPersistent=false&maxElementsInMemory=2").
                        choice().when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNotNull()).
                        to("mock:ObjectCacheProducerTest.result").end();
            }
        });
        context.setTracing(true);
        context.start();
        resultEndpoint.expectedMessageCount(2);
        cacheExceptionEndpoint.expectedMessageCount(0);
        log.debug("------------Beginning CacheProducer Add and Get Test---------------");

        log.debug("Putting data into cache");
        sendNonSerializedData("direct:a", newPoetry("Ralph Waldo Emerson", "Brahma"));
        sendNonSerializedData("direct:b", newPoetry("Ralph Waldo Emerson", "The Rhodora"));
        sendNonSerializedData("direct:c", newPoetry("Ralph Waldo Emerson", "Concord Hymn"));

        log.debug("Retrieving data from cache");
        sendEmptyBody("direct:aGet");
        sendEmptyBody("direct:bGet");
        sendEmptyBody("direct:cGet");

        cacheExceptionEndpoint.assertIsSatisfied();
        resultEndpoint.assertIsSatisfied();
    }

    private void sendNonSerializedData(String endpoint, final PoetryNotSerializable notSerializable) throws Exception {
        template.send(endpoint, new Processor() {
            public void process(Exchange exchange) throws Exception {
                // Set the property of the charset encoding
                exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");
                Message in = exchange.getIn();
                in.setBody(notSerializable);
            }
        });
    }

    private void sendEmptyBody(String endpoint) {
        template.send(endpoint, new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody(null);
            }
        });
    }

    private PoetryNotSerializable newPoetry(String poet, String poem) {
        PoetryNotSerializable poetry = new PoetryNotSerializable();
        poetry.setPoet(poet);
        poetry.setPoem(poem);
        return poetry;
    }
}


text:
<!DOCTYPE html>
<html class='reftest-wait'>
  <link rel='stylesheet' type='text/css' href='style.css'>
  <body onload="document.getElementById('t').value = '';
                document.documentElement.className = '';">
    <form novalidate>
      <textarea id='t' required class='notinvalid'></textarea>
    </form>
  </body>
</html>


text:
require "action_dispatch/journey/visitors"

module ActionDispatch
  module Journey # :nodoc:
    module Nodes # :nodoc:
      class Node # :nodoc:
        include Enumerable

        attr_accessor :left, :memo

        def initialize(left)
          @left = left
          @memo = nil
        end

        def each(&block)
          Visitors::Each::INSTANCE.accept(self, block)
        end

        def to_s
          Visitors::String::INSTANCE.accept(self, "")
        end

        def to_dot
          Visitors::Dot::INSTANCE.accept(self)
        end

        def to_sym
          name.to_sym
        end

        def name
          left.tr "*:".freeze, "".freeze
        end

        def type
          raise NotImplementedError
        end

        def symbol?; false; end
        def literal?; false; end
        def terminal?; false; end
        def star?; false; end
        def cat?; false; end
        def group?; false; end
      end

      class Terminal < Node # :nodoc:
        alias :symbol :left
        def terminal?; true; end
      end

      class Literal < Terminal # :nodoc:
        def literal?; true; end
        def type; :LITERAL; end
      end

      class Dummy < Literal # :nodoc:
        def initialize(x = Object.new)
          super
        end

        def literal?; false; end
      end

      %w{ Symbol Slash Dot }.each do |t|
        class_eval <<-eoruby, __FILE__, __LINE__ + 1
          class #{t} < Terminal;
            def type; :#{t.upcase}; end
          end
        eoruby
      end

      class Symbol < Terminal # :nodoc:
        attr_accessor :regexp
        alias :symbol :regexp
        attr_reader :name

        DEFAULT_EXP = /[^\.\/\?]+/
        def initialize(left)
          super
          @regexp = DEFAULT_EXP
          @name = left.tr "*:".freeze, "".freeze
        end

        def default_regexp?
          regexp == DEFAULT_EXP
        end

        def symbol?; true; end
      end

      class Unary < Node # :nodoc:
        def children; [left] end
      end

      class Group < Unary # :nodoc:
        def type; :GROUP; end
        def group?; true; end
      end

      class Star < Unary # :nodoc:
        def star?; true; end
        def type; :STAR; end

        def name
          left.name.tr "*:", ""
        end
      end

      class Binary < Node # :nodoc:
        attr_accessor :right

        def initialize(left, right)
          super(left)
          @right = right
        end

        def children; [left, right] end
      end

      class Cat < Binary # :nodoc:
        def cat?; true; end
        def type; :CAT; end
      end

      class Or < Node # :nodoc:
        attr_reader :children

        def initialize(children)
          @children = children
        end

        def type; :OR; end
      end
    end
  end
end


text:
Lightweight wrapper around Flipper to initialize nicely in rails apps

## Usage

### Installation

Add flipper-rails to your Gemfile:

```
gem 'flipper-rails'
```

If you'd like to use the adapter for ActiveRecord, Mongo or Redis, include the relevant Gem too:

```
gem 'flipper-active_record` # or flipper-mongo, flipper-redis
```

### Configuration

Configure your application (`config/application.rb` or `config/environments/<env>.rb`) with the adapter and options to use:

```
  config.flipper = {
    adapter: Flipper::Adapters::ActiveRecord,
    adapter_options: {}
  }
```

or

```
  config.flipper = {
    adapter: Flipper::Adapters::Redis,
    adapter_options: Redis::Namespace.new(:flipper_namespace, redis: Redis.new)
  }
```

### In-App

Now to access flipper in-app, you can access it with `Flipper::Rails.flipper` e.g.  `Flipper::Rails.flipper[:search].enabled?`

## ActiveRecord

The Flipper gem has a migration built in to create the migration that creates the flipper tables: `rails g flipper:active_record`


text:
using System;
using System.Globalization;
using System.Runtime.Serialization;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// The exception that is thrown when an error occurs during application execution.
    /// </summary>
    [Serializable]
    public class LibGit2SharpException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LibGit2SharpException"/> class.
        /// </summary>
        public LibGit2SharpException()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LibGit2SharpException"/> class with a specified error message.
        /// </summary>
        /// <param name="message">A message that describes the error.</param>
        public LibGit2SharpException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LibGit2SharpException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception. If the <paramref name="innerException"/> parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
        public LibGit2SharpException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LibGit2SharpException"/> class with a serialized data.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
        protected LibGit2SharpException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        internal LibGit2SharpException(string message, GitErrorCode code, GitErrorCategory category) : this(message)
        {
            Data.Add("libgit2.code", (int)code);
            Data.Add("libgit2.category", (int)category);

        }
    }
}


text:
var Debug = debug.Debug;
var exception = null;
var delegate = null;
var done = false;

function listener(event, exec_state, event_data, data) {
  if (event != Debug.DebugEvent.Break) return;
  try {
    assertEquals([ debug.ScopeType.Block,
                   debug.ScopeType.Script,
                   debug.ScopeType.Global ],
                 exec_state.frame(0).allScopes().map(s => s.scopeType()));
    done = true;
  } catch (e) {
    exception = e;
  }
}

Debug.setListener(listener);

for(let a = 0; a < 3; a++) {
  debugger;
  eval();  // Force context-allocation of everything.
}

Debug.setListener(null);
assertNull(exception);
assertTrue(done);


text:
Each instantaneous value is of one of 2 kinds

* Scalar
* Vector

## Scalar values
There are 5 scalar values: $H$, $L$, $Z$, $X$, and $E$.

These are arranged in a semilattice such that

* $E < x$ for all $x$ in ${H,L,Z,X}$
* $X < x$ for all $x$ in ${H,L,Z}$
* $y \ge x$ in all other cases

Scalar values have depth 0.

### Explanation

$H$ represents a high voltage state. $L$ represents a low voltage state. $Z$ represents a high impedance state. $Z$ is used for tri-state output and is also the output value for input gates.

$E$ represents any kind of error condition.  Errors should not happen in a well designed circuit that is used properly. So errors should only arise from bad design or bad use. $E$ values in practice are associated with zero or more error messages.

Finally $X$ represents an unknown or don't care value.  Certain devices may output an unknown value when they are in transition. For example if a device has a minimum delay $\delta_0$ and a maximum delay $\delta_1$, then, if an input change at time $t$ causes a state change in the output, then the value of the output will be unknown from time $t+\delta_0$ to time $t+\delta_1$.

Another role for $X$ is as a don't care for an expected output. When we specify a decoder, it might be that we don't care what its output is for certain inputs. We might not care what the output is, but we do care that it's not an error, so we should test the device on those inputs, but give $X$ as the expected output for inputs where we don't care about the value.  Another example is where a specification is loose about time.  Say we need a device to react within 10 ns, but it's ok it it's faster.  Then the expected output would be given as $X$ from the time the input changes until 10 ns after that.

Finally, we can use don't care values to fill out the signal values. This allows us to use total functions for signal values and we can give a don't care value the times that we really aren't interested in.

### Resolution

During simulation, values from various ports need to be resolved.

## Vector values
A vector value is a sequence of 0 or more instantaneous values, called its items, each with lesser depth. The depth of a vector is 1 plus the depth of its deepest item.  The length of a vector is the number of children it has. For example $[H,L,[ ]]$ is a tuple of length 3 and depth 2.  Tuples are written in Arabic order, e.g., item 0 of $[H,L,[]]$ is $[]$, item 1 is $L$ and item 2 is $H$.

### Explanation

Often in circuit diagrams we use one net --a net is a maximal set of connected links-- to represent multiple parallel wires.  If similitude had strong typing (like VHDL), then we would perhaps indicate, for one link in each net, how many wires it represents. However that would mean that we could't reuse the same component for different widths.  The VHDL approach involves generics and that's a great approach, but complicated.  The similitude approach is to let any link carry any number of values at once by using vectors.

We allow vectors to nest, so that complex busses can be represented too.  For example, a vector $[a,d,c]$ might represent the value of a bus where $c$, $d$, and $a$ are vectors representing control values, a data value, and an address.

## Error values

Any instantaneous value that contains an $E$ anywhere in it is an error value.  Each $E$ value has zero on more messages associated with it.

## Operations on instantaneous values

Length: $\#x$ is the length of $x$.  This applies only to vectors.

Catenation: Vectors can be catenated to make a new value whose length is the sum of the operands. For example

* $[H] \smallfrown [L] = [H,L]$
* $[U]  \smallfrown [] = [X]$
* $[H,L] \smallfrown [L,L,H]=[H,L,L,L,H)]$

Index: $x(i)$ where $i$ is an integer. This is defined when $x$ is a vector and $0\le 0 < \#x$. When the indexing is not defined, the result is $E$.

Substring: $x(i,..j)$, where $i$ and $j$ are integers. This is defined when $x$ is a vector and every $k$ such that $i \le i < j$ is such that $0 \le k < \#x$. This is the value made by forming a vector $[x(j-1), x(j-2), ... x(i)]$.  In particular when $i \ge j$, the result is the empty vector.  In the undefined cases, it is $E$.

[Note: When defined, the length of the result is $\max(j-i,0)$.]

##Lifting

Logical operations such as AND, OR, IMPLIES, and resolution, are defined on the scalars by a truth tables. These scalar operations are then lifted to instantaneous values as follows. Here $s$ is any scalar value and @ represents any scalar operation

* $s @ [v_n-1, ... , v_1, v_0] = [s] @ [v_n-1, ... , v_1, v_0]= [s @ v_n-1, ... , s @ v_1, s @ v_0]$
* $[v_{n-1}, ... , v_1, v_0] @ s = [v_{n-1}, ... , v_1, v_0] @ [s]  = [v_{n-1} @ s, ... , v_1 @ s, v_0 @ s]$
* $[v_{n-1}, ... , v_1, v_0] @ [w_{n-1}, ..., w_1, w_0) = [v_{n-1} @ w_{n-1}, ... , v_1 @ w_1, v_0 @ w_0)$
* $[v_m-1, ... , v1, v0] @ [w_n-1, ..., w1, w0] = [E]$ when $m\not=n$ and neither length is 1.

This lifting is recursive. For example $[H, L]\; AND\; [[H,L],[H,L]] = [[H,L],[L,L]]$.

##Represetations

Number representation. Given a nonnegative integer $n$ and a nonnegative length $k$, we can define a representation of $n$ as an instantaneous value by $repr(n, k)$ as follows

*   $repr(0, 0) = []$
*   $repr(0, 1) = [L]$
*   $repr(1, 1) = [H]$
*   $repr(n, k)$, when $k > 1$ and $0 \le n < 2^k$ is a tuple $x$ of length $k$ so that $x$ is the unsigned magnitude representation of $n$. For example $repr(6,3) = [H,H,L]$.

For negative integer $n$, $repr(n,k)$ gives the two's complement representation. In particular

* $repr(-1,1) = [H]$
* $repr(-n,k)$, when $k > 1$ and $0 < n \le 2^{k-1}$ is a tuple $x$ of length $k$ the two's complement representation of $-n$. For example $repr(-2,3)$ is $[H,H,L]$.

In all other cases, $repr(n,k)$ is $[E]$.

# Time

A time is a nonnegative number from 0 to $2^{64}-1$.  Each unit of time represents a femtosecond.

[This model might change in the future to one where a time is a pair $(t,u)$ where $t$ is a number of femtoseconds and $u$ is a natural number of simulation cycles (deltas).]

# Signal values

A signal value is a function from time to the set of vector values.

Signal values are used to represent (a) inputs to a system, (b) values that are created by simulation, and (c) expected values used in tests.

## Vectorization

If the result of an operation is a scalar, it can't be the value of a signal at any time, so  we sometimes need to convert the scalar to a vector of length 1.  For example the result of an operation might be $E$, but in this case, to add it to a signal, we need to convert it to $[E]$.


text:
Summary.

Main docstring content.


text:
#include "OgreD3D9RenderSystem.h"
#include "OgreD3D9HardwareBufferManager.h"
#include "OgreD3D9HardwareVertexBuffer.h"
#include "OgreD3D9HardwareIndexBuffer.h"
#include "OgreD3D9VertexDeclaration.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreException.h"

namespace Ogre {
    //-----------------------------------------------------------------------
    D3D9HardwareBufferManagerBase::D3D9HardwareBufferManagerBase()
    {
    }
    //-----------------------------------------------------------------------
    D3D9HardwareBufferManagerBase::~D3D9HardwareBufferManagerBase()
    {
        destroyAllDeclarations();
        destroyAllBindings();
    }
    //-----------------------------------------------------------------------
    HardwareVertexBufferSharedPtr
    D3D9HardwareBufferManagerBase::
    createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage,
		bool useShadowBuffer)
    {
		assert (numVerts > 0);
#if OGRE_D3D_MANAGE_BUFFERS
        // Override shadow buffer setting; managed buffers are automatically
        // backed by system memory
        // Don't override shadow buffer if discardable, since then we use
        // unmanaged buffers for speed (avoids write-through overhead)
		// Don't override if we use directX9EX, since then we don't have managed
		// pool. And creating non-write only default pool causes a performance warning.
		if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) &&
			!D3D9RenderSystem::isDirectX9Ex())
		{
            useShadowBuffer = false;
            // Also drop any WRITE_ONLY so we can read direct
            if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY)
            {
                usage = HardwareBuffer::HBU_DYNAMIC;
            }
            else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY)
            {
                usage = HardwareBuffer::HBU_STATIC;
            }
        }
#endif
		D3D9HardwareVertexBuffer* vbuf = OGRE_NEW D3D9HardwareVertexBuffer(
			this, vertexSize, numVerts, usage, false, useShadowBuffer);
		{
                    OGRE_LOCK_MUTEX(mVertexBuffersMutex);
			mVertexBuffers.insert(vbuf);
		}
        return HardwareVertexBufferSharedPtr(vbuf);
    }
    //-----------------------------------------------------------------------
	HardwareIndexBufferSharedPtr
    D3D9HardwareBufferManagerBase::
    createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes,
        HardwareBuffer::Usage usage, bool useShadowBuffer)
    {
		assert (numIndexes > 0);
#if OGRE_D3D_MANAGE_BUFFERS
        // Override shadow buffer setting; managed buffers are automatically
        // backed by system memory
		// Don't override shadow buffer if discardable, since then we use
		// unmanaged buffers for speed (avoids write-through overhead)
		// Don't override if we use directX9EX, since then we don't have managed
		// pool. And creating non-write only default pool causes a performance warning.
		if (useShadowBuffer && !(usage & HardwareBuffer::HBU_DISCARDABLE) &&
			!D3D9RenderSystem::isDirectX9Ex())
		{
            useShadowBuffer = false;
            // Also drop any WRITE_ONLY so we can read direct
            if (usage == HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY)
            {
                usage = HardwareBuffer::HBU_DYNAMIC;
            }
            else if (usage == HardwareBuffer::HBU_STATIC_WRITE_ONLY)
            {
                usage = HardwareBuffer::HBU_STATIC;
            }
        }
#endif
		D3D9HardwareIndexBuffer* idx = OGRE_NEW D3D9HardwareIndexBuffer(
			this, itype, numIndexes, usage, false, useShadowBuffer);
		{
                    OGRE_LOCK_MUTEX(mIndexBuffersMutex);
			mIndexBuffers.insert(idx);
		}
		return HardwareIndexBufferSharedPtr(idx);

    }
    //-----------------------------------------------------------------------
    RenderToVertexBufferSharedPtr
        D3D9HardwareBufferManagerBase::createRenderToVertexBuffer()
    {
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
            "Direct3D9 does not support render to vertex buffer objects",
            "D3D9HardwareBufferManagerBase::createRenderToVertexBuffer");
	}
	//---------------------------------------------------------------------
	HardwareUniformBufferSharedPtr
		D3D9HardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name)
	{
		OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
				"Uniform buffer not supported in Direct3D 9 RenderSystem.",
				"D3D9HardwareBufferManagerBase::createUniformBuffer");
	}
    //-----------------------------------------------------------------------
	HardwareCounterBufferSharedPtr
    D3D9HardwareBufferManagerBase::createCounterBuffer(size_t sizeBytes,
                                                          HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name)
	{
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                    "D3D9 does not support atomic counter buffers",
                    "D3D9HardwareBufferManagerBase::createCounterBuffer");
	}
    //-----------------------------------------------------------------------
    VertexDeclaration* D3D9HardwareBufferManagerBase::createVertexDeclarationImpl(void)
    {
        return OGRE_NEW D3D9VertexDeclaration();
    }
    //-----------------------------------------------------------------------
    void D3D9HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl)
    {
        OGRE_DELETE decl;
    }
}


text:
package ucar.units;

import javax.annotation.concurrent.Immutable;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Provides support for unknown base units. This can be used, for example, to
 * accomodate an unknown unit (e.g. "foo"). Values in such a unit will only be
 * convertible with units derived from "foo" (e.g. "20 foo").
 *
 * @author Steven R. Emmerson
 */
@Immutable
public final class UnknownUnit extends BaseUnit {
  private static final long serialVersionUID = 1L;
  /**
   * The name-to-unit map.
   *
   * @serial
   */
  private static final SortedMap<String, UnknownUnit> map = new TreeMap<>();

  /**
   * Constructs from a name.
   *
   * @param name The name of the unit.
   */
  private UnknownUnit(final String name) throws NameException {
    super(UnitName.newUnitName(name, null, name), BaseQuantity.UNKNOWN);
  }

  /**
   * Factory method for constructing an unknown unit from a name.
   *
   * @param name The name of the unit.
   * @return The unknown unit.
   * @throws NameException name == null.
   */
  public static UnknownUnit create(String name) throws NameException {
    UnknownUnit unit;
    name = name.toLowerCase();
    synchronized (map) {
      unit = map.get(name);
      if (unit == null) {
        unit = new UnknownUnit(name);
        map.put(unit.getName(), unit);
        map.put(unit.getPlural(), unit);
      }
    }
    return unit;
  }

  /*
   * From Unit:
   */

  /**
   * Indicates if this unit is semantically identical to an object.
   *
   * @param object The object.
   * @return true if and only if this instance is semantically
   *         identical to the object.
   */
  @Override
  public boolean equals(final Object object) {
    if (this == object) {
      return true;
    }
    if (!(object instanceof UnknownUnit)) {
      return false;
    }
    final UnknownUnit that = (UnknownUnit) object;
    return getName().equalsIgnoreCase(that.getName());
  }

  /**
   * Returns the hash code of this instance.
   *
   * @return The hash code of this instance.
   */
  @Override
  public int hashCode() {
    return getName().toLowerCase().hashCode();
  }

  /**
   * Indicates if this unit is dimensionless. An unknown unit is never
   * dimensionless.
   *
   * @return false always.
   */
  @Override
  public boolean isDimensionless() {
    return false;
  }

}


text:
@interface SpellFailRainbow : Spell

@end


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
C. S. Sargent, Pl. wilson. 2:338. 1915

#### Original name
null

### Remarks
null


text: This provides the environment for KRL to run.


text:
<?php

namespace Alchemy\Service;

use Alchemy\Application;

use Propel\Runtime\Propel;
use Propel\Runtime\Connection\ConnectionManagerSingle;

/**
 * Propel service provider.
 *
 * @author Erik Amaru Ortiz <aortiz.erik@gmail.com>
 */
class PropelServiceProvider implements ServiceProviderInterface
{
    protected $alreadyInit = false;
    protected $classDir = "";
    protected $config = array();

    public function register(Application $app)
    {
        $app["propel"] = $app->protect(function() use ($app) {
            if (! class_exists('\Propel\Runtime\Propel')) {
                throw new \Exception("Can't register Propel, it is not installed or not loaded!");
            }

            $this->configure($app);
            $this->initPropel();
        });
    }

    public function init(Application $app)
    {
        $app["propel"]();
    }

    protected function configure(Application $app)
    {
        /** @var \Alchemy\Config $config */
        $config = $app["config"];

        $this->classDir = $config->get("propel.class_dir", $config->get("app.model_dir"));
        $this->config["engine"] = $config->get("database.engine", "");
        $this->config["host"] = $config->get("database.host", "");
        $this->config["port"] = $config->get("database.port", "");
        $this->config["user"] = $config->get("database.user", "");
        $this->config["password"] = $config->get("database.password", "");
        $this->config["dbname"] = $config->get("database.dbname", "");

        $requiredConfig = array("engine", "host", "user", "dbname");

        foreach ($requiredConfig as $keyConf => $valConf) {
            $valConf = trim($valConf);

            if (empty($valConf)) {
                throw new \RuntimeException(sprintf(
                    "Propel Service Provider Error: Configuration missing." . PHP_EOL .
                    "Configuration: \"%s.%s\" is missing or empty.",
                    "database", $keyConf
                ));
            }
        }
    }

    protected function initPropel()
    {
        $serviceContainer = Propel::getServiceContainer();
        $serviceContainer->setAdapterClass($this->config["dbname"], $this->config["engine"]);
        $manager = new ConnectionManagerSingle();
        $port = empty($this->config["port"])? "": ";port=".$this->config["port"];
        $manager->setConfiguration(array(
            "dsn" => $this->config["engine"].":host=".$this->config["host"].";dbname=".$this->config["dbname"].$port,
            "user"     => $this->config["user"],
            "password" => $this->config["password"],
        ));
        $serviceContainer->setConnectionManager($this->config["dbname"], $manager);
        $this->alreadyInit = true;
    }
}


text:
<?php

namespace Opulence\Collections;

use ArrayIterator;
use InvalidArgumentException;
use OutOfBoundsException;
use RuntimeException;
use Traversable;

/**
 * Defines an immutable hash table
 */
class ImmutableHashTable implements IImmutableDictionary
{
    /** @var KeyValuePair[] The list of values */
    protected $hashKeysToKvps = [];
    /** @var KeyHasher The key hasher to use */
    private $keyHasher = null;

    /**
     * @param KeyValuePair[] $kvps The list of values to add
     * @throws InvalidArgumentException Thrown if the array contains a non-key-value pair
     * @throws RuntimeException Thrown if a hash key could not be calculated
     */
    public function __construct(array $kvps)
    {
        $this->keyHasher = new KeyHasher();

        foreach ($kvps as $kvp) {
            if (!$kvp instanceof KeyValuePair) {
                throw new InvalidArgumentException('Value must be instance of ' . KeyValuePair::class);
            }

            $this->hashKeysToKvps[$this->getHashKey($kvp->getKey())] = $kvp;
        }
    }

    /**
     * @inheritdoc
     */
    public function containsKey($key) : bool
    {
        return array_key_exists($this->getHashKey($key), $this->hashKeysToKvps);
    }

    /**
     * @inheritdoc
     */
    public function containsValue($value) : bool
    {
        foreach ($this->hashKeysToKvps as $kvp) {
            if ($kvp->getValue() == $value) {
                return true;
            }
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function count() : int
    {
        return count($this->hashKeysToKvps);
    }

    /**
     * @inheritdoc
     */
    public function get($key)
    {
        $hashKey = $this->getHashKey($key);

        if (!$this->containsKey($key)) {
            throw new OutOfBoundsException("Hash key \"$hashKey\" not found");
        }

        return $this->hashKeysToKvps[$hashKey]->getValue();
    }

    /**
     * @inheritdoc
     */
    public function getIterator() : Traversable
    {
        return new ArrayIterator(array_values($this->hashKeysToKvps));
    }

    /**
     * @inheritdoc
     */
    public function getKeys() : array
    {
        $keys = [];

        foreach ($this->hashKeysToKvps as $kvp) {
            $keys[] = $kvp->getKey();
        }

        return $keys;
    }

    /**
     * @inheritdoc
     */
    public function getValues() : array
    {
        $values = [];

        foreach ($this->hashKeysToKvps as $kvp) {
            $values[] = $kvp->getValue();
        }

        return $values;
    }

    /**
     * @inheritdoc
     * @throws RuntimeException Thrown if the value's key could not be calculated
     */
    public function offsetExists($offset) : bool
    {
        return $this->containsKey($offset);
    }

    /**
     * @inheritdoc
     * @throws OutOfBoundsException Thrown if the key could not be found
     * @throws RuntimeException Thrown if the value's key could not be calculated
     */
    #[\ReturnTypeWillChange]
    public function offsetGet($offset)
    {
        return $this->get($offset);
    }

    /**
     * @inheritdoc
     * @throws RuntimeException Thrown because this is immutable
     */
    public function offsetSet($offset, $value) : void
    {
        throw new RuntimeException('Cannot set values in ' . self::class);
    }

    /**
     * @inheritdoc
     * @throws RuntimeException Thrown because this is immutable
     */
    public function offsetUnset($offset) : void
    {
        throw new RuntimeException('Cannot unset values in ' . self::class);
    }

    /**
     * @inheritdoc
     */
    public function toArray() : array
    {
        return array_values($this->hashKeysToKvps);
    }

    /**
     * @inheritdoc
     */
    public function tryGet($key, &$value) : bool
    {
        try {
            $value = $this->get($key);

            return true;
        } catch (OutOfBoundsException $ex) {
            return false;
        }

        return false;
    }

    /**
     * Gets the hash key for a value
     * This method allows extending classes to customize how hash keys are calculated
     *
     * @param string|int|float|array|object|resource $value The value whose hash key we want
     * @return string The hash key
     * @throws RuntimeException Thrown if the hash key could not be calculated
     */
    protected function getHashKey($value) : string
    {
        return $this->keyHasher->getHashKey($value);
    }
}


text:
 function terminalAndGliaMitoAnalysis(annotationfiles, mitofiles,...
    animalid, outputTemplate, summaryfile)
% terminalAndGliaMitoAnalysis(annotationfiles, mitofiles,...
%    animalid, outputfile, summaryfile)
%
% Create terminal and glia mito analysis csv files
%   annotationfiles - a cell array containing the annotation image files
%   mitofiles       - a cell array containing the mitochondria image files
%   animalid        - a cell array of the animal ids
%   outputTemplate  - the template path to the output csv file
%                     should be in printf format with one string argument,
%                     like 'animalstuff_%s.csv'
%   summaryfile     - the path the summary csv file
%
% annotationfiles, mitofiles, and animalid must all have the same number of
% elements.

%%%% Setup Variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

minArea = 256; % corresponds to blob roughly 16 x 16 pix.

% Predefined colors

% Mito color (blue)
c_mito = [0 0 1];

% Capillary color (purple / magenta)
c_cap = [255  0   243] / 255;

% Colors among k number of classes
c_k = [255  0	0;
       255	255	0;
       255  0    243;
       0    0   0] / 255;

% class names
kname = {'terminal', 'glia', 'capillary', 'background'};
strfields = {'n', 'fraction', 'avgsize'};

k = numel(kname);

% If k_doMito[ii] is true, then do the mito analysis for the ii'th class
k_doMito = [true, true, false, false];

n_files = numel(annotationfiles);

% Instantiate the stat_str struct
stat_str = repmat(areaStatStr, [n_files, k]);
% and the mito_str struct
mito_str = stat_str;

% This line is confusing. Look at the output of help('unique') for guidance
[uanimalid, ~, ids] = unique(animalid);

%%%% Collate Data Structures from Image Files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for ii = 1:n_files
    % Annotation image
    im_a = im2single(imread(annotationfiles{ii}));
    % Annotation image for mitochondria
    im_m = im2single(imread(mitofiles{ii}));

    % Get the mitochondria mask from the mito image
    mito_mask = getMask(im_m, c_mito);
    % Get the capillary mask from the annotation image
    cap_mask = getMask(im_a, c_cap);
    % Now we know how many pixels the capillary takes up
    capPix = sum(cap_mask(:));

    if capPix == 0
        warning('Found zero capillary pixels');
    end

    totPix = size(im_a, 1) * size(im_a, 2) - capPix;
    npix = zeros(k, 1);

    % Store the current animal id index
    id = ids(ii);

    % For each of the k classes
    for ik = 1:k
        % Get the classes color
        c = c_k(ik, :);
        % Get the class-mask from the annotation image
        mask = getMask(im_a, c);

        % Compute the statistic struct for this class
        [stat_str(ii, ik), npix(ik)] = areaStatStr(mask, minArea, id, ...
            annotationfiles{ii}, totPix);

        % If we want the corresponding mitochondria stats, get those here
        % We compute over the pixel-wise and of the class mask and the mito
        % mask.
        if k_doMito(ik)
            mito_str(ii, ik) = areaStatStr(and(mask, mito_mask), minArea,...
                id, mitofiles{ii}, totPix);
        end

    end

    if size(im_a, 1) * size(im_a, 2) - sum(npix) > minArea
        error(['For image file %s, missed some pixels. Analyzed %d, ', ...
            'expected %d'], annotationfiles{ii}, sum(npix), ...
            size(im_a, 1) * size(im_a, 2));
    end

end

strid = [stat_str(:,1).id];

g = fopen(summaryfile, 'w');

if g < 1
    error('Could not open %s for writing', filename);
end

fprintf(g, 'Animal ID, ');
for ik = 1:k
    for ff = 1:numel(strfields)
        fprintf(g, '%s %s, ', kname{ik}, strfields{ff});
    end
    if k_doMito(ik)
        for ff = 1:numel(strfields)
            fprintf(g, '%s mito %s, ', kname{ik}, strfields{ff});
        end
    end
end
fprintf(g, '\n');

% Write out animal files
for ii = 1:numel(ids)
    id = ids(ii);
    sel = find(strid == id);
    animal_stat_str = stat_str(sel,:);
    animal_mito_str = mito_str(sel,:);

    n = numel(sel);

    fname = sprintf(outputTemplate, uanimalid{id});

    f = fopen(fname, 'w');

    if f < 1
        error('Could not open %s for writing', fname);
    else
        % Write out the header
        fprintf(f, 'Animal ID, Annotation File, Mito File, ');
        for ik = 1:k
            for ff = 1:numel(strfields)
                fprintf(f, '%s %s, ', kname{ik}, strfields{ff});
            end
            if k_doMito(ik)
                for ff = 1:numel(strfields)
                    fprintf(f, '%s mito %s, ', kname{ik}, strfields{ff});
                end
            end
        end
        fprintf(f, '\n');

        for jj = 1:n
            fprintf(f, '%s, %s, %s, ', uanimalid{id},...
                animal_stat_str(jj, 1).filename, ...
                animal_mito_str(jj, 1).filename);
            for ik = 1:k
                for ff = 1:numel(strfields)
                    fprintf(f, '%g, ', ...
                        animal_stat_str(jj, ik).(strfields{ff}));
                end
                if k_doMito(ik)
                    for ff = 1:numel(strfields)
                        fprintf(f, '%g, ', ...
                            animal_mito_str(jj, ik).(strfields{ff}));
                    end
                end
            end
            fprintf(f, '\n');
        end

    end

    fclose(f);

    fprintf(g, '%s, ', uanimalid{id});
    % ik is class index, k number of classes
    for ik = 1:k
        for ff = 1:numel(strfields)
            aggregate_stat = ...
                aggregate(animal_stat_str(:,ik), strfields{ff});
            fprintf(g, '%g, ', aggregate_stat);
        end
        if k_doMito(ik)
            for ff = 1:numel(strfields)
                aggregate_stat = ...
                    aggregate(animal_mito_str(:,ik), strfields{ff});
                fprintf(g, '%g, ', aggregate_stat);
            end
        end
    end
    fprintf(g, '\n');
end

fclose(g);

end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = aggregate(str, fname)
% str - an animal stat struct array, one struct per image
% fname - the field name to aggregate. each field has its own rule
switch fname
    case 'n'
        % n aggregated by summation over all images
        a = sum([str.n]);
    case 'fraction'
        % fraction aggregated by summing npix across all images, then
        % dividing by the summation of totpix.
        % this gives the total fraction over all analyzed non-capillary
        % pixels.
        a = sum([str.fraction] .* [str.totpix]) /...
            sum([str.totpix]);
    case 'avgsize'
        % avgsize aggregated by summing totsize, found by image-wise n *
        % avgsize, then dividing the sum by the n across all images.
        a = sum([str.avgsize] .* [str.n]) / ...
            sum([str.n]);
    otherwise
        % As of this writing, we know of only three output struct fields.
        % If we encounter an unexpected one, aggregate to a not-a-number
        % (NaN) value.
        a = nan;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [str, npix] = areaStatStr(mask, minArea, id, fname, totPix)

if nargin < 1 || isempty(mask)
    str = struct('n', 0, 'fraction', 0, 'avgsize', 0, 'totpix', 0, ...
        'id', -1, 'filename', '');
    return
end

rpstr = regionprops(mask, 'Area');
area = [rpstr.Area];
npix = sum(area);
sel = area < minArea;
area(sel) = [];

str.n = numel(area);
str.fraction = sum(area) / totPix;
str.avgsize = mean(area);
str.totpix = totPix;
str.id = id;
str.filename = fname;

end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mask = getMask(im, c)
% Creates a mask over im for a given color

fprintf('Processing color %03d %03d %03d...', c(1) * 255, c(2) * 255, c(3)* 255);

% Start out everywhere true.
mask = true(size(im,1), size(im,2));
for ic = 1:numel(c)
    % Set the mask to false if the image's channel
    % doesn't match the corresponding component of
    % the color. This works for RGB or grayscale.
    mask = and(mask, abs(im(:,:,ic) - c(ic)) < (16 / 256));
end

fprintf('done.\n');

%subplot(1, 2, 1); imshow(imresize(im, 1/24));
%subplot(1, 2, 2); imshow(imresize(mask, 1/24));
%drawnow;

end


text:
require File.expand_path("#{File.dirname(__FILE__)}/../../../helpers/article_helper")

describe Diffbot::Clients::Article do
  include Helpers::ArticleHelper
  it "returns article title" do
    FakeWeb.register_uri(:get, %r|http://api.diffbot.com/v2/article|, :body => xconomy_post_json(:title).to_json, 'Content-Type' => "application/json")
    Diffbot::Clients::Article.new(DEV_TOKEN, XCONOMY_POST_URL).title.should eql(xconomy_post_title)
  end

end