text:
<?php

  use OSC\OM\HTML;
  use OSC\OM\OSCOM;
  use OSC\OM\Registry;

  class ht_gpublisher {
    var $code = 'ht_gpublisher';
    var $group = 'header_tags';
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;

    function __construct() {
      $this->title = OSCOM::getDef('module_header_tags_gpublisher_title');
      $this->description = OSCOM::getDef('module_header_tags_gpublisher_description');

      if ( defined('MODULE_HEADER_TAGS_GPUBLISHER_STATUS') ) {
        $this->sort_order = MODULE_HEADER_TAGS_GPUBLISHER_SORT_ORDER;
        $this->enabled = (MODULE_HEADER_TAGS_GPUBLISHER_STATUS == 'True');
      }
    }

    function execute() {
      global $oscTemplate;

      $oscTemplate->addBlock('<link rel="publisher" href="' . HTML::output(MODULE_HEADER_TAGS_GPUBLISHER_ID) . '" />' . PHP_EOL, $this->group);
    }

    function isEnabled() {
      return $this->enabled;
    }

    function check() {
      return defined('MODULE_HEADER_TAGS_GPUBLISHER_STATUS');
    }

    function install() {
      $OSCOM_Db = Registry::get('Db');

      $OSCOM_Db->save('configuration', [
        'configuration_title' => 'Enable G+ Publisher Module',
        'configuration_key' => 'MODULE_HEADER_TAGS_GPUBLISHER_STATUS',
        'configuration_value' => 'True',
        'configuration_description' => 'Add G+ Publisher Link to your shop?  You MUST have a BUSINESS G+ account.  Once installed and configured, don\'t forget to link your G+ page back to your website.

Helper Links:
http://www.google.com/+/business/
http://www.advancessg.com/googles-relpublisher-tag-is-for-all-business-and-brand-websites-not-just-publishers/',
        'configuration_group_id' => '6',
        'sort_order' => '1',
        'set_function' => 'tep_cfg_select_option(array(\'True\', \'False\'), ',
        'date_added' => 'now()'
      ]);

      $OSCOM_Db->save('configuration', [
        'configuration_title' => 'G+ Publisher Address',
        'configuration_key' => 'MODULE_HEADER_TAGS_GPUBLISHER_ID',
        'configuration_value' => '',
        'configuration_description' => 'Your G+ URL.',
        'configuration_group_id' => '6',
        'sort_order' => '0',
        'date_added' => 'now()'
      ]);

      $OSCOM_Db->save('configuration', [
        'configuration_title' => 'Sort Order',
        'configuration_key' => 'MODULE_HEADER_TAGS_GPUBLISHER_SORT_ORDER',
        'configuration_value' => '0',
        'configuration_description' => 'Sort order of display. Lowest is displayed first.',
        'configuration_group_id' => '6',
        'sort_order' => '0',
        'date_added' => 'now()'
      ]);
    }

    function remove() {
      return Registry::get('Db')->exec('delete from :table_configuration where configuration_key in ("' . implode('", "', $this->keys()) . '")');
    }

    function keys() {
      return array('MODULE_HEADER_TAGS_GPUBLISHER_STATUS', 'MODULE_HEADER_TAGS_GPUBLISHER_ID', 'MODULE_HEADER_TAGS_GPUBLISHER_SORT_ORDER');
    }
  }


text:
<?php

/**
 * User: Alex Gusev <alex@flancer64.com>
 */
include_once('../../../../phpunit_bootstrap.php');

/**
 * User: Alex Gusev <alex@flancer64.com>
 */
class Praxigento_SavedCards_Test_Model_Own_Service_PayPal_Call_UnitTest extends PHPUnit_Framework_TestCase
{

    public function test_constructor()
    {
        $call = Mage::getModel('prxgt_savedcards_model/own_service_payPal_call');
        $this->assertNotNull($call);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Support and FAQ: visit Atmel Support
 */
#ifndef GFX_TEXT_H_INCLUDED
#define GFX_TEXT_H_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

#include "compiler.h"
#ifdef CONFIG_HAVE_HUGEMEM
# include "hugemem.h"
#endif
#if XMEGA
# include "progmem.h"
#endif

/**
 * \ingroup gfx_group
 * \defgroup gfx_font_group Font support
 * This modules provides functionality for outputting a font to a display.
 *
 * @{
 */

/**
 * \brief Valid storage locations for font data
 *
 * \todo Add support for fonts in regular ram
 */
enum font_data_type {
	/*! Font data stored in program/flash memory. */
	FONT_LOC_PROGMEM,
#ifdef CONFIG_HAVE_HUGEMEM
	/*! Font data stored in HUGEMEM. */
	FONT_LOC_HUGEMEM,
#endif
};

/** Text alignment options for text lines within a paragraph. */
enum gfx_text_alignment {
	/**< Align each line to the left side of the paragraph bounding box */
	TEXT_ALIGN_LEFT,
	/**< Align each line to the right side of the paragraph bounding box */
	TEXT_ALIGN_RIGHT,
	/**< Align each line to the center of the paragraph bounding box */
	TEXT_ALIGN_CENTER,
};

/** Text paraphraph positioning options. */
enum gfx_text_position {
	/**< Position text paragraph vertically below given coordinate */
	TEXT_POS_TOP        = (1 << 0),
	/**< Position text paragraph vertically centered on given coordinate */
	TEXT_POS_CENTER_Y   = (1 << 1),
	/**< Position text paragraph vertically above given coordinate */
	TEXT_POS_BOTTOM     = (1 << 2),
	/**< Position text paragraph horizontally right to the given coordinate */
	TEXT_POS_LEFT       = (1 << 3),
	/**< Position text paragraph horizontally centered on given coordinate */
	TEXT_POS_CENTER_X   = (1 << 4),
	/**< Position text paragraph horizontally left to the given coordinate */
	TEXT_POS_RIGHT      = (1 << 5),

	TEXT_POS_TOP_LEFT      = TEXT_POS_TOP      | TEXT_POS_LEFT,
	TEXT_POS_TOP_CENTER    = TEXT_POS_TOP      | TEXT_POS_CENTER_X,
	TEXT_POS_TOP_RIGHT     = TEXT_POS_TOP      | TEXT_POS_RIGHT,
	TEXT_POS_CENTER_LEFT   = TEXT_POS_CENTER_Y | TEXT_POS_LEFT,
	TEXT_POS_CENTER        = TEXT_POS_CENTER_Y | TEXT_POS_CENTER_X,
	TEXT_POS_CENTER_RIGHT  = TEXT_POS_CENTER_Y | TEXT_POS_RIGHT,
	TEXT_POS_BOTTOM_LEFT   = TEXT_POS_BOTTOM   | TEXT_POS_LEFT,
	TEXT_POS_BOTTOM_CENTER = TEXT_POS_BOTTOM   | TEXT_POS_CENTER_X,
	TEXT_POS_BOTTOM_RIGHT  = TEXT_POS_BOTTOM   | TEXT_POS_RIGHT,
};

/** Storage structure for font meta data. */
struct font {
	/*! Type of storage used for binary font data. See \ref font_data_type. **/
	enum font_data_type type;
	union {
		/**
		 * Pointer to where the binary font data is stored. This
		 * variable is accessed either through hugemem or progmem
		 * depending on the value of \a type.
		 */
#ifdef CONFIG_HAVE_HUGEMEM
		hugemem_ptr_t hugemem;
#endif
		uint8_t PROGMEM_PTR_T progmem;
	} data;

	/*! Width of one font character, in pixels. */
	uint8_t width;
	/*! Height of one font character, in pixels. */
	uint8_t height;
	/*! ASCII value of first character in font set. */
	uint8_t first_char;
	/*! ASCII value of last character in the set. */
	uint8_t last_char;
};

/** \name Strings and characters located in RAM */
/** @{ */
void gfx_draw_char(const char c, const gfx_coord_t x, const gfx_coord_t y,
		const struct font *font, const gfx_color_t bg_color,
		const gfx_color_t text_color);

void gfx_draw_string(const char *str, const gfx_coord_t x,
		const gfx_coord_t y, const struct font *font,
		const gfx_color_t bg_color, const gfx_color_t text_color);

void gfx_draw_string_aligned(const char *str, gfx_coord_t x, gfx_coord_t y,
		const struct font *font, const gfx_color_t bg_color,
		const gfx_color_t text_color, enum gfx_text_position text_pos,
		enum gfx_text_alignment text_align);

void gfx_get_string_bounding_box(char const *str, const struct font *font,
		gfx_coord_t *width, gfx_coord_t *height);
/** @} */

/** \name Strings located in flash
 * @{
 */
void gfx_draw_progmem_string(char PROGMEM_PTR_T str, gfx_coord_t x,
		gfx_coord_t y, const struct font *font,
		const gfx_color_t bg_color, const gfx_color_t text_color);

void gfx_draw_progmem_string_aligned(char PROGMEM_PTR_T str,
		gfx_coord_t x, gfx_coord_t y, const struct font *font,
		const gfx_color_t bg_color, const gfx_color_t text_color,
		enum gfx_text_position text_pos, enum gfx_text_alignment text_align);

void gfx_get_progmem_string_bounding_box(char PROGMEM_PTR_T str,
		const struct font *font, gfx_coord_t *width,
		gfx_coord_t *height);
/** @} */

/** @} */

#ifdef __cplusplus
}
#endif

#endif /* GFX_TEXT_H_INCLUDED */


text:
$ vagrant up

selinuxがある状況でcopyコマンド使うために
$ ansible-playbook -i hosts install.yml

$ ansible-playbook -i hosts playbook.yml

$ vagrant halt

$ vagrant destroy


text:
# Quantile Function

> [Bernoulli][bernoulli-distribution] distribution [quantile function][quantile-function].

The [quantile function][quantile-function] for a [Bernoulli][bernoulli-distribution] random variable is

for `0 <= r <= 1`, where `p` is the success probability.

## Usage

```javascript
var quantile = require( '@stdlib/stats/base/dists/bernoulli/quantile' );
```

#### quantile( r, p )

Evaluates the [quantile function][quantile-function] for a [Bernoulli][bernoulli-distribution] distribution with success probability `p` at a value `r`.

```javascript
var y = quantile( 0.8, 0.4 );
// returns 1

y = quantile( 0.5, 0.4 );
// returns 0

y = quantile( 0.9, 0.1 );
// returns 0
```

If provided `r <= 0` or `r >= 0`, the function returns `NaN`.

```javascript
var y = quantile( 1.9, 0.5 );
// returns NaN

y = quantile( -0.1, 0.5 );
// returns NaN
```

If provided `NaN` as any argument, the function returns `NaN`.

```javascript
var y = quantile( NaN, 1.0 );
// returns NaN

y = quantile( 0.0, NaN );
// returns NaN
```

If provided a success probability `p` outside the interval `[0,1]`, the function returns `NaN`.

```javascript
var y = quantile( 0.4, -1.0 );
// returns NaN

y = quantile( 0.4, 1.5 );
// returns NaN
```

#### quantile.factory( p )

Returns a function for evaluating the [quantile function][quantile-function] for a [Bernoulli][bernoulli-distribution] distribution with success probability `p`.

```javascript
var myquantile = quantile.factory( 0.4 );
var y = myquantile( 0.4 );
// returns 0

y = myquantile( 0.8 );
// returns 1

y = myquantile( 1.0 );
// returns 1
```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var quantile = require( '@stdlib/stats/base/dists/bernoulli/quantile' );

var p;
var r;
var y;
var i;

for ( i = 0; i < 10; i++ ) {
    r = randu();
    p = randu();
    y = quantile( r, p );
    console.log( 'r: %d, p: %d, Q(r;p): %d', r.toFixed( 4 ), p.toFixed( 4 ), y.toFixed( 4 ) );
}
```

[bernoulli-distribution]: https://en.wikipedia.org/wiki/Bernoulli_distribution

[quantile-function]: https://en.wikipedia.org/wiki/Quantile_function


text:
package com.amazonaws.services.route53.model;

import javax.annotation.Generated;

/**
 * <p>
 * The specified VPC and hosted zone are not currently associated.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VPCAssociationNotFoundException extends com.amazonaws.services.route53.model.AmazonRoute53Exception {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new VPCAssociationNotFoundException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public VPCAssociationNotFoundException(String message) {
        super(message);
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>grlc</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.17.1/swagger-ui.css" >
    <link rel="icon" href="{{ relative_path + url_for('.static', filename='favicon.ico')}}">

            grlc

              <button class="btn" id="ohyeah" onclick="grlcProvToggle()">Oh, yeah?</button>

                <button class="btn" id="prev-commit" onclick="">< Prev</button>
                 |
                <button class="btn" id="next-commit" onclick="">Next ></button>


text:
FinderSidebarWidth is a Finder SIMBL plugin which automatically resizes the sidebar width.

Motivation
==========

There is [a lot of confusion](https://www.google.com/search?q=finder+sidebar+width) about how to persist the Finder sidebar width.

Worry no more: with this plugin, your Finder sidebars will always be 150px wide.

Requirements
============

- OSX 10.7 or newer
- [SIMBL](http://www.culater.net/software/SIMBL/SIMBL.php) 0.9.9

Installation
============

Download the [latest release](https://github.com/MarkVillacampa/FinderSidebarWidth/releases/latest) and copy FinderSidebarWidth.bundle to `/Library/Application Support/SIMBL/Plugins`

Uninstall
=========

```sh
sudo rm -r "/Library/Application Support/SIMBL/Plugins/FinderSidebarWidth.bundle"
```


text:
require 'rails_helper'

describe Devices::Type do
end


text:
#ifndef sequence_h
#define sequence_h

#include <stddef.h>
#include <stdint.h>

#include "wapiti.h"

/*******************************************************************************
 * Sequences and Dataset objects
 *
 *   Sequences represent the input data feeded by the user in Wapiti either for
 *   training or labelling. The internal form used here is very different from
 *   the data read from files and the convertion process is done in three steps
 *   illustrated here:
 *         +------+     +-------+     +-------+     +-------+
 *         | FILE | --> | raw_t | --> | tok_t | --> | seq_t |
 *         +------+     +-------+     +-------+     +-------+
 *   First the sequence is read as a set of lines from the input file, this
 *   give a raw_t object. Next this set of lines is split in tokens and
 *   eventually the last one is separated as it will become a label, this result
 *   in a tok_t object.
 *   The last step consist in applying all the patterns givens by the user to
 *   extract from these tokens the observations made on the sequence in order to
 *   build the seq_t object which can be used by the trainer and tagger.
 *
 *   A dataset object is just a container for a list of sequences in internal
 *   form used to store either training or development set.
 *
 *   All the convertion process is driven by the reader object and, as it is
 *   responsible for creating the objects with a quite special allocation
 *   scheme, we just have to implement function for freeing these objects here.
 ******************************************************************************/

/* raw_t:
 *   Data-structure representing a raw sequence as a set of lines read from the
 *   input file. This is the result of the first step of the interning process.
 *   We keep this form separate from the tokenized one as we want to be able to
 *   output the sequence as it was read in the labelling mode.
 *
 *   This represent a sequence of lengths <len> and for each position 't' you
 *   find the corresponding line at <lines>[t].
 *
 *   The <lines> array is allocated with data structure, and the different lines
 *   are allocated separatly.
 */
typedef struct raw_s raw_t;
struct raw_s {
	uint32_t  len;      //   T     Sequence length
	char     *lines[];  //  [T]    Raw lines directly from file
};

/* tok_t:
 *   Data-structure representing a tokenized sequence. This is the result of the
 *   second step of the interning process after the raw sequence have been split
 *   in tokens and eventual labels separated from the observations.
 *
 *   For each position 't' in the sequence of length <len>, you find at <lbl>[t]
 *   the eventual label provided in input file, and at <toks>[t] a list of
 *   string tokens of length <cnts>[t].
 *
 *   Memory allocation here is a bit special as the first token at each position
 *   point to a memory block who hold a copy of the raw line. Each other tokens
 *   and the label are pointer in this block. This reduce memory fragmentation.
 */
typedef struct tok_s tok_t;
struct tok_s {
	uint32_t   len;     //   T     Sequence length
	char     **lbl;     //  [T]    List of labels strings
	uint32_t  *cnts;    //  [T]    Length of tokens lists
	char     **toks[];  //  [T][]  Tokens lists
};

/* seq_t:
 *   Data-structure representing a sequence of length <len> in the internal form
 *   used by the trainers and the tagger. For each position 't' in the sequence
 *   (0 <= t < <len>) there is some observations made on the data and an
 *   eventual label if provided in the input file.
 *
 *   There is two kind of features: unigrams and bigrams one, build by combining
 *   one observation and one or two labels. At position 't', the unigrams
 *   features are build using the list of observations from <uobs>[t] which
 *   contains <ucnt>[t] items, and the observation at <lbl>[t]. The bigrams
 *   features are obtained in the same way using <bobs> and <bcnt>, and have to
 *   be combined also with <lbl>[t-1].
 *
 *   If the sequence is read from a file without label, as it is the case in
 *   labelling mode, the <lbl> field will be NULL and so, the sequence cannot be
 *   used for training.
 *
 *   The raw field is private and used internaly for efficient memory
 *   allocation. This allow to allocate <lbl>, <*cnt>, and all the list in
 *   <*obs> with the datastructure itself.
 */
typedef struct pos_s pos_t;
typedef struct seq_s seq_t;
struct seq_s {
	uint32_t  len;
	uint64_t *raw;
	struct pos_s {
		uint32_t  lbl;
		uint32_t  ucnt,  bcnt;
		uint64_t *uobs, *bobs;
	} pos[];
};

/* dat_t:
 *   Data-structure representing a full dataset: a collection of sequences ready
 *   to be used for training or to be labelled. It keep tracks of the maximum
 *   sequence length as the trainer need this for memory allocation. The dataset
 *   contains <nseq> sequence stored in <seq>. These sequences are labeled only
 *   if <lbl> is true.
 */
typedef struct dat_s dat_t;
struct dat_s {
	bool       lbl;   //         True iff sequences are labelled
	uint32_t   mlen;  //         Length of the longest sequence in the set
	uint32_t   nseq;  //   S     Number of sequences in the set
	seq_t    **seq;   //  [S]    List of sequences
};

#endif


text:
package io.reactivesw.merchant.domain.service.update;

import com.google.common.collect.Sets;

import io.reactivesw.common.model.Update;
import io.reactivesw.common.model.UpdateAction;
import io.reactivesw.merchant.application.model.action.SetDefaultCurrencyAction;
import io.reactivesw.merchant.application.model.mapper.CurrencyMapper;
import io.reactivesw.merchant.domain.entity.CurrencyValue;
import io.reactivesw.merchant.domain.entity.InternationalEntity;
import io.reactivesw.merchant.infrastructure.util.CurrencyMap;
import io.reactivesw.merchant.infrastructure.util.InternationalActionUtils;
import io.reactivesw.merchant.infrastructure.validator.CurrencyValidator;

import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * Created by Davis on 17/1/9.
 */
@Service(value = InternationalActionUtils.SET_DEFAULT_CURRENCY)
public class SetDefaultCurrencyService implements Update<InternationalEntity> {
  /**
   * set default currency.
   *
   * @param entity E
   * @param action UpdateAction
   */
  @Override
  public void handle(InternationalEntity entity, UpdateAction action) {

    String currencyCode = ((SetDefaultCurrencyAction) action).getCurrencyCode();

    CurrencyValidator.validate(currencyCode);

    CurrencyValue currencyValue = CurrencyMapper.modelToEntity(
        CurrencyMap.getCurrencyByCode(currencyCode));

    CurrencyValue defaultCurrency = entity.getDefaultCurrency();

    Set<CurrencyValue> currencyValues = entity.getSupportedCurrencies();

    if (currencyValues == null || currencyValues.isEmpty()) {
      currencyValues = Sets.newHashSet(currencyValue);
    } else {
      currencyValues.remove(defaultCurrency);
      currencyValues.add(currencyValue);
    }
    entity.setDefaultCurrency(currencyValue);
    entity.setSupportedCurrencies(currencyValues);
  }
}


text:
namespace casst
{
  inline auto update(std::string const &tab)
  { return detail::update::update<detail::update::step::base>{ tab }; }
}


text:
require 'spec_helper'

describe Gitlab::Metrics::RackMiddleware do
  let(:app) { double(:app) }

  let(:middleware) { described_class.new(app) }

  let(:env) { { 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/foo' } }

  describe '#call' do
    before do
      expect_any_instance_of(Gitlab::Metrics::Transaction).to receive(:finish)
    end

    it 'tracks a transaction' do
      expect(app).to receive(:call).with(env).and_return('yay')

      expect(middleware.call(env)).to eq('yay')
    end

    it 'tags a transaction with the name and action of a controller' do
      klass      = double(:klass, name: 'TestController')
      controller = double(:controller, class: klass, action_name: 'show')

      env['action_controller.instance'] = controller

      allow(app).to receive(:call).with(env)

      expect(middleware).to receive(:tag_controller).
        with(an_instance_of(Gitlab::Metrics::Transaction), env)

      middleware.call(env)
    end

    it 'tags a transaction with the method andpath of the route in the grape endpoint' do
      route    = double(:route, route_method: "GET", route_path: "/:version/projects/:id/archive(.:format)")
      endpoint = double(:endpoint, route: route)

      env['api.endpoint'] = endpoint

      allow(app).to receive(:call).with(env)

      expect(middleware).to receive(:tag_endpoint).
        with(an_instance_of(Gitlab::Metrics::Transaction), env)

      middleware.call(env)
    end
  end

  describe '#transaction_from_env' do
    let(:transaction) { middleware.transaction_from_env(env) }

    it 'returns a Transaction' do
      expect(transaction).to be_an_instance_of(Gitlab::Metrics::Transaction)
    end

    it 'stores the request method and URI in the transaction as values' do
      expect(transaction.values[:request_method]).to eq('GET')
      expect(transaction.values[:request_uri]).to eq('/foo')
    end

    context "when URI includes sensitive parameters" do
      let(:env) do
        {
          'REQUEST_METHOD' => 'GET',
          'REQUEST_URI'    => '/foo?private_token=my-token',
          'PATH_INFO' => '/foo',
          'QUERY_STRING' => 'private_token=my_token',
          'action_dispatch.parameter_filter' => [:private_token]
        }
      end

      it 'stores the request URI with the sensitive parameters filtered' do
        expect(transaction.values[:request_uri]).to eq('/foo?private_token=[FILTERED]')
      end
    end
  end

  describe '#tag_controller' do
    let(:transaction) { middleware.transaction_from_env(env) }

    it 'tags a transaction with the name and action of a controller' do
      klass      = double(:klass, name: 'TestController')
      controller = double(:controller, class: klass, action_name: 'show')

      env['action_controller.instance'] = controller

      middleware.tag_controller(transaction, env)

      expect(transaction.action).to eq('TestController#show')
    end
  end

  describe '#tag_endpoint' do
    let(:transaction) { middleware.transaction_from_env(env) }

    it 'tags a transaction with the method and path of the route in the grape endpount' do
      route    = double(:route, route_method: "GET", route_path: "/:version/projects/:id/archive(.:format)")
      endpoint = double(:endpoint, route: route)

      env['api.endpoint'] = endpoint

      middleware.tag_endpoint(transaction, env)

      expect(transaction.action).to eq('Grape#GET /projects/:id/archive')
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace ODataValidator.Rule
{
    #region Namespaces
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using Newtonsoft.Json.Linq;
    using ODataValidator.RuleEngine;
    using ODataValidator.RuleEngine.Common;
    #endregion

    /// <summary>
    /// Class of extension rule for Entry.Core.4082
    /// </summary>
    [Export(typeof(ExtensionRule))]
    public class EntryCore4082 : ExtensionRule
    {
        /// <summary>
        /// Gets Category property
        /// </summary>
        public override string Category
        {
            get
            {
                return "core";
            }
        }

        /// <summary>
        /// Gets rule name
        /// </summary>
        public override string Name
        {
            get
            {
                return "Entry.Core.4082";
            }
        }

        /// <summary>
        /// Gets rule description
        /// </summary>
        public override string Description
        {
            get
            {
                return "Values of type Edm.String are represented as JSON strings.";
            }
        }

        /// <summary>
        /// Gets rule specification in OData document
        /// </summary>
        public override string V4SpecificationSection
        {
            get
            {
                return "7.1";
            }
        }

        /// <summary>
        /// Gets the version.
        /// </summary>
        public override ODataVersion? Version
        {
            get
            {
                return ODataVersion.V3_V4;
            }
        }

        /// <summary>
        /// Gets location of help information of the rule
        /// </summary>
        public override string HelpLink
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Gets the error message for validation failure
        /// </summary>
        public override string ErrorMessage
        {
            get
            {
                return this.Description;
            }
        }

        /// <summary>
        /// Gets the requirement level.
        /// </summary>
        public override RequirementLevel RequirementLevel
        {
            get
            {
                return RequirementLevel.Must;
            }
        }

        /// <summary>
        /// Gets the payload type to which the rule applies.
        /// </summary>
        public override PayloadType? PayloadType
        {
            get
            {
                return RuleEngine.PayloadType.Entry;
            }
        }

        /// <summary>
        /// Gets the payload format to which the rule applies.
        /// </summary>
        public override PayloadFormat? PayloadFormat
        {
            get
            {
                return RuleEngine.PayloadFormat.JsonLight;
            }
        }

        /// <summary>
        /// Gets the RequireMetadata property to which the rule applies.
        /// </summary>
        public override bool? RequireMetadata
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the flag whether this rule applies to offline context
        /// </summary>
        public override bool? IsOfflineContext
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            JObject entry;
            context.ResponsePayload.TryToJObject(out entry);

            XElement metadata = XElement.Parse(context.MetadataDocument);

            // Use the XPath query language to access the metadata document and get the node which will be used.
            string xpath = string.Format(@"//*[local-name()='EntityType' and @Name='{0}']/*[local-name()='Property']", context.EntityTypeShortName);
            IEnumerable<XElement> props = metadata.XPathSelectElements(xpath, ODataNamespaceManager.Instance);

            if (entry != null && entry.Type == JTokenType.Object)
            {
                var o = (JObject)entry;

                // Get all the properties in current entry.
                var jProps = o.Children();

                foreach (JProperty jProp in jProps)
                {
                    string propType = string.Empty;

                    foreach (var prop in props)
                    {
                        if (jProp.Name == prop.Attribute("Name").Value)
                        {
                            propType = prop.Attribute("Type").Value;
                            break;
                        }
                    }

                    if (propType == "Edm.String")
                    {
                        if (jProp.Value.Type == JTokenType.String || jProp.Value.Type == JTokenType.Null)
                        {
                            passed = true;
                        }
                        else
                        {
                            passed = false;
                            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                            break;
                        }
                    }
                }
            }

            return passed;
        }
    }
}


text:
import os
import tempfile
import vtk

className = obj.__class__.__name__

if className == 'slice3dVWR':

    # find all polydata objects
    so = obj._tdObjects._getSelectedObjects()
    polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
                 pd.GetClassName() == 'vtkPolyData']

    # now find their Mappers
    objectsDict = obj._tdObjects._tdObjectsDict
    actors = [objectsDict[pd]['vtkActor'] for pd in polyDatas]
    mappers = [a.GetMapper() for a in actors]

    for mapper in mappers:
        lut = mapper.GetLookupTable()
        lut.SetScaleToLog10()
        #lut.SetScaleToLinear()

        srange = mapper.GetInput().GetScalarRange()
        lut.SetTableRange(srange)
        lut.SetSaturationRange(1.0,1.0)
        lut.SetValueRange(1.0, 1.0)
        lut.SetHueRange(0.1, 1.0)

        lut.Build()

else:
    print "This snippet must be run from a slice3dVWR introspection window."


text:
package com.gtabox.zigbee;

import java.io.IOException;
import java.util.Arrays;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.gtafe.taiyuan_sensor.R;
import com.gtafe.taiyuan_sensor.SerialPortActivity;
import com.gtafe.until.ModeBusStrParse;
import com.gtafe.until.SuportMethod;

public class ZigbeeDetailDataWindow extends SerialPortActivity{
	private String SensorType;
	private Handler handler;
	private ImageView sensor_icon_iv;
	private TextView sensor_name_tv, zigbee_addr_tv, zigbee_data_tv;
	/*
	public ZigbeeDetailDataWindow(String type) {
	}*/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.zig_topo_detail_data_xml);
		sensor_icon_iv = (ImageView)findViewById(R.id.sensor_icon_iv);
		sensor_name_tv = (TextView)findViewById(R.id.sensor_name_tv);
		zigbee_addr_tv = (TextView)findViewById(R.id.zigbee_addr_tv);
		zigbee_data_tv = (TextView)findViewById(R.id.zigbee_data_tv);
		Intent intent = getIntent();
		SensorType = intent.getStringExtra("SensorType");

		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Bundle data = msg.getData();
				sensor_icon_iv.setImageResource(data.getInt("SensorImg"));
				sensor_name_tv.setText(data.getString("SensorName"));
				zigbee_addr_tv.setText(data.getString("SensorAddr"));
				zigbee_data_tv.setText(data.getString("SensorData"));
			}
		};
	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		byte[] buf = Arrays.copyOf(buffer, size);
		SuportMethod sup = new SuportMethod();
		String bufferStr = sup.byteToHexString(buf);
		Log.d("GTA", "bufferStr:" + bufferStr);
		Log.d("GTA", "sensorType:" + SensorType);
		if(size < 10 || buffer[0] != 0x7e){
			return;
		}
		ModeBusStrParse modebus = new ModeBusStrParse(bufferStr);
		String sensorType = modebus.getSensorCategory()+modebus.getSensorType();//获取传感器类型
		if(SensorType.equals(sensorType)){
			int sensorImg = ModeBusStrParse.getSensorImg(sensorType);//获得传感器图片
			String sensorName = ModeBusStrParse.getSersorName(sensorType);//获得传感器名称
			String sensorAddr = modebus.getSensorAddr();//获得地址
			String sensorHexData = modebus.getSensorData(modebus.getSensorDataLength());//获得十六进制数据
			String sensorData = modebus.getSensorIntData(sensorType, sensorHexData);//获得传感器实际数据
			Message msg = handler.obtainMessage();
			Bundle data = new Bundle();
			data.putInt("SensorImg", sensorImg);
			data.putString("SensorName", sensorName);
			data.putString("SensorAddr", sensorAddr);
			data.putString("SensorData", sensorData);
			msg.setData(data);
			handler.sendMessage(msg);
		}
	}
}


text:
package org.apache.axis.wsdl.symbolTable;

import org.w3c.dom.Node;

import javax.xml.namespace.QName;

/**
 * This class represents a TypeEntry that is a type (complexType, simpleType, etc.
 *
 * @author Rich Scheuerle  (scheu@us.ibm.com)
 */
public abstract class Element extends TypeEntry {

    /**
     * Create an Element object for an xml construct that references a type that has
     * not been defined yet.  Defer processing until refType is known.
     *
     * @param pqName
     * @param refType
     * @param pNode
     * @param dims
     */
    protected Element(QName pqName, TypeEntry refType, Node pNode,
                      String dims) {
        super(pqName, refType, pNode, dims);
    }

    /**
     * Create a Element object for an xml construct that is not a base java type
     *
     * @param pqName
     * @param pNode
     */
    protected Element(QName pqName, Node pNode) {
        super(pqName, pNode);
    }
}


text:
//package ajuda.ai.backend.v0;
//
//import java.util.Map.Entry;
//
//import javax.inject.Inject;
//import javax.persistence.Query;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.transaction.Transactional;
//
//import org.slf4j.Logger;
//
//import ajuda.ai.backend.v0.paymentServices.PaymentProcessor;
//import ajuda.ai.backend.v0.paymentServices.PaymentService;
//import ajuda.ai.backend.v0.util.PersistenceService;
//import ajuda.ai.model.billing.PaymentEvent;
//import ajuda.ai.model.institution.Institution;
//import br.com.caelum.vraptor.Controller;
//import br.com.caelum.vraptor.Path;
//import br.com.caelum.vraptor.Result;
//import br.com.caelum.vraptor.view.Results;
//
//@Controller
//public class TransactionNotificationsController {
//	private final Logger log;
//	private final Result result;
//	private final HttpServletRequest request;
//	private final HttpServletResponse response;
//	private final PersistenceService ps;
//	private final PaymentService paymentService;
//
//	/** @deprecated CDI */ @Deprecated
//	TransactionNotificationsController() { this(null, null, null, null, null, null); }
//
//	@Inject
//	public TransactionNotificationsController(final Logger log, final Result result, final HttpServletRequest request, final HttpServletResponse response, final PersistenceService ps, final PaymentService paymentService) {
//		this.log = log;
//		this.result = result;
//		this.request = request;
//		this.response = response;
//		this.ps = ps;
//		this.paymentService = paymentService;
//	}
//
//	@Transactional
//	@Path("/{slug:[a-z][a-z0-9\\-]*[a-z0-9]}/api/transaction-notification")
//	public void notification(final String slug) {
//		log.info("Recebida uma notificação de transação! Slug = /{}, method = {}, request = {}", slug, request.getMethod(), request);
//		for (final Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
//			log.info(" - {} = {}", entry.getKey(), entry.getValue() == null ? null : entry.getValue()[0]);
//		}
//
//		if (log.isDebugEnabled()) { log.debug("Processando notificação de transação"); }
//
////		response.addHeader("Access-Control-Allow-Origin", "*");
//
//		final Institution institution = (Institution) ps.createQuery("FROM Institution WHERE slug = :slug").setParameter("slug", slug).getSingleResult();
//
//		if (institution != null) {
//			if (log.isDebugEnabled()) { log.debug("Transação para Instituição: {} (/{}, #{})", institution.getName(), institution.getSlug(), institution.getId()); }
//
//			final PaymentProcessor paymentProcessor = paymentService.get(institution.getPaymentService());
//			if (log.isDebugEnabled()) { log.debug("PaymentProcessor: {}", paymentProcessor); }
//
//			if (paymentProcessor != null) {
//				try {
//					final PaymentEvent newEvent = paymentProcessor.processEvent(institution, request, ps, result, log);
//
//					log.info("Payment Event: {}", newEvent);
//
//					if (newEvent != null) {
//						ps.persist(newEvent);
//
//						final Query updatePayment = ps.createQuery("UPDATE Payment SET paid = :paid, cancelled = :cancelled, readyForAccounting = :readyForAccounting WHERE id = :id").setParameter("id", newEvent.getPayment().getId());
//						updatePayment.setParameter("paid", institution.getPaymentService().isPaid(newEvent.getStatus()));
//						updatePayment.setParameter("cancelled", institution.getPaymentService().isCancelled(newEvent.getStatus()));
//						updatePayment.setParameter("readyForAccounting", institution.getPaymentService().isReadyForAccounting(newEvent.getStatus()));
//						updatePayment.executeUpdate();
//					}
//					else {
//						result.use(Results.http()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Não foi possível processar notificação de pagamento");
//					}
//				} catch (final Exception e) {
//					log.error("Erro processando notificação de pagamento", e);
//					result.use(Results.http()).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Erro processando notificação de pagamento: " + e.getClass().getName());
//				}
//			}
//			else {
//				result.notFound();
//			}
//		}
//		else {
//			result.notFound();
//		}
//	}
//}


text:
using Android.App;
using Android.Widget;
using Android.OS;
using System.Linq;
using HansWehr;
using Android.Content;
using Android.Views;
using IoC = TinyIoC.TinyIoCContainer;

namespace HansWehr.Droid
{
	[Activity(Label = "HansWehr", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity
	{
		private SearchView WordSearchView { get; set; }
		private ListView ResultListView { get; set; }
		private WordResultAdapter Adapter { get; set; }

		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			WordSearchView = FindViewById<SearchView>(Resource.Id.WordSearchView);
			ResultListView = FindViewById<ListView>(Resource.Id.ResultListView);

			WordSearchView.QueryTextSubmit += (sender, e) =>
			{
				using (var dictionary = IoC.Current.Resolve<Dictionary>())
				{
					var words = dictionary.Search(e.Query).ToList();
					//words = new WeightedRanker(new OkapiBm25Ranker(),new PositionRanker(), 0.1).Rank(words);
					//words = new PositionRanker().Rank(words);
					//var okapiBm25Ranker = new OkapiBm25Ranker(words);

					ResultListView.Adapter = Adapter = new WordResultAdapter(this, words);
				}
			};
			ResultListView.ItemClick += (sender, e) => DisplayWordView(Adapter.Results[e.Position]);
		}

		private void DisplayWordView(WordResult word)
		{
			var intent = new Intent(this, typeof(WordViewActivity));
			intent.PutExtra(WordViewActivity.WORD_ID, word.Id);
			intent.PutExtra(WordViewActivity.ROOT_WORD_ID, word.RootWordId);
			StartActivity(intent);
		}

	}
}


text:
import pytest
from automower.weather_forecast import WeatherException, WeatherForecast
class TestWeatherForecast(object):

    def test_download_xml_file_from_yr(self):
        forecast = WeatherForecast("test", "https://www.yr.no/place/Norway/Oslo/Oslo/Oslo/varsel_time_for_time.xml")
        forecast.download_xml_file()

    def test_download_xml_file_with_file_that_cant_be_downloaded__should_raise_exception(self):
        forecast = WeatherForecast("test", "invalidurladress")
        with pytest.raises(WeatherException):
            forecast.download_xml_file()


text:
``AffinityPropagation``
============================================================================

.. autoclass:: ibex.sklearn.cluster.AffinityPropagation
    :members:
    :special-members:
    :show-inheritance:


text:
AMLMOD= region
COLL= ../..

TOP= $(COLL)/../../..
include $(COLL)/Makefile.install


text:
/* Created: 29/09/07 15.23 by claudio */
#search-results {
  position: absolute;
  margin-left: 0;
  margin-top: -25px;
  width: 266px;
  display: none; }

* html #search-results {
  margin-left: -86px; }

#searchbubble-top,
#searchbubble-top-r,
#searchbubble-top-l,
.toolspane-top {
  height: 24px;
  width: 266px;
  background: transparent url("/assets/images/searchbubble-top-r.png") no-repeat top center; }

#searchbubble-top-l {
  background-image: url("/assets/images/searchbubble-top-l.png") !important; }

* html #searchbubble-top,
* html .toolspane-top {
  background-image: url("/assets/images/searchbubble-top_ie.gif"); }

#searchbubble-body,
.toolspane-body {
  width: 236px;
  padding: 10px 15px;
  background: transparent url("/assets/images/searchbubble-body.png") repeat-y top center;
  color: #fff; }

.toolspane-body {
  padding: 0 15px; }

* html #searchbubble-body,
* html .toolspane-body {
  background-image: url("/assets/images/searchbubble-body_ie.gif"); }

#searchbubble-bottom,
.toolspane-bottom {
  height: 21px;
  width: 266px;
  background: transparent url("/assets/images/searchbubble-bottom.png") no-repeat top center; }

* html #searchbubble-bottom,
* html .toolspane-bottom {
  background-image: url("/assets/images/searchbubble-bottom_ie.gif"); }

#search-results a:link,
#search-results a:visited,
.toolspane a:link,
.toolspane a:visited {
  color: #fff;
  text-shadow: none !important; }

#search-results a:hover,
#search-results a:active,
.toolspane a:hover,
.toolspane a:active {
  color: #6af !important;
  text-shadow: none !important; }

#search-results .lighter {
  color: #aaa !important; }

#search-results .search-result {
  padding-bottom: 5px;
  cursor: pointer; }

* html #search-results .search-result {
  cursor: hand; }

#search-results .search-result:hover {
  background-color: transparent; }

#search-results .dismiss-search,
.toolspane .dismiss-search {
  float: left;
  display: block;
  width: 12px;
  height: 12px;
  margin: 18px 0 0 13px;
  background: transparent url("/assets/images/searchbubble-close.png") no-repeat center center; }

* html #search-results .dismiss-search,
* html .toolspane .dismiss-search {
  margin-left: 8px;
  background-image: url("/assets/images/searchbubble-close_ie.gif"); }

.toolspane-body p {
  margin: 0;
  line-height: 1.5;
  padding: 0.25em 0; }

.db-debug {
  font-family: "Lucida Console", "Monaco", fixed;
  border: 4px dashed #000;
  background-color: lightyellow;
  padding: 1em;
  margin: 0.5em;
  white-space: auto !important; }

#consacration {
  text-align: center;
  text-transform: uppercase;
  font-size: 9px;
  margin-top: 3em;
  color: #eee; }

.localization-debug {
  color: magenta !important; }

/* Code highligthing */
.code-method {
  color: #f00; }

.code-class {
  color: #f60; }

.code-delimiter,
.code-operator {
  color: #009; }

.code-literal {
  color: #0c0; }

.code-array-key {
  color: #909; }

input.error,
select.error,
textarea.error {
  border: 2px solid red !important; }

.loading {
  padding: 2em 3em;
  text-align: center;
  color: #999; }

.loading > span {
  background: transparent url("/assets/images/throbber_white.gif") no-repeat center left;
  padding-left: 16px; }

.highlighted {
  background-color: #FDFF5B;
  padding: 0 2px;
  color: #444; }

.missing-file {
  padding-left: 22px;
  background: transparent url("/assets/images/warning18.gif") no-repeat center left; }

.approved {
  padding-left: 15px;
  background: transparent url("/assets/images/tick_icon.gif") no-repeat center left; }

#software-list.iconic div.software-icon {
  margin: 8px; }

#software-list.iconic h3,
#software-list.iconic ul.version,
#software-list.iconic p.software-abstract {
  display: none; }

.is-spam {
  background: #aaa none !important; }

label.left-aligned {
  display: block; }

label.required:after {
  content: "*"; }

.form-left textarea {
  width: 90%; }

.diario-gravatar {
  float: left; }

.diario-comment-text {
  margin-left: 50px;
  min-height: 48px; }

.contact-form {
  width: 600px;
  margin: auto; }

@media screen and (min-width: 768px) {
  label.left-aligned {
    float: left;
    display: block;
    width: 80px;
    text-align: right;
    margin-right: 10px; }
  .labeled {
    margin-left: 90px; }
  .padded-to-label {
    padding-left: 90px; }
  .form-left textarea {
    width: auto; } }

.slide-thumb {
  width: 210px; }


text:
namespace MassTransit.Logging.Tracing
{
    using System;
    using System.Diagnostics;
    using System.Globalization;

    public class TraceLog :
        ILog
    {
        readonly LogLevel _level;
        readonly TraceSource _source;

        public TraceLog(TraceSource source)
        {
            _source = source;
            _level = LogLevel.FromSourceLevels(source.Switch.Level);
        }

        public bool IsDebugEnabled
        {
            get { return _level >= LogLevel.Debug; }
        }

        public bool IsInfoEnabled
        {
            get { return _level >= LogLevel.Info; }
        }

        public bool IsWarnEnabled
        {
            get { return _level >= LogLevel.Warn; }
        }

        public bool IsErrorEnabled
        {
            get { return _level >= LogLevel.Error; }
        }

        public bool IsFatalEnabled
        {
            get { return _level >= LogLevel.Fatal; }
        }

        public void LogFormat(LogLevel level, string format, params object[] args)
        {
            if (_level < level)
                return;

            LogInternal(level, string.Format(format, args), null);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="message">The message to log</param>
        public void Debug(object message)
        {
            if (!IsDebugEnabled)
                return;
            Log(LogLevel.Debug, message, null);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="message">The message to log</param>
        public void Debug(object message, Exception exception)
        {
            if (!IsDebugEnabled)
                return;
            Log(LogLevel.Debug, message, exception);
        }

        public void Debug(LogOutputProvider messageProvider)
        {
            if (!IsDebugEnabled)
                return;

            object obj = messageProvider();

            LogInternal(LogLevel.Debug, obj, null);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void DebugFormat(string format, params object[] args)
        {
            if (!IsDebugEnabled)
                return;
            LogInternal(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), null);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsDebugEnabled)
                return;
            LogInternal(LogLevel.Debug, string.Format(formatProvider, format, args), null);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="message">The message to log</param>
        public void Info(object message)
        {
            if (!IsInfoEnabled)
                return;
            Log(LogLevel.Info, message, null);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="message">The message to log</param>
        public void Info(object message, Exception exception)
        {
            if (!IsInfoEnabled)
                return;
            Log(LogLevel.Info, message, exception);
        }

        public void Info(LogOutputProvider messageProvider)
        {
            if (!IsInfoEnabled)
                return;

            object obj = messageProvider();

            LogInternal(LogLevel.Info, obj, null);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void InfoFormat(string format, params object[] args)
        {
            if (!IsInfoEnabled)
                return;
            LogInternal(LogLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), null);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsInfoEnabled)
                return;
            LogInternal(LogLevel.Info, string.Format(formatProvider, format, args), null);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="message">The message to log</param>
        public void Warn(object message)
        {
            if (!IsWarnEnabled)
                return;
            Log(LogLevel.Warn, message, null);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="message">The message to log</param>
        public void Warn(object message, Exception exception)
        {
            if (!IsWarnEnabled)
                return;
            Log(LogLevel.Warn, message, exception);
        }

        public void Warn(LogOutputProvider messageProvider)
        {
            if (!IsWarnEnabled)
                return;

            object obj = messageProvider();

            LogInternal(LogLevel.Warn, obj, null);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void WarnFormat(string format, params object[] args)
        {
            if (!IsWarnEnabled)
                return;
            LogInternal(LogLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), null);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsWarnEnabled)
                return;
            LogInternal(LogLevel.Warn, string.Format(formatProvider, format, args), null);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="message">The message to log</param>
        public void Error(object message)
        {
            if (!IsErrorEnabled)
                return;
            Log(LogLevel.Error, message, null);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="message">The message to log</param>
        public void Error(object message, Exception exception)
        {
            if (!IsErrorEnabled)
                return;
            Log(LogLevel.Error, message, exception);
        }

        public void Error(LogOutputProvider messageProvider)
        {
            if (!IsErrorEnabled)
                return;

            object obj = messageProvider();

            LogInternal(LogLevel.Error, obj, null);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void ErrorFormat(string format, params object[] args)
        {
            if (!IsErrorEnabled)
                return;
            LogInternal(LogLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), null);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsErrorEnabled)
                return;
            LogInternal(LogLevel.Error, string.Format(formatProvider, format, args), null);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="message">The message to log</param>
        public void Fatal(object message)
        {
            if (!IsFatalEnabled)
                return;
            Log(LogLevel.Fatal, message, null);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="message">The message to log</param>
        public void Fatal(object message, Exception exception)
        {
            if (!IsFatalEnabled)
                return;
            Log(LogLevel.Fatal, message, exception);
        }

        public void Fatal(LogOutputProvider messageProvider)
        {
            if (!IsFatalEnabled)
                return;

            object obj = messageProvider();

            LogInternal(LogLevel.Fatal, obj, null);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void FatalFormat(string format, params object[] args)
        {
            if (!IsFatalEnabled)
                return;
            LogInternal(LogLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), null);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsFatalEnabled)
                return;
            LogInternal(LogLevel.Fatal, string.Format(formatProvider, format, args), null);
        }

        public void Log(LogLevel level, object obj)
        {
            if (_level < level)
                return;

            LogInternal(level, obj, null);
        }

        public void Log(LogLevel level, object obj, Exception exception)
        {
            if (_level < level)
                return;

            LogInternal(level, obj, exception);
        }

        public void Log(LogLevel level, LogOutputProvider messageProvider)
        {
            if (_level < level)
                return;

            object obj = messageProvider();

            LogInternal(level, obj, null);
        }

        public void LogFormat(LogLevel level, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (_level < level)
                return;

            LogInternal(level, string.Format(formatProvider, format, args), null);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void DebugFormat(Exception exception, string format, params object[] args)
        {
            if (!IsDebugEnabled)
                return;
            LogInternal(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), exception);
        }

        /// <summary>
        /// Logs a debug message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsDebugEnabled)
                return;
            LogInternal(LogLevel.Debug, string.Format(formatProvider, format, args), exception);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void InfoFormat(Exception exception, string format, params object[] args)
        {
            if (!IsInfoEnabled)
                return;
            LogInternal(LogLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), exception);
        }

        /// <summary>
        /// Logs an info message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsInfoEnabled)
                return;
            LogInternal(LogLevel.Info, string.Format(formatProvider, format, args), exception);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void WarnFormat(Exception exception, string format, params object[] args)
        {
            if (!IsWarnEnabled)
                return;
            LogInternal(LogLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), exception);
        }

        /// <summary>
        /// Logs a warn message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsWarnEnabled)
                return;
            LogInternal(LogLevel.Warn, string.Format(formatProvider, format, args), exception);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void ErrorFormat(Exception exception, string format, params object[] args)
        {
            if (!IsErrorEnabled)
                return;
            LogInternal(LogLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), exception);
        }

        /// <summary>
        /// Logs an error message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsErrorEnabled)
                return;
            LogInternal(LogLevel.Error, string.Format(formatProvider, format, args), exception);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void FatalFormat(Exception exception, string format, params object[] args)
        {
            if (!IsFatalEnabled)
                return;
            LogInternal(LogLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), exception);
        }

        /// <summary>
        /// Logs a fatal message.
        ///
        /// </summary>
        /// <param name="exception">The exception to log</param>
        /// <param name="formatProvider">The format provider to use</param>
        /// <param name="format">Format string for the message to log</param>
        /// <param name="args">Format arguments for the message to log</param>
        public void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            if (!IsFatalEnabled)
                return;
            LogInternal(LogLevel.Fatal, string.Format(formatProvider, format, args), exception);
        }

        void LogInternal(LogLevel level, object obj, Exception exception)
        {
            string message = obj == null
                                 ? ""
                                 : obj.ToString();

            if (exception == null)
                _source.TraceEvent(level.TraceEventType, 0, message);
            else
                _source.TraceData(level.TraceEventType, 0, (object)message, (object)exception);
        }
    }
}


text:
use rulinalg::matrix::Matrix;
use rand;
use rand::{Rng, SeedableRng};

pub fn reproducible_random_matrix(rows: usize, cols: usize) -> Matrix<f64> {
    const STANDARD_SEED: [usize; 4] = [12, 2049, 4000, 33];
    let mut rng = rand::StdRng::from_seed(&STANDARD_SEED);
    let elements: Vec<_> = rng.gen_iter::<f64>().take(rows * cols).collect();
    Matrix::new(rows, cols, elements)
}


text:
<!DOCTYPE html>

      De Desem Doos - Je bestelling werd helaas niet voltooid

      Beste ${naam},

      Spijtig genoeg betaalde je niet op tijd om je doos binnenkort in ontvangst te kunnen nemen.

      Je factuurnummer ${id} op datum ${datum} werd daarom ongedaan gemaakt, conform met de algemene voorwaarden.

      Indien je toch beslist om een Desem Doos opnieuw te bestellen, gelieve dit dan te doen via het formulier op de website.

      Hopelijk tot binnenkort!

    Voor meer informatie, raadpleeg de vragenlijst of de algemene voorwaarden.

    De Desem Doos - Een tweemaandelijkse thuiscursus voor de ambitieuze broodbakker.


text:
#ifndef QQNXNAVIGATOREVENTHANDLER_H
#define QQNXNAVIGATOREVENTHANDLER_H

#include <QObject>

QT_BEGIN_NAMESPACE

class QQnxNavigatorEventHandler : public QObject
{
    Q_OBJECT
public:
    explicit QQnxNavigatorEventHandler(QObject *parent = 0);

    bool handleOrientationCheck(int angle);
    void handleOrientationChange(int angle);
    void handleSwipeDown();
    void handleExit();
    void handleWindowGroupActivated(const QByteArray &id);
    void handleWindowGroupDeactivated(const QByteArray &id);
    void handleWindowGroupStateChanged(const QByteArray &id, Qt::WindowState state);

Q_SIGNALS:
    void rotationChanged(int angle);
    void windowGroupActivated(const QByteArray &id);
    void windowGroupDeactivated(const QByteArray &id);
    void windowGroupStateChanged(const QByteArray &id, Qt::WindowState state);
};

QT_END_NAMESPACE

#endif // QQNXNAVIGATOREVENTHANDLER_H


text:
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Prop_NoChannel extends Property
{
	@Override public String ID() { return "Prop_NoChannel"; }
	@Override public String name(){ return "Channel Neutralizing";}
	@Override protected int canAffectCode(){return Ability.CAN_ROOMS|Ability.CAN_AREAS;}
	protected List<String> channels=null;
	protected boolean receive=true;
	protected boolean sendOK=false;

	@Override
	public String accountForYourself()
	{ return "No Channeling Field"; }

	@Override
	public void setMiscText(String newText)
	{
		super.setMiscText(newText);
		channels=CMParms.parseSemicolons(newText.toUpperCase(),true);
		int x=channels.indexOf("SENDOK");
		sendOK=(x>=0);
		if(sendOK)
			channels.remove(x);
		x=channels.indexOf("QUIET");
		receive=(x<0);
		if(!receive)
			channels.remove(x);
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!super.okMessage(myHost,msg))
			return false;

		if(msg.othersMajor(CMMsg.MASK_CHANNEL))
		{
			final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL;
			if((msg.source()==affected)||(!(affected instanceof MOB))
			&&((channels==null)||(channels.size()==0)||(channels.contains(CMLib.channels().getChannel(channelInt).name))))
			{
				if(!sendOK)
				{
					if(msg.source()==affected)
						msg.source().tell(_("Your message drifts into oblivion."));
					else
					if((!(affected instanceof MOB))
					&&(CMLib.map().roomLocation(affected)==msg.source().location()))
						msg.source().tell(_("This is a no-channel area."));
					return false;
				}
				if(!receive)
				{
					if((msg.source()!=affected)
					||((!(affected instanceof MOB))&&(CMLib.map().roomLocation(affected)!=msg.source().location())))
						return false;
				}
			}
		}
		return true;
	}
}


text:
require "spec_helper"

describe Billymad::Invoice do
  include_examples "can be initialized"

  include_examples "has .all method"
  include_examples "has .find method"
  include_examples "has .create method"
  include_examples "has .update methods"
  include_examples "has .destroy methods"

  it "has correct .resource_name" do
    expect(described_class.send(:resource_name)).to eq('invoice')
  end

  it "has correct .plural_resource_name" do
    expect(described_class.send(:plural_resource_name)).to eq('invoices')
  end
end


text:
module Query
  # Images with observations of a given name.
  class ImageWithObservationsOfName < Query::ImageBase
    include Query::Initializers::ContentFilters
    include Query::Initializers::OfName

    def parameter_declarations
      super.merge(
        old_by?: :string
      ).merge(of_name_parameter_declarations).
        merge(content_filter_parameter_declarations(Observation))
    end

    def initialize_flavor
      give_parameter_defaults
      names = target_names
      choose_a_title(names, :with_observation)
      add_join(:images_observations, :observations)
      add_name_conditions(names)
      initialize_content_filters(Observation)
      super
    end

    def add_join_to_observations(table)
      add_join(:observations, table)
    end

    def default_order
      "name"
    end

    def coerce_into_observation_query
      Query.lookup(:Observation, :of_name, params_with_old_by_restored)
    end
  end
end


text:
<?php
session_start();

	//open .csv file for writing and create headings for each horse's data
	$output = fopen('horses.csv', 'w');
	$progress = fopen('progress.txt', 'w');
	$heading_array = Array('Horse', 'Relative', 'Inbreeding Stats', 'Crosses', 'Lines', 'Blood%', 'Influence', 'AGR');

    //include the amazing simple dom parser that allows us to search through the html of the returned data
	include('simple_html_dom.php');

	//turn off notices related to dom conversion errors
	libxml_use_internal_errors(true);

	//take in values from index.htm for each filter and horse name list
	$horsenames = $_REQUEST['horsenames'];
	$filter = $_REQUEST['filter'];
	$crosses = $_REQUEST['crosses'];
	$gens = $_REQUEST['gens'];
	$influence = $_REQUEST['influence'];

	$inf_num = 0;
	//influence is weird. the filter menu on allbreedpedigree displays in NumxNum format but requires a decimal in the url
	switch($influence)
	{
		case "All":
			break;
		case "> 2x3":
			$inf_num = 9.375;
			break;
		case "> 3x3":
			$inf_num = 6.25;
			break;
		case "> 3x4":
			$inf_num = 4.6875;
			break;
		case "> 4x4":
			$inf_num = 3.125;
			break;
		case "> 4x5":
			$inf_num = 2.34275;
			break;
		case "> 5x5":
			$inf_num = 1.5625;
			break;
		case "> 5x6":
			$inf_num = 1.171875;
			break;
		case "All2":
			$inf_num = 0.78125;
			break;
	}

	//put each horse's name in an array based on a single horse's name entered on each line
	$horse_name_array = (preg_split('/[\n]+/', $horsenames));
	fwrite($progress, "Horse names sent to server. \n");

	/* declare urls, checkbreed and display_names arrays. urls will contain URLs to send to allbreedpedigree.com, display
	names is for .csv formatting, and checkbreed will contain horse names to check s for "Thoroughbred" or "Quarter
	Horse" */
	$urls = Array();
	$checkbreed = Array();
	$display_names = Array();

	//loop through each horse's name and remove annoying whitespace and plus signs (+) from the horses' names for the URL
	for ($i = 0; $i < count($horse_name_array); $i++)
	{
        array_push($display_names, $horse_name_array[$i]);
		$horse_name_array[$i] = str_replace(' ', '+', $horse_name_array[$i]);
		$horse_name_array[$i] = trim(preg_replace('/\s+/', '', $horse_name_array[$i]));
	}

	//make display names in .csv uppercase based on legacy app and client preference
	$display_names = array_map('strtoupper', $display_names);

	//replace excess whitespace for .csv display purposes
    for($i = 0; $i < count($display_names); $i++)
    {
        $display_names[$i] = trim(preg_replace('/\s+/', ' ', $display_names[$i]));
    }

	fwrite($progress, "Horse names formatted for database query. \n");
	//begin checking breeds
  for ($j = 0; $j < count($horse_name_array); $j++)
	{
		array_push($checkbreed, "http://www.allbreedpedigree.com/".$horse_name_array[$j]);
	}

	fwrite($progress, "Checking results for invalid names and non-Quarter Horses. \n");
		//start output buffer
    ob_start();

    $page_data = '';
		//curling function for breed checking purposes
    function curl($url)
    {
        // assigning curl options to array
        $options = Array(
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_FOLLOWLOCATION => TRUE,
            CURLOPT_AUTOREFERER => TRUE,
            CURLOPT_CONNECTTIMEOUT => 1200,
            CURLOPT_TIMEOUT => 1200,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8",  //setting the useragent
            CURLOPT_URL => $url, //setting curl's url option with the $url variable passed into the function
        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
		//curl each url in the checkbreed array
    foreach ($checkbreed as $cb)
    {
        $page_data = curl($cb);
        echo $page_data;
	}
	fwrite($progress, "Horse names sent to database. \n");

	$cbpage = ob_get_clean(); //set contents of output buffer equal to page
	fwrite($progress, "Combing through data to delete non-Quarter Horses. \n");
	$cbpage = html_entity_decode($cbpage); //get rid of entities

	$first_column = array(); //used in .csv file to display horse name in first column of every horse table
	$cbhtml = str_get_html($cbpage); //convert ob string to html
    $breed = Array(); //used to store page titles
		//get each title from each html page
    foreach($cbhtml->find('title') as $title)
    {
        $breed[] = $title->plaintext;
    }
    //go through each page title
    $incrementer = 1;

    for($i = 0; $i < count($horse_name_array); $i++)
    {
        fwrite($progress, "Horse ". $incrementer ." of ".count($horse_name_array)." checked \n");
        $incrementer++;
				//if the page title does have the word Quarter Horse in it, perform these operations
        if(strpos($breed[$i], "Quarter Horse") !== FALSE)
        {
						//check to see if there are multiple horses with the same name
            $curl_url = "http://www.allbreedpedigree.com/index.php?query_type=check&search_bar=linebreeding&hypo_sire=&hypo_dam=&what=done&sort=inf&border=0&h=".$horse_name_array[$i]."&g=".$gens."&crosses=".$crosses."&inf=".$inf_num."&all=".$filter."&sort=inf&t=&username=".$_SESSION['username']."&password=".$_SESSION['password'];
						//start output buffer
						ob_start();
						//curl url and store contents in $page_data
						$page_data = curl($curl_url);
            echo $page_data;
						//store contents of output buffer into $search_page and convert it to html
            $search_page = ob_get_clean();
            $search_html = str_get_html($search_page);
						//search for "legend" tag. this tag only appears if there are multiple horses with the same name.
            $legend = $search_html->find('legend');
						//if there is no legend tag, the horse is unique and is a quarter horse. store the above url into urls array to be used later.
            if (!$legend)
            {
                array_push($urls, $curl_url);
								//push horse name to first_column array to be used in .csv output
                array_push($first_column, $display_names[$i]);
            }
						//if there is a legend tag, the horse is not unique. search for the horse that is a quarter horse within the page.
            else
            {
								//get "Multiple Horse Occurrence" page
                $curl_url = "http://www.allbreedpedigree.com/index.php?query_type=check&search_bar=linebreeding&hypo_sire=&hypo_dam=&what=done&sort=inf&border=0&h=".$horse_name_array[$i]."&g=".$gens."&crosses=".$crosses."&inf=".$inf_num."&all=".$filter."&sort=inf&t=&username=".$_SESSION['username']."&password=".$_SESSION['password'];
								//start output buffer
								ob_start();
								//curl url and store contents in $page_data
                $page_data = curl($curl_url);
                echo $page_data;
								//store contents of output buffer into $search_page and convert it to html
                $search_page = ob_get_clean();
                $search_html = str_get_html($search_page);
								//comb through tds to find the one whose innertext equals "Quarter Horse"
                foreach($search_html->find('td') as $col)
                {
										//if the td contains the name of the horse, peek at the adjacent td and look at its contents.
                    if ($col->plaintext == $display_names[$i])
                    {
                        $next_col = $col->next_sibling();
												//if the next td contains the words "Quarter Horse", get the link from the td you are currently in
                        if ($next_col->plaintext == "QUARTER HORSE")
                        {
                            foreach($col->find('a') as $link)
                            {
                                $href = $link->href;
                            }
														//format the link to be consistent with the urls array and push it to the urls array to be used later
                            $formatted_link = "http://www.allbreedpedigree.com/".$href;
                            $formatted_link = str_replace(' ', '+', $formatted_link);
                            array_push($urls, $formatted_link);
														//push horse name to first_column array to be used in .csv output
                            array_push($first_column, $display_names[$i]);
                        }

                    }
                }
            }
        }
				//if the page title contains the word "Appendix" within it, perform these operations
        else if(strpos($breed[$i], "Appendix") !== FALSE)
        {
              //check to see if there are multiple horses with the same name
              $curl_url = "http://www.allbreedpedigree.com/index.php?query_type=check&search_bar=linebreeding&hypo_sire=&hypo_dam=&what=done&sort=inf&border=0&h=".$horse_name_array[$i]."&g=".$gens."&crosses=".$crosses."&inf=".$inf_num."&all=".$filter."&sort=inf&t=&username=".$_SESSION['username']."&password=".$_SESSION['password'];
              //start output buffer
              ob_start();
              //curl url and store contents in $page data
              $page_data = curl($curl_url);
              echo $page_data;
              //store contents of output buffer into $search_page and convert it to html
              $search_page = ob_get_clean();
              $search_html = str_get_html($search_page);
              //search for "legend" tag. this tag only appears if there are multiple horses with the same name.
              $legend = $search_html->find('legend');
              /*if there is no legend tag, and if the title contains the words "appendix", the horse is unique and is a quarter horse.
              store the above url into urls array to be used later. i know that the logic is weird considering this block of code only
              executes if the title doesn't contain "appendix", but it serves to filter out non-quarter horses from the query.
              if the horse has no breed in the title, it will be added to the urls array as well.*/
              if (!$legend && strpos($breed[$i], "Appendix") !== FALSE)
              {
                  array_push($urls, $curl_url);
                  //push horse name to first_column array to be used in .csv output
                  array_push($first_column, $display_names[$i]);
              }
              //if there is a legend tag, the horse is not unique. search for the horse that is an appendix within the page.
              //this logic automatically assumes that you are taken to the "Multiple Horse Occurrence" page, so no curling is needed
              else
              {
                //get "Multiple Horse Occurrence" page
                $curl_url = "http://www.allbreedpedigree.com/index.php?query_type=check&search_bar=linebreeding&hypo_sire=&hypo_dam=&what=done&sort=inf&border=0&h=".$horse_name_array[$i]."&g=".$gens."&crosses=".$crosses."&inf=".$inf_num."&all=".$filter."&sort=inf&t=&username=".$_SESSION['username']."&password=".$_SESSION['password'];
                //start output buffer
                ob_start();
                //curl url and store contents in $page data
                $page_data = curl($curl_url);
                echo $page_data;
                //store contents of output buffer into $search_page and convert it to html
                $search_page = ob_get_clean();
                $search_html = str_get_html($search_page);
                  //comb through tds to find the one that contains the words "appendix"
                  foreach($search_html->find('td') as $col)
                  {
                    //if the td contains the name of the horse, peek at the adjacent td and look at its contents.
                      if ($col->plaintext == $display_names[$i])
                      {
                          $next_col = $col->next_sibling();
                          //if the next td contains the words "appendix", get the link from the td you are currently in

                              foreach($col->find('a') as $link)
                              {
                                  $href = $link->href;
                              }
                              //format the link to be consistent with the urls array and push it to the urls array to be used later
                              $formatted_link = "http://www.allbreedpedigree.com/".$href;
                              $formatted_link = str_replace(' ', '+', $formatted_link);
                              array_push($urls, $formatted_link);
                              //push horse name to first_column array to be used in .csv output
                              array_push($first_column, $display_names[$i]);

                      }
                  }
              }
        }
				//if the page title does not have the words "Quarter Horse" within it, and the horse is not an appendix, perform these operations
        else if(strpos($breed[$i], "Quarter Horse") === FALSE)
        {
						//check to see if there are multiple horses with the same name
						$curl_url = "http://www.allbreedpedigree.com/index.php?query_type=check&search_bar=linebreeding&hypo_sire=&hypo_dam=&what=done&sort=inf&border=0&h=".$horse_name_array[$i]."&g=".$gens."&crosses=".$crosses."&inf=".$inf_num."&all=".$filter."&sort=inf&t=&username=".$_SESSION['username']."&password=".$_SESSION['password'];
						//start output buffer
						ob_start();
						//curl url and store contents in $page data
						$page_data = curl($curl_url);
            echo $page_data;
						//store contents of output buffer into $search_page and convert it to html
            $search_page = ob_get_clean();
            $search_html = str_get_html($search_page);
						//search for "legend" tag. this tag only appears if there are multiple horses with the same name.
            $legend = $search_html->find('legend');
						/*if there is no legend tag, the horse is unique and is a quarter horse.*/
            if (!$legend)
            {
                array_push($urls, $curl_url);
								//push horse name to first_column array to be used in .csv output
                array_push($first_column, $display_names[$i]);
            }
						//if there is a legend tag, the horse is not unique. search for the horse that is a quarter horse within the page.
            //this logic automatically assumes that you are taken to the "Multiple Horse Occurrence" page, so no curling is needed
            else
            {
								//comb through tds to find the one that contains the words "Quarter Horse"
                foreach($search_html->find('td') as $col)
                {
										//if the td contains the name of the horse, peek at the adjacent td and look at its contents.
                    if ($col->plaintext == $display_names[$i])
                    {
                        $next_col = $col->next_sibling();
												//if the next td contains the words "Quarter Horse", get the link from the td you are currently in
                        if ($next_col->plaintext == "QUARTER HORSE")
                        {
                            foreach($col->find('a') as $link)
                            {
                                $href = $link->href;
                            }
														//format the link to be consistent with the urls array and push it to the urls array to be used later
                            $formatted_link = "http://www.allbreedpedigree.com/".$href;
                            $formatted_link = str_replace(' ', '+', $formatted_link);
                            //echo $formatted_link;
                            array_push($urls, $formatted_link);
														//push horse name to first_column array to be used in .csv output
                            array_push($first_column, $display_names[$i]);
                        }
                    }
                }
            }
        }
    }
	fwrite($progress, "Checked for non-Quarter Horses and removed them from the data. \n");
	ob_start();

	//go curling
	$incrementer = 0;

	foreach ($urls as $url)
	{
		$urlcount = count($urls);
		$incrementer++;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1200);
		curl_setopt($ch, CURLOPT_TIMEOUT, 1200);

		curl_exec($ch);
		curl_close($ch);
		fwrite($progress, "Horse ". $incrementer ." of ".$urlcount." processed \n");
	}

	//output returned curl data as $page
	$page = ob_get_clean();

	//get rid of all the < and > and other entities in the data
	$page = html_entity_decode($page);

	//parse the string of data in $page as html in $html
	$html = str_get_html($page);

	//start output buffering again
	ob_start();

	//declare full_data array
    $full_data = array();
	fwrite($progress, "Beginning to format data for display in .csv. \n");
	//simple dom parser find for all images and get rid of them with empty strings
	foreach($html->find('img') as $images)
	{
		$images->outertext = '';
	}

	//get rid of header class  elements
	foreach($html->find('.header') as $headers)
	{
		$headers->outertext = '';
	}

	//find  elements and get rid of all their attributes
	foreach($html->find('td') as $cells)
	{
		$cells->class = null;
		$cells->onmousedown = null;
		$cells->align = null;
		$cells->colspan = null;
	}

	//find all the data between the  elements without a class
	foreach($html->find('center[!class]') as $horse)
	{
        //echo $horse;
		//remove all the html besides
 and store in $horse
		$horse = strip_tags($horse,'
');
		//parse $horse as HTML again
		$horse = str_get_html($horse);
		//find all the empty
 and get rid of them
		foreach($horse->find('b, td, tr') as $element)
		{
			if(trim($element->innertext) == '')
			{
				$element->outertext = '';
			}
		}

		//declare rowData array
		$rowData = array();

		//find all the
 and  elements to find the rows
		foreach($horse->find('tr, b') as $row)
		{
			//declare horse_data array
			$horse_data = array();

			//store  element values in plaintext in $horse data
			foreach($row->find('td') as $cell)
			{
				$horse_data[] = $cell->plaintext;
			}

			//put the  stuff from $horse_data[] into "rows" in $rowData[]
			$rowData[] = $horse_data;
		}

		//put the "rows" into $full_data
        $full_data[] = $rowData;

	}
	//declare raw_data array
    $raw_data = array();

	//loop through $full_data and return the big list of unchunked horse data
    foreach ($full_data as $fd)
    {
        $raw_data[] = $fd['3'];
    }
	//cut up the horse data into chunks of 7 's (cells) for display in .csv
    $chunked_data = array();
    foreach($raw_data as $rd)
    {
        $chunked_data[] = array_chunk($rd, 7);
    }

    //adds display names to the first column of each row for the corresponding horse

	for ($i = 0; $i < count($chunked_data); $i++)
    {
        for ($j = 0; $j < count($chunked_data[$i]); $j++)
        {
            array_unshift($chunked_data[$i][$j], $first_column[$i]);
        }
    }
	//go through the chunked data
	$i=0;
	foreach ($chunked_data as $cd)
    {
		//remove the inbreeding coefficient number from the bottom of the results and place as the top per client preference

		$coef = array_pop($cd);
		$coef = implode($coef);
		$coef = preg_replace("/[^\d,.]/", "", $coef);$coef = $coef."%";

        $sort_array = array($first_column[$i], substr($coef, 1), "***");
        fputcsv($output, $sort_array);
		//output headings after coefficient number
		fputcsv($output, $heading_array);

		//remove numbers from horse names for duplicate horses.
        foreach ($cd as $second)
        {
                $second['1'] = preg_replace('/\d*$/', '', $second['1']);
                fputcsv($output, $second);
        }
		fwrite($output, "\n");
		$i++;
    }

	//scraped tables contains all the formatted data for .csv
	$scraped_tables = ob_get_clean();

	//output the data for .csv
	fwrite($output, $scraped_tables);
	fwrite($progress, ".csv is ready. \n");
	//print_r($chunked_data);
	ob_end_clean();
	unlink('progress.txt');
	fwrite($progress, "Downloading. \n");
	fwrite($progress, "Query finished. \n");
	exit();

?>


text:
import { NonNullLoadable, onLoadableError, onLoadableLoad, onLoadableSuccess } from '../shared/loadable/loadable';
import { insertItem, removeItem, updateItem } from '../shared/util';
import { FormsActions, FormsActionTypes } from './forms.actions';
import { FormResponsesState, FormsState, initialFormsState, responsesAdapter } from './forms.state';
import { FormSettings } from './interfaces/forms';

export function formsReducer(state: FormsState = initialFormsState, action: FormsActions): FormsState {
  switch (action.type) {
    case FormsActionTypes.GET_FORMS:
      return { ...state, forms: onLoadableLoad(initialFormsState.forms.data) };
    case FormsActionTypes.GET_FORMS_COMPLETE:
      return { ...state, forms: onLoadableSuccess(action.forms) };
    case FormsActionTypes.GET_FORMS_FAILED:
      return { ...state, forms: onLoadableError(action.error, state.forms.data) };
    case FormsActionTypes.GET_FORM:
      return {
        ...state,
        form: onLoadableLoad(initialFormsState.form.data),
        tombolaWinners: initialFormsState.tombolaWinners,
        formResponses: initialFormsState.formResponses,
        selectedFormResponseId: initialFormsState.selectedFormResponseId,
      };
    case FormsActionTypes.GET_FORM_COMPLETE:
      return { ...state, form: onLoadableSuccess(action.form) };
    case FormsActionTypes.GET_FORM_FAILED:
      return { ...state, form: onLoadableError(action.error, state.form.data) };
    case FormsActionTypes.GET_FORM_STATISTICS:
      return { ...state, formStatistics: onLoadableLoad(initialFormsState.formStatistics.data) };
    case FormsActionTypes.GET_FORM_STATISTICS_COMPLETE:
      return { ...state, formStatistics: onLoadableSuccess(action.stats) };
    case FormsActionTypes.GET_FORM_STATISTICS_FAILED:
      return { ...state, formStatistics: onLoadableError(action.error, state.formStatistics.data) };
    case FormsActionTypes.SAVE_FORM:
      return { ...state, updatedForm: onLoadableLoad(initialFormsState.updatedForm.data) };
    case FormsActionTypes.SAVE_FORM_COMPLETE:
      return {
        ...state,
        form: onLoadableSuccess(action.form),
        updatedForm: onLoadableSuccess(action.form),
        forms: { ...state.forms, data: updateItem(state.forms.data as FormSettings[], action.form.settings, 'id') },
      };
    case FormsActionTypes.SAVE_FORM_FAILED:
      return { ...state, updatedForm: onLoadableError(action.error, state.updatedForm.data) };
    case FormsActionTypes.CREATE_FORM:
      return { ...state, createdForm: onLoadableLoad(initialFormsState.createdForm.data) };
    case FormsActionTypes.CREATE_FORM_COMPLETE:
      return {
        ...state,
        form: onLoadableSuccess(action.form),
        createdForm: onLoadableSuccess(action.form),
        forms: { ...state.forms, data: insertItem(state.forms.data as FormSettings [], action.form.settings) },
      };
    case FormsActionTypes.CREATE_FORM_FAILED:
      return { ...state, createdForm: onLoadableError(action.error, state.createdForm.data) };
    case FormsActionTypes.GET_TOMBOLA_WINNERS:
      return { ...state, tombolaWinners: onLoadableLoad(initialFormsState.tombolaWinners.data) };
    case FormsActionTypes.GET_TOMBOLA_WINNERS_COMPLETE:
      return { ...state, tombolaWinners: onLoadableSuccess(action.payload) };
    case FormsActionTypes.GET_TOMBOLA_WINNERS_FAILED:
      return { ...state, tombolaWinners: onLoadableError(action.error, state.tombolaWinners.data) };
    case FormsActionTypes.DELETE_ALL_RESPONSES_COMPLETE:
      return {
        ...state,
        formStatistics: onLoadableSuccess({ submissions: 0, statistics: {} }),
        selectedFormResponseId: initialFormsState.selectedFormResponseId,
        formResponses: initialFormsState.formResponses,
      };
    case FormsActionTypes.DELETE_RESPONSE_COMPLETE:
      return {
        ...state,
        selectedFormResponseId: getNextItemInArray(state.formResponses.data.ids as number[], action.payload.submissionId),
        formResponses: onLoadableSuccess(responsesAdapter.removeOne(action.payload.submissionId, state.formResponses.data)),
      };
    case FormsActionTypes.DELETE_FORM_COMPLETE:
      return { ...state, forms: { ...state.forms, data: removeItem(state.forms.data as FormSettings[], action.form.id, 'id') } };
    case FormsActionTypes.GET_RESPONSE:
      return {
        ...state,
        selectedFormResponseId: action.payload.id,
      };
    case FormsActionTypes.GET_RESPONSES:
      const responses = action.clear ? responsesAdapter.removeAll(state.formResponses.data) : state.formResponses.data;
      return {
        ...state,
        formResponses: onLoadableLoad(responses) as NonNullLoadable<FormResponsesState>,
      };
    case FormsActionTypes.GET_RESPONSES_COMPLETE:
      return {
        ...state,
        selectedFormResponseId: action.payload.results.length ? action.payload.results[ 0 ].id : state.selectedFormResponseId,
        formResponses: onLoadableSuccess(
          responsesAdapter.upsertMany(action.payload.results, {
            ...state.formResponses.data,
            cursor: action.payload.cursor,
            more: action.payload.more,
          })),
      };
    case FormsActionTypes.GET_INTEGRATIONS:
      return { ...state, integrations: onLoadableLoad(initialFormsState.integrations.data) };
    case FormsActionTypes.GET_INTEGRATIONS_COMPLETE:
      return { ...state, integrations: onLoadableSuccess(action.payload) };
    case FormsActionTypes.GET_INTEGRATIONS_FAILED:
      return { ...state, integrations: onLoadableError(action.error, initialFormsState.integrations.data) };
    case FormsActionTypes.UPDATE_INTEGRATION:
      return { ...state, integrations: onLoadableLoad(state.integrations.data) };
    case FormsActionTypes.UPDATE_INTEGRATION_COMPLETE:
      return { ...state, integrations: onLoadableSuccess(updateItem(state.integrations.data, action.payload, 'provider')) };
    case FormsActionTypes.UPDATE_INTEGRATION_FAILED:
      return { ...state, integrations: onLoadableError(action.error, state.integrations.data) };
    case FormsActionTypes.IMPORT_FORM:
      return {
        ...state,
        form: state.form.data ? {
          ...state.form,
            data: {...state.form.data, form: {...state.form.data.form, ...action.payload.form}}
        } : state.form
      };
  }
  return state;
}

function getNextItemInArray(array: number[], currentItem: number): number | null {
  const currentIndex = array.indexOf(currentItem);
  const index = currentIndex + 1 === array.length ? currentIndex - 1 : currentIndex + 1;
  if (index in array) {
    return array[ index ];
  }
  return null;
}


text:
A rather crude implementation of a TransXChange to GTFS converter written in Objective-C. It needs a *lot* of work, but the basics are there. It's ultimately intended to be used a command line tool in the import process of the Transporter API.

[TransXChange](https://www.gov.uk/government/collections/transxchange) is the UK standard for publishing transportation data. TransXChange, whilst comprehensive, is tricky to parse and even trickier to understand. [GTFS](https://developers.google.com/transit/gtfs/) (General Transit Feed Specification) is a CSV based transit format which is much easier to parse and query.

## Known Issues

- Needs a UI / command to import documents
- Doesn't factor in public holidays
- No examples / poor documentation.

## Maintainers

- [Phillip Caudell](http://phillipcaudell.com) [(@phillipcaudell)](http://twitter.com/phillipcaudell)

## License

Lightning Table is available under the MIT license. See the LICENSE file for more info.