text:
HOMEBREW_TAP_ARGS_REGEX = %r{^([\w-]+)/(homebrew-)?([\w-]+)$}
# match taps' formulae, e.g. someuser/sometap/someformula
HOMEBREW_TAP_FORMULA_REGEX = %r{^([\w-]+)/([\w-]+)/([\w+-.]+)$}
# match core's formulae, e.g. homebrew/homebrew/someformula
HOMEBREW_CORE_FORMULA_REGEX = %r{^homebrew/homebrew/([\w+-.]+)$}i
# match taps' directory paths, e.g. HOMEBREW_LIBRARY/Taps/someuser/sometap
HOMEBREW_TAP_DIR_REGEX = %r{#{Regexp.escape(HOMEBREW_LIBRARY.to_s)}/Taps/([\w-]+)/([\w-]+)}
# match taps' formula paths, e.g. HOMEBREW_LIBRARY/Taps/someuser/sometap/someformula
HOMEBREW_TAP_PATH_REGEX = Regexp.new(HOMEBREW_TAP_DIR_REGEX.source + %r{/(.*)}.source)
# match the default brew-cask tap e.g. Caskroom/cask
HOMEBREW_CASK_TAP_FORMULA_REGEX = %r{^(Caskroom)/(cask)/([\w+-.]+)$}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ophiotrichum acalyphae Thüm.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.11.22 at 01:45:09 PM EST
//

package uk.org.siri.siri_2;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * Requests for CONNECTION LINK data for use in service requests. +SIRI v2.0
 *
 *
Java class for ConnectionLinksDiscoveryRequestStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ConnectionLinksDiscoveryRequestStructure">
 *   <complexContent>
 *     <extension base="{http://www.siri.org.uk/siri}AbstractDiscoveryRequestStructure">
 *       <sequence>
 *         <group ref="{http://www.siri.org.uk/siri}ConnectionLinksDiscoveryRequestTopicGroup"/>
 *         <group ref="{http://www.siri.org.uk/siri}ConnectionLinksDiscoveryRequestPolicyGroup"/>
 *         <element ref="{http://www.siri.org.uk/siri}Extensions" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="version" use="required" type="{http://www.siri.org.uk/siri}VersionString" fixed="2.0" />
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConnectionLinksDiscoveryRequestStructure", propOrder = {
    "boundingBox",
    "circle",
    "placeRef",
    "lineRef",
    "operatorRef",
    "language",
    "connectionLinksDetailLevel",
    "extensions"
})
public class ConnectionLinksDiscoveryRequestStructure
    extends AbstractDiscoveryRequestStructure
{

    @XmlElement(name = "BoundingBox")
    protected BoundingBoxStructure boundingBox;
    @XmlElement(name = "Circle")
    protected LocationStructure circle;
    @XmlElement(name = "PlaceRef")
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    @XmlSchemaType(name = "normalizedString")
    protected String placeRef;
    @XmlElement(name = "LineRef")
    protected LineRefStructure lineRef;
    @XmlElement(name = "OperatorRef")
    protected OperatorRefStructure operatorRef;
    @XmlElement(name = "Language", defaultValue = "en")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String language;
    @XmlElement(name = "ConnectionLinksDetailLevel", defaultValue = "normal")
    protected ConnectionLinksDetailEnumeration connectionLinksDetailLevel;
    @XmlElement(name = "Extensions")
    protected ExtensionsStructure extensions;
    @XmlAttribute(name = "version", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String version;

    /**
     * Gets the value of the boundingBox property.
     *
     * @return
     *     possible object is
     *     {@link BoundingBoxStructure }
     *
     */
    public BoundingBoxStructure getBoundingBox() {
        return boundingBox;
    }

    /**
     * Sets the value of the boundingBox property.
     *
     * @param value
     *     allowed object is
     *     {@link BoundingBoxStructure }
     *
     */
    public void setBoundingBox(BoundingBoxStructure value) {
        this.boundingBox = value;
    }

    /**
     * Gets the value of the circle property.
     *
     * @return
     *     possible object is
     *     {@link LocationStructure }
     *
     */
    public LocationStructure getCircle() {
        return circle;
    }

    /**
     * Sets the value of the circle property.
     *
     * @param value
     *     allowed object is
     *     {@link LocationStructure }
     *
     */
    public void setCircle(LocationStructure value) {
        this.circle = value;
    }

    /**
     * Gets the value of the placeRef property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPlaceRef() {
        return placeRef;
    }

    /**
     * Sets the value of the placeRef property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPlaceRef(String value) {
        this.placeRef = value;
    }

    /**
     * Gets the value of the lineRef property.
     *
     * @return
     *     possible object is
     *     {@link LineRefStructure }
     *
     */
    public LineRefStructure getLineRef() {
        return lineRef;
    }

    /**
     * Sets the value of the lineRef property.
     *
     * @param value
     *     allowed object is
     *     {@link LineRefStructure }
     *
     */
    public void setLineRef(LineRefStructure value) {
        this.lineRef = value;
    }

    /**
     * Gets the value of the operatorRef property.
     *
     * @return
     *     possible object is
     *     {@link OperatorRefStructure }
     *
     */
    public OperatorRefStructure getOperatorRef() {
        return operatorRef;
    }

    /**
     * Sets the value of the operatorRef property.
     *
     * @param value
     *     allowed object is
     *     {@link OperatorRefStructure }
     *
     */
    public void setOperatorRef(OperatorRefStructure value) {
        this.operatorRef = value;
    }

    /**
     * Gets the value of the language property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLanguage() {
        return language;
    }

    /**
     * Sets the value of the language property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLanguage(String value) {
        this.language = value;
    }

    /**
     * Gets the value of the connectionLinksDetailLevel property.
     *
     * @return
     *     possible object is
     *     {@link ConnectionLinksDetailEnumeration }
     *
     */
    public ConnectionLinksDetailEnumeration getConnectionLinksDetailLevel() {
        return connectionLinksDetailLevel;
    }

    /**
     * Sets the value of the connectionLinksDetailLevel property.
     *
     * @param value
     *     allowed object is
     *     {@link ConnectionLinksDetailEnumeration }
     *
     */
    public void setConnectionLinksDetailLevel(ConnectionLinksDetailEnumeration value) {
        this.connectionLinksDetailLevel = value;
    }

    /**
     * Gets the value of the extensions property.
     *
     * @return
     *     possible object is
     *     {@link ExtensionsStructure }
     *
     */
    public ExtensionsStructure getExtensions() {
        return extensions;
    }

    /**
     * Sets the value of the extensions property.
     *
     * @param value
     *     allowed object is
     *     {@link ExtensionsStructure }
     *
     */
    public void setExtensions(ExtensionsStructure value) {
        this.extensions = value;
    }

    /**
     * Gets the value of the version property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVersion() {
        if (version == null) {
            return "2.0";
        } else {
            return version;
        }
    }

    /**
     * Sets the value of the version property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVersion(String value) {
        this.version = value;
    }

}


text: console.log(caches);  // CacheStorage {}


text:
def left_rotate(list, n):
    """Rotate list n times

    Attributes:
        list: A list to be rotated
        n: An integer representing the number of times to rotate
    """
    n %= len(list)
    return list[n:] + list[:n]

input_str = input()
n = int(input())
list = input_str.split()

result = left_rotate(list, n)
print(result)


text:
import { mean, extent } from 'd3-array';

import functor from '../util/functor';

function midpoint(arr, value) {
  value = functor(value || function(d){return d;});
  if(arr.length) return mean(extent(arr, value));
}

midpoint.tendancy = 'midpoint';

export default midpoint;


text:
"""Types used in Google Cloud AI Platform under experimental stage."""

from tfx.extensions.google_cloud_ai_platform.bulk_inferrer.executor import SERVING_ARGS_KEY as BULK_INFERRER_SERVING_ARGS_KEY
from tfx.extensions.google_cloud_ai_platform.constants import ENDPOINT_ARGS_KEY
# PUSHER_SERVING_ARGS_KEY is deprecated.
# Please use tfx.extensions.google_cloud_ai_platform.SERVING_ARGS_KEY instead.
from tfx.extensions.google_cloud_ai_platform.constants import SERVING_ARGS_KEY as PUSHER_SERVING_ARGS_KEY
from tfx.extensions.google_cloud_ai_platform.tuner.executor import REMOTE_TRIALS_WORKING_DIR_KEY
from tfx.extensions.google_cloud_ai_platform.tuner.executor import TUNING_ARGS_KEY


text:
<?php

// C:\xampp\htdocs\jquery\src\Acme\DemoBundle/Resources/views\layout.html.twig
return array (
);


text:
/****************************************************************************
** Meta object code from reading C++ file 'optionsdialog.h'
**
** Created: Thu Dec 11 09:26:27 2014
**      by: The Qt Meta Object Compiler version 63 (Qt 4.8.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../src/qt/optionsdialog.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'optionsdialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_OptionsDialog[] = {

 // content:
       6,       // revision
       0,       // classname
       0,    0, // classinfo
       6,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       0,       // signalCount

 // slots: signature, parameters, type, tag, flags
      14,   30,   36,   36, 0x0a,
      37,   36,   36,   36, 0x08,
      49,   36,   36,   36, 0x08,
      65,   36,   36,   36, 0x08,
      80,   36,   36,   36, 0x08,
      94,   36,   36,   36, 0x08,

       0        // eod
};

static const char qt_meta_stringdata_OptionsDialog[] = {
    "OptionsDialog\0changePage(int)\0index\0"
    "\0okClicked()\0cancelClicked()\0"
    "applyClicked()\0enableApply()\0"
    "disableApply()\0"
};

void OptionsDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        Q_ASSERT(staticMetaObject.cast(_o));
        OptionsDialog *_t = static_cast<OptionsDialog *>(_o);
        switch (_id) {
        case 0: _t->changePage((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: _t->okClicked(); break;
        case 2: _t->cancelClicked(); break;
        case 3: _t->applyClicked(); break;
        case 4: _t->enableApply(); break;
        case 5: _t->disableApply(); break;
        default: ;
        }
    }
}

const QMetaObjectExtraData OptionsDialog::staticMetaObjectExtraData = {
    0,  qt_static_metacall
};

const QMetaObject OptionsDialog::staticMetaObject = {
    { &QDialog::staticMetaObject, qt_meta_stringdata_OptionsDialog,
      qt_meta_data_OptionsDialog, &staticMetaObjectExtraData }
};

#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &OptionsDialog::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION

const QMetaObject *OptionsDialog::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}

void *OptionsDialog::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_OptionsDialog))
        return static_cast<void*>(const_cast< OptionsDialog*>(this));
    return QDialog::qt_metacast(_clname);
}

int OptionsDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDialog::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 6)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 6;
    }
    return _id;
}
QT_END_MOC_NAMESPACE


text:
package de.hbrs.aspgen.jparser;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.HashSet;

import org.junit.Test;

import de.hbrs.aspgen.jparser.type.Java6Annotation;
import de.hbrs.aspgen.jparser.type.Java6Class;
import de.hbrs.aspgen.jparser.type.Java6Field;
import de.hbrs.aspgen.jparser.type.Java6Method;
import de.hbrs.aspgen.jparser.type.Java6Parameter;

public class JavaClassWithAnnotationsAndImports {
    @Test
    public void replaceClassAnnotations() {
        final Java6Class java6Class = new Java6Class();
        final Java6Annotation annotation = new Java6Annotation();
        annotation.setName("ToString");
        java6Class.addAnnotation(annotation);
        final Java6Annotation annotation2 = new Java6Annotation();
        annotation2.setName("JavaBean");
        java6Class.addAnnotation(annotation2);
        final Java6Annotation annotation3 = new Java6Annotation();
        annotation3.setName("de.package.HashCode");
        java6Class.addAnnotation(annotation3);
        java6Class.addImport("de.hbrs.ToString");
        java6Class.addImport("de.pack.*");

        java6Class.replaceWithFullQualifiedAnnotations(new HashSet<>(Arrays.asList("de.hbrs.ToString", "de.package.HashCode", "de.pack.JavaBean")));

        assertEquals("de.hbrs.ToString", java6Class.getAnnotations().get(0).getName());
        assertEquals("de.pack.JavaBean", java6Class.getAnnotations().get(1).getName());
        assertEquals("de.package.HashCode", java6Class.getAnnotations().get(2).getName());
    }

    @Test
    public void replaceClassAnnotationsWithImports() {
        final Java6Class java6Class = new Java6Class();
        final Java6Annotation annotation = new Java6Annotation();
        annotation.setName("ToString");
        java6Class.addAnnotation(annotation);
        final Java6Annotation annotation2 = new Java6Annotation();
        annotation2.setName("JavaBean");
        java6Class.addAnnotation(annotation2);
        final Java6Annotation annotation3 = new Java6Annotation();
        annotation3.setName("de.package.HashCode");
        java6Class.addAnnotation(annotation3);
        java6Class.addImport("de.hbrs.ToString");

        java6Class.replaceWithFullQualifiedAnnotations(new HashSet<>(Arrays.asList("de.hbrs.ToString", "de.package.HashCode", "de.pack.JavaBean")));

        assertEquals("de.hbrs.ToString", java6Class.getAnnotations().get(0).getName());
        assertEquals("JavaBean", java6Class.getAnnotations().get(1).getName());
        assertEquals("de.package.HashCode", java6Class.getAnnotations().get(2).getName());
    }

    @Test
    public void replaceClassAndFieldAnnotations() {
        final Java6Class java6Class = new Java6Class();
        final Java6Annotation annotation = new Java6Annotation();
        annotation.setName("ToString");
        java6Class.addAnnotation(annotation);
        final Java6Annotation annotation2 = new Java6Annotation();
        annotation2.setName("JavaBean");
        java6Class.addAnnotation(annotation2);
        final Java6Annotation annotation3 = new Java6Annotation();
        annotation3.setName("de.package.HashCode");
        java6Class.addAnnotation(annotation3);

        final Java6Field java6Field = new Java6Field();
        final Java6Annotation annotation4= new Java6Annotation();
        annotation4.setName("FieldAnno1");
        java6Field.addAnnotation(annotation4);
        java6Class.addField(java6Field);

        final Java6Field java6Field2 = new Java6Field();
        final Java6Annotation annotation5= new Java6Annotation();
        annotation5.setName("FieldAnno2");
        java6Field2.addAnnotation(annotation5);
        java6Class.addField(java6Field2);

        java6Class.addImport("de.hbrs.ToString");
        java6Class.addImport("de.pack.*");
        java6Class.addImport("de.field.*");

        java6Class.replaceWithFullQualifiedAnnotations(new HashSet<>(Arrays.asList(
                "de.hbrs.ToString",
                "de.package.HashCode",
                "de.pack.JavaBean",
                "de.field.FieldAnno1",
                "de.fieldwithoutimport.FieldAnno2")));

        assertEquals("de.hbrs.ToString", java6Class.getAnnotations().get(0).getName());
        assertEquals("de.pack.JavaBean", java6Class.getAnnotations().get(1).getName());
        assertEquals("de.package.HashCode", java6Class.getAnnotations().get(2).getName());
        assertEquals("de.field.FieldAnno1", java6Class.getFields().get(0).getAnnotations().get(0).getName());
        assertEquals("FieldAnno2", java6Class.getFields().get(1).getAnnotations().get(0).getName());
    }

    @Test
    public void replaceClassAndMethodWithParameterAnnotations() {
        final Java6Class java6Class = new Java6Class();
        final Java6Annotation annotation = new Java6Annotation();
        annotation.setName("ToString");
        java6Class.addAnnotation(annotation);
        final Java6Annotation annotation2 = new Java6Annotation();
        annotation2.setName("JavaBean");
        java6Class.addAnnotation(annotation2);
        final Java6Annotation annotation3 = new Java6Annotation();
        annotation3.setName("de.package.HashCode");
        java6Class.addAnnotation(annotation3);

        final Java6Method java6Method = new Java6Method();
        final Java6Annotation annotation4 = new Java6Annotation();
        annotation4.setName("Anno1");
        java6Method.addAnnotation(annotation4);
        java6Class.addMethod(java6Method);

        final Java6Parameter java6Parameter = new Java6Parameter();
        final Java6Annotation annotation5 = new Java6Annotation();
        annotation5.setName("Anno2");
        java6Parameter.addAnnotation(annotation5);
        java6Method.addParameter(java6Parameter);

        final Java6Method java6Method2 = new Java6Method();
        final Java6Annotation annotation6 = new Java6Annotation();
        annotation6.setName("Anno3");
        java6Method2.addAnnotation(annotation6);
        java6Class.addMethod(java6Method2);

        java6Class.addImport("de.hbrs.ToString");
        java6Class.addImport("de.pack.*");
        java6Class.addImport("de.methodandparameter.*");

        java6Class.replaceWithFullQualifiedAnnotations(new HashSet<>(Arrays.asList("de.hbrs.ToString", "de.package.HashCode", "de.pack.JavaBean",
                "de.notimported.Anno1", "de.methodandparameter.Anno2", "de.methodandparameter.Anno3")));

        assertEquals("de.hbrs.ToString", java6Class.getAnnotations().get(0).getName());
        assertEquals("de.pack.JavaBean", java6Class.getAnnotations().get(1).getName());
        assertEquals("de.package.HashCode", java6Class.getAnnotations().get(2).getName());

        assertEquals("Anno1", java6Class.getMethods().get(0).getAnnotations().get(0).getName());
        assertEquals("de.methodandparameter.Anno2", java6Class.getMethods().get(0).getParameters().get(0).getAnnotations().get(0).getName());
        assertEquals("de.methodandparameter.Anno3", java6Class.getMethods().get(1).getAnnotations().get(0).getName());
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>CAPTCHA Helper — CodeIgniter 3.0.1 documentation</title>

    <link rel="shortcut icon" href="../_static/ci-icon.ico"/>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../_static/css/citheme.css" type="text/css" />

    <link rel="top" title="CodeIgniter 3.0.1 documentation" href="../index.html"/>
        <link rel="up" title="Helpers" href="index.html"/>
        <link rel="next" title="Cookie Helper" href="cookie_helper.html"/>
        <link rel="prev" title="Array Helper" href="array_helper.html"/>

           CodeIgniter

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Welcome to CodeIgniter

Installation Instructions

Downloading CodeIgniter

Installation Instructions

Upgrading From a Previous Version

Troubleshooting

CodeIgniter Overview

Getting Started

CodeIgniter at a Glance

Supported Features

Application Flow Chart

Model-View-Controller

Architectural Goals

Tutorial

Static pages

News section

Create news items

Conclusion

General Topics

CodeIgniter URLs

Controllers

Reserved Names

Views

Models

Helpers

Using CodeIgniter Libraries

Creating Libraries

Using CodeIgniter Drivers

Creating Drivers

Creating Core System Classes

Creating Ancillary Classes

Hooks - Extending the Framework Core

Auto-loading Resources

Common Functions

Compatibility Functions

URI Routing

Error Handling

Caching

Profiling Your Application

Running via the CLI

Managing your Applications

Handling Multiple Environments

Alternate PHP Syntax for View Files

Security

PHP Style Guide

Libraries

Benchmarking Class

Caching Driver

Calendaring Class

Shopping Cart Class

Config Class

Email Class

Encrypt Class

Encryption Library

File Uploading Class

Form Validation

FTP Class

Image Manipulation Class

Input Class

Javascript Class

Language Class

Loader Class

Migrations Class

Output Class

Pagination Class

Template Parser Class

Security Class

Session Library

HTML Table Class

Trackback Class

Typography Class

Unit Testing Class

URI Class

User Agent Class

XML-RPC and XML-RPC Server Classes

Zip Encoding Class

Database Reference

Quick Start: Usage Examples

Database Configuration

Connecting to a Database

Running Queries

Generating Query Results

Query Helper Functions

Query Builder Class

Transactions

Getting MetaData

Custom Function Calls

Query Caching

Database Manipulation with Database Forge

Database Utilities Class

Database Driver Reference

Helpers

Array Helper

CAPTCHA Helper

Cookie Helper

Date Helper

Directory Helper

Download Helper

Email Helper

File Helper

Form Helper

HTML Helper

Inflector Helper

Language Helper

Number Helper

Path Helper

Security Helper

Smiley Helper

String Helper

Text Helper

Typography Helper

URL Helper

XML Helper

Contributing to CodeIgniter

Writing CodeIgniter Documentation

Developer’s Certificate of Origin 1.1

        CodeIgniter

Docs »

Helpers »

CAPTCHA Helper

CAPTCHA Helper¶

The CAPTCHA Helper file contains functions that assist in creating
CAPTCHA images.

Loading this Helper

Using the CAPTCHA helper

Adding a Database

Available Functions

Loading this Helper¶

This helper is loaded using the following code:

$this->load->helper('captcha');

Using the CAPTCHA helper¶

Once loaded you can generate a CAPTCHA like this:

$vals = array(
        'word'          => 'Random word',
        'img_path'      => './captcha/',
        'img_url'       => 'http://example.com/captcha/',
        'font_path'     => './path/to/fonts/texb.ttf',
        'img_width'     => '150',
        'img_height'    => 30,
        'expiration'    => 7200,
        'word_length'   => 8,
        'font_size'     => 16,
        'img_id'        => 'Imageid',
        'pool'          => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

        // White background and border, black text and red grid
        'colors'        => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
        )
);

$cap = create_captcha($vals);
echo $cap['image'];

The captcha function requires the GD image library.

Only the img_path and img_url are required.

If a word is not supplied, the function will generate a random
ASCII string. You might put together your own word library that you
can draw randomly from.

If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.

The “captcha” directory must be writable

The expiration (in seconds) signifies how long an image will remain
in the captcha folder before it will be deleted. The default is two
hours.

word_length defaults to 8, pool defaults to ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’

font_size defaults to 16, the native GD font has a size limit. Specify a “true type” font for bigger sizes.

The img_id will be set as the “id” of the captcha image.

If any of the colors values is missing, it will be replaced by the default.

Adding a Database¶

In order for the captcha function to prevent someone from submitting,
you will need to add the information returned from <tt class="docutils literal">create_captcha()</tt>
to your database. Then, when the data from the form is submitted by
the user you will need to verify that the data exists in the database
and has not expired.

Here is a table prototype:

CREATE TABLE captcha (
        captcha_id bigint(13) unsigned NOT NULL auto_increment,
        captcha_time int(10) unsigned NOT NULL,
        ip_address varchar(45) NOT NULL,
        word varchar(20) NOT NULL,
        PRIMARY KEY `captcha_id` (`captcha_id`),
        KEY `word` (`word`)
);

Here is an example of usage with a database. On the page where the
CAPTCHA will be shown you’ll have something like this:

$this->load->helper('captcha');
$vals = array(
        'img_path'      => './captcha/',
        'img_url'       => 'http://example.com/captcha/'
);

$cap = create_captcha($vals);
$data = array(
        'captcha_time'  => $cap['time'],
        'ip_address'    => $this->input->ip_address(),
        'word'          => $cap['word']
);

$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);

echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';

Then, on the page that accepts the submission you’ll have something like
this:

// First, delete old captchas
$expiration = time() - 7200; // Two hour limit
$this->db->where('captcha_time < ', $expiration)
        ->delete('captcha');

// Then see if a captcha exists:
$sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();

if ($row->count == 0)
{
        echo 'You must submit the word that appears in the image.';
}

Available Functions¶

The following functions are available:

<tt class="descname">create_captcha</tt><big>(</big>[$data = ''[, $img_path = ''[, $img_url = ''[, $font_path = '']]]]<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Parameters:

$data (array) – Array of data for the CAPTCHA

$img_path (string) – Path to create the image in

$img_url (string) – URL to the CAPTCHA image folder

$font_path (string) – Server path to font

Returns:
array(‘word’ => $word, ‘time’ => $now, ‘image’ => $img)

Return type:
array

Takes an array of information to generate the CAPTCHA as input and
creates the image to your specifications, returning an array of
associative data about the image.

array(
        'image' => IMAGE TAG
        'time'  => TIMESTAMP (in microtime)
        'word'  => CAPTCHA WORD
)

The image is the actual image tag:

<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />

The time is the micro timestamp used as the image name without the
file extension. It will be a number like this: 1139612155.3422

The word is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.

        Next

         Previous

        © Copyright 2014 - 2015, British Columbia Institute of Technology.
      Last updated on Aug 07, 2015.

  Built with Sphinx using a theme provided by Read the Docs.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spark.planner;

import com.facebook.presto.Session;
import com.facebook.presto.common.predicate.TupleDomain;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.cost.CostCalculator;
import com.facebook.presto.cost.CostCalculatorUsingExchanges;
import com.facebook.presto.cost.PlanNodeStatsEstimate;
import com.facebook.presto.cost.StatsAndCosts;
import com.facebook.presto.cost.StatsCalculator;
import com.facebook.presto.cost.TaskCountEstimator;
import com.facebook.presto.dispatcher.NoOpQueryManager;
import com.facebook.presto.execution.NodeTaskMap;
import com.facebook.presto.execution.QueryManagerConfig;
import com.facebook.presto.execution.scheduler.LegacyNetworkTopology;
import com.facebook.presto.execution.scheduler.NodeScheduler;
import com.facebook.presto.execution.scheduler.NodeSchedulerConfig;
import com.facebook.presto.execution.scheduler.nodeSelection.NodeSelectionStats;
import com.facebook.presto.execution.scheduler.nodeSelection.SimpleTtlNodeSelectorConfig;
import com.facebook.presto.metadata.CatalogManager;
import com.facebook.presto.metadata.InMemoryNodeManager;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.operator.StageExecutionDescriptor;
import com.facebook.presto.security.AllowAllAccessControl;
import com.facebook.presto.spark.planner.IterativePlanFragmenter.PlanAndFragments;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorId;
import com.facebook.presto.spi.TableHandle;
import com.facebook.presto.spi.WarningCollector;
import com.facebook.presto.spi.plan.AggregationNode;
import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.spi.plan.PlanNodeId;
import com.facebook.presto.spi.plan.PlanNodeIdAllocator;
import com.facebook.presto.spi.plan.ProjectNode;
import com.facebook.presto.spi.plan.TableScanNode;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.analyzer.FeaturesConfig;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.NodePartitioningManager;
import com.facebook.presto.sql.planner.PartitioningHandle;
import com.facebook.presto.sql.planner.PartitioningProviderManager;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.Plan;
import com.facebook.presto.sql.planner.PlanFragment;
import com.facebook.presto.sql.planner.PlanFragmenter;
import com.facebook.presto.sql.planner.PlanVariableAllocator;
import com.facebook.presto.sql.planner.RuleStatsRecorder;
import com.facebook.presto.sql.planner.SubPlan;
import com.facebook.presto.sql.planner.TypeProvider;
import com.facebook.presto.sql.planner.iterative.IterativeOptimizer;
import com.facebook.presto.sql.planner.iterative.rule.TranslateExpressions;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.PlanFragmentId;
import com.facebook.presto.sql.planner.sanity.PlanChecker;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.SymbolReference;
import com.facebook.presto.tpch.TpchColumnHandle;
import com.facebook.presto.tpch.TpchTableHandle;
import com.facebook.presto.tpch.TpchTableLayoutHandle;
import com.facebook.presto.tpch.TpchTransactionHandle;
import com.facebook.presto.transaction.TransactionManager;
import com.facebook.presto.ttl.nodettlfetchermanagers.ThrowingNodeTtlFetcherManager;
import com.facebook.presto.util.FinalizerService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager;
import static com.facebook.presto.spark.planner.TestIterativePlanFragmenter.CanonicalTestFragment.toCanonicalTestFragment;
import static com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet;
import static com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder.assignment;
import static com.facebook.presto.sql.planner.optimizations.AggregationNodeUtils.count;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.LOCAL;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.REMOTE_STREAMING;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.systemPartitionedExchange;
import static com.facebook.presto.sql.relational.Expressions.variable;
import static com.facebook.presto.testing.TestingSession.createBogusTestingCatalog;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.transaction.InMemoryTransactionManager.createTestTransactionManager;
import static com.facebook.presto.transaction.TransactionBuilder.transaction;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Objects.requireNonNull;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class TestIterativePlanFragmenter
{
    private PlanFragmenter planFragmenter;
    private Session session;
    private MetadataManager metadata;
    private TransactionManager transactionManager;
    private FinalizerService finalizerService;
    private NodeScheduler nodeScheduler;
    private NodePartitioningManager nodePartitioningManager;

    @BeforeClass
    public void setUp()
    {
        session = testSessionBuilder().setCatalog("tpch").build();

        CatalogManager catalogManager = new CatalogManager();
        catalogManager.registerCatalog(createBogusTestingCatalog("tpch"));
        transactionManager = createTestTransactionManager(catalogManager);
        metadata = createTestMetadataManager(transactionManager, new FeaturesConfig());

        finalizerService = new FinalizerService();
        finalizerService.start();
        nodeScheduler = new NodeScheduler(
                new LegacyNetworkTopology(),
                new InMemoryNodeManager(),
                new NodeSelectionStats(),
                new NodeSchedulerConfig().setIncludeCoordinator(true),
                new NodeTaskMap(finalizerService),
                new ThrowingNodeTtlFetcherManager(),
                new NoOpQueryManager(),
                new SimpleTtlNodeSelectorConfig());
        PartitioningProviderManager partitioningProviderManager = new PartitioningProviderManager();
        nodePartitioningManager = new NodePartitioningManager(nodeScheduler, partitioningProviderManager, new NodeSelectionStats());
        planFragmenter = new PlanFragmenter(metadata, nodePartitioningManager, new QueryManagerConfig(), new SqlParser(), new FeaturesConfig());
    }

    @AfterClass(alwaysRun = true)
    public void tearDown()
    {
        planFragmenter = null;
        session = null;
        transactionManager = null;
        metadata = null;
        finalizerService.destroy();
        finalizerService = null;
        nodeScheduler.stop();
        nodeScheduler = null;
        nodePartitioningManager = null;
    }

    @Test
    public void testIterativePlanFragmenter()
    {
        TableScanNode ts1 = tableScan("ts1", "orderkey");
        TableScanNode ts2 = tableScan("ts2", "orderkey_0");
        PlanNode p1 = project("p1", ts1, variable("orderkey_1", BIGINT), new SymbolReference("orderkey"));
        ExchangeNode remoteExchange1 = systemPartitionedExchange(
                new PlanNodeId("re1"),
                REMOTE_STREAMING,
                p1,
                ImmutableList.of(new VariableReferenceExpression(Optional.empty(), "orderkey_1", BIGINT)),
                Optional.empty());
        ExchangeNode remoteExchange2 = systemPartitionedExchange(
                new PlanNodeId("re2"),
                REMOTE_STREAMING,
                ts2,
                ImmutableList.of(new VariableReferenceExpression(Optional.empty(), "orderkey_0", BIGINT)),
                Optional.empty());
        ExchangeNode localExchange = systemPartitionedExchange(
                new PlanNodeId("le"),
                LOCAL,
                remoteExchange2,
                ImmutableList.of(new VariableReferenceExpression(Optional.empty(), "orderkey_0", BIGINT)),
                Optional.empty());

        JoinNode join = join("join",
                remoteExchange1,
                localExchange,
                JoinNode.DistributionType.PARTITIONED,
                "orderkey_1",
                "orderkey_0");
        Map<String, Type> types = ImmutableMap.of(
                "orderkey", BIGINT,
                "orderkey_1", BIGINT,
                "orderkey_0", BIGINT);
        TypeProvider typeProvider = TypeProvider.copyOf(types);
        PlanNode node = translateExpression(join, typeProvider);
        Plan plan = new Plan(node, typeProvider, StatsAndCosts.empty());

        SubPlan fullFragmentedPlan = getFullFragmentedPlan(plan);

        inTransaction(session -> runTestIterativePlanFragmenter(node, plan, fullFragmentedPlan, session));
    }

    private Void runTestIterativePlanFragmenter(PlanNode node, Plan plan, SubPlan fullFragmentedPlan, Session session)
    {
        TestingFragmentTracker testingFragmentTracker = new TestingFragmentTracker();
        IterativePlanFragmenter iterativePlanFragmenter = new IterativePlanFragmenter(
                plan,
                testingFragmentTracker::isFragmentFinished,
                metadata,
                new PlanChecker(new FeaturesConfig()),
                new SqlParser(),
                new PlanNodeIdAllocator(),
                nodePartitioningManager,
                new QueryManagerConfig(),
                session,
                WarningCollector.NOOP,
                false);

        PlanAndFragments nextPlanAndFragments = getNextPlanAndFragments(iterativePlanFragmenter, node);
        assertTrue(nextPlanAndFragments.getRemainingPlan().isPresent());
        assertEquals(nextPlanAndFragments.getReadyFragments().size(), 2);

        // nothing new is ready for execution, you are returned the same plan you sent in
        // and no fragments.
        PlanAndFragments previousPlanAndFragments = nextPlanAndFragments;
        nextPlanAndFragments = getNextPlanAndFragments(iterativePlanFragmenter, previousPlanAndFragments.getRemainingPlan().get());
        assertTrue(nextPlanAndFragments.getReadyFragments().isEmpty());
        assertTrue(nextPlanAndFragments.getRemainingPlan().isPresent());
        assertEquals(previousPlanAndFragments.getRemainingPlan().get(), nextPlanAndFragments.getRemainingPlan().get());

        // finish one fragment
        // still nothing is ready for execution as the join stage has two dependencies
        previousPlanAndFragments = nextPlanAndFragments;
        testingFragmentTracker.addFinishedFragment(new PlanFragmentId(1));

        nextPlanAndFragments = getNextPlanAndFragments(iterativePlanFragmenter, previousPlanAndFragments.getRemainingPlan().get());
        assertEquals(previousPlanAndFragments, nextPlanAndFragments);

        testingFragmentTracker.addFinishedFragment(new PlanFragmentId(2));
        previousPlanAndFragments = nextPlanAndFragments;
        nextPlanAndFragments = getNextPlanAndFragments(iterativePlanFragmenter, previousPlanAndFragments.getRemainingPlan().get());

        // when the root fragment is ready to execute, there should be no remaining plan left
        assertFalse(nextPlanAndFragments.getRemainingPlan().isPresent());
        assertEquals(nextPlanAndFragments.getReadyFragments().size(), 1);

        assertSubPlansEquivalent(nextPlanAndFragments.getReadyFragments().get(0), fullFragmentedPlan);
        return null;
    }

    private void assertSubPlansEquivalent(SubPlan subPlan1, SubPlan subPlan2)
    {
        assertEquals(toCanonicalTestFragment(subPlan1.getFragment()), toCanonicalTestFragment(subPlan2.getFragment()));
        Set<CanonicalTestFragment> subPlan1Children = subPlan1.getChildren().stream()
                .map(child -> toCanonicalTestFragment(child.getFragment()))
                .collect(toImmutableSet());
        Set<CanonicalTestFragment> subPlan2Children = subPlan2.getChildren().stream()
                .map(child -> toCanonicalTestFragment(child.getFragment()))
                .collect(toImmutableSet());

        assertEquals(subPlan1Children, subPlan2Children);
    }

    private TableScanNode tableScan(String id, String... symbols)
    {
        List<VariableReferenceExpression> variables = Arrays.stream(symbols)
                .map(symbol -> new VariableReferenceExpression(Optional.empty(), symbol, BIGINT))
                .collect(toImmutableList());
        return tableScan(id, variables);
    }

    private TableScanNode tableScan(String id, List<VariableReferenceExpression> variables)
    {
        ImmutableMap.Builder<VariableReferenceExpression, ColumnHandle> assignments = ImmutableMap.builder();

        for (VariableReferenceExpression variable : variables) {
            assignments.put(variable, new TpchColumnHandle("orderkey", BIGINT));
        }

        TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0);
        return new TableScanNode(
                Optional.empty(),
                new PlanNodeId(id),
                new TableHandle(
                        new ConnectorId("tpch"),
                        tableHandle,
                        TpchTransactionHandle.INSTANCE,
                        Optional.of(new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))),
                variables,
                assignments.build(),
                TupleDomain.all(),
                TupleDomain.all());
    }

    private PlanNode project(String id, PlanNode source, VariableReferenceExpression variable, Expression expression)
    {
        return new ProjectNode(
                new PlanNodeId(id),
                source,
                assignment(variable, expression));
    }

    private AggregationNode aggregation(String id, PlanNode source)
    {
        AggregationNode.Aggregation aggregation = count(metadata.getFunctionAndTypeManager());

        return new AggregationNode(
                Optional.empty(),
                new PlanNodeId(id),
                source,
                ImmutableMap.of(new VariableReferenceExpression(Optional.empty(), "count", BIGINT), aggregation),
                singleGroupingSet(source.getOutputVariables()),
                ImmutableList.of(),
                AggregationNode.Step.FINAL,
                Optional.empty(),
                Optional.empty());
    }

    /**
     * EquiJoinClause is created from symbols in form of:
     * symbol[0] = symbol[1] AND symbol[2] = symbol[3] AND ...
     */
    private JoinNode join(String planNodeId, PlanNode left, PlanNode right, JoinNode.DistributionType distributionType, String... symbols)
    {
        checkArgument(symbols.length % 2 == 0);
        ImmutableList.Builder<JoinNode.EquiJoinClause> criteria = ImmutableList.builder();

        for (int i = 0; i < symbols.length; i += 2) {
            criteria.add(new JoinNode.EquiJoinClause(new VariableReferenceExpression(Optional.empty(), symbols[i], BIGINT), new VariableReferenceExpression(Optional.empty(), symbols[i + 1], BIGINT)));
        }

        return new JoinNode(
                Optional.empty(),
                new PlanNodeId(planNodeId),
                JoinNode.Type.INNER,
                left,
                right,
                criteria.build(),
                ImmutableList.<VariableReferenceExpression>builder()
                        .addAll(left.getOutputVariables())
                        .addAll(right.getOutputVariables())
                        .build(),
                Optional.empty(),
                Optional.empty(),
                Optional.empty(),
                Optional.of(distributionType),
                ImmutableMap.of());
    }

    private PlanNode translateExpression(PlanNode planNode, TypeProvider typeProvider)
    {
        StatsCalculator statsCalculator = (node, sourceStats, lookup, session, types) -> PlanNodeStatsEstimate.unknown();
        CostCalculator costCalculatorUsingExchanges = new CostCalculatorUsingExchanges(new TaskCountEstimator(() -> 1));
        IterativeOptimizer optimizer = new IterativeOptimizer(new RuleStatsRecorder(), statsCalculator, costCalculatorUsingExchanges, new TranslateExpressions(metadata, new SqlParser()).rules());
        return optimizer.optimize(planNode, session, typeProvider, new PlanVariableAllocator(typeProvider.allVariables()), new PlanNodeIdAllocator(), WarningCollector.NOOP);
    }

    private SubPlan getFullFragmentedPlan(Plan plan)
    {
        return inTransaction(session -> planFragmenter.createSubPlans(session, plan, false, new PlanNodeIdAllocator(), WarningCollector.NOOP));
    }

    private PlanAndFragments getNextPlanAndFragments(IterativePlanFragmenter iterativePlanFragmenter, PlanNode node)
    {
        return iterativePlanFragmenter.createReadySubPlans(node);
    }

    private <T> T inTransaction(Function<Session, T> transactionSessionConsumer)
    {
        return transaction(transactionManager, new AllowAllAccessControl())
                .singleStatement()
                .execute(session, session -> {
                    // metadata.getCatalogHandle() registers the catalog for the transaction
                    session.getCatalog().ifPresent(catalog -> metadata.getCatalogHandle(session, catalog));
                    return transactionSessionConsumer.apply(session);
                });
    }

    private static class TestingFragmentTracker
    {
        private final Set<PlanFragmentId> finishedFragments = new HashSet<>();

        public void addFinishedFragment(PlanFragmentId id)
        {
            finishedFragments.add(id);
        }

        public boolean isFragmentFinished(PlanFragmentId id)
        {
            return finishedFragments.contains(id);
        }
    }

    static class CanonicalTestFragment
    {
        // it's tricky to compare plans between fragments
        // because the remotes sources will be different
        // just make sure they have the same root node
        // for sanity checking
        private final Class<PlanNode> clazz;
        private final Set<VariableReferenceExpression> variables;
        private final PartitioningHandle partitioning;
        private final List<PlanNodeId> tableScanSchedulingOrder;
        private final List<Type> types;

        // can't compare the remoteSourceNodes themselves
        // because fragment numbering can differ,
        // so just ensure that there are the same number
        private final int numberOfRemoteSourceNodes;
        private final PartitioningScheme partitioningScheme;
        private final StageExecutionDescriptor stageExecutionDescriptor;
        private final boolean outputTableWriterFragment;
        private final StatsAndCosts statsAndCosts;

        public CanonicalTestFragment(
                Class<PlanNode> clazz,
                Set<VariableReferenceExpression> variables,
                PartitioningHandle partitioning,
                List<PlanNodeId> tableScanSchedulingOrder,
                List<Type> types,
                int numberOfRemoteSourceNodes,
                PartitioningScheme partitioningScheme,
                StageExecutionDescriptor stageExecutionDescriptor,
                boolean outputTableWriterFragment,
                StatsAndCosts statsAndCosts)
        {
            this.clazz = requireNonNull(clazz, "clazz is null");
            this.variables = ImmutableSet.copyOf(requireNonNull(variables, "variables is null"));
            this.partitioning = requireNonNull(partitioning, "partitioning is null");
            this.tableScanSchedulingOrder = ImmutableList.copyOf(requireNonNull(tableScanSchedulingOrder, "tableScanSchedulingOrder is null"));
            this.types = ImmutableList.copyOf(requireNonNull(types, "types is null"));
            this.numberOfRemoteSourceNodes = numberOfRemoteSourceNodes;
            this.partitioningScheme = requireNonNull(partitioningScheme, "partitioningScheme is null");
            this.stageExecutionDescriptor = requireNonNull(stageExecutionDescriptor, "stageExecutionDescriptor is null");
            this.outputTableWriterFragment = outputTableWriterFragment;
            this.statsAndCosts = requireNonNull(statsAndCosts, "statsAndCosts is null");
        }

        public static CanonicalTestFragment toCanonicalTestFragment(PlanFragment planFragment)
        {
            return new CanonicalTestFragment(
                    (Class<PlanNode>) planFragment.getRoot().getClass(),
                    planFragment.getVariables(),
                    planFragment.getPartitioning(),
                    planFragment.getTableScanSchedulingOrder(),
                    planFragment.getTypes(),
                    planFragment.getRemoteSourceNodes().size(),
                    planFragment.getPartitioningScheme(),
                    planFragment.getStageExecutionDescriptor(),
                    planFragment.isOutputTableWriterFragment(),
                    planFragment.getStatsAndCosts());
        }

        @Override
        public boolean equals(Object o)
        {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            CanonicalTestFragment that = (CanonicalTestFragment) o;
            return numberOfRemoteSourceNodes == that.numberOfRemoteSourceNodes &&
                    outputTableWriterFragment == that.outputTableWriterFragment &&
                    clazz.equals(that.clazz) &&
                    variables.equals(that.variables) &&
                    partitioning.equals(that.partitioning) &&
                    tableScanSchedulingOrder.equals(that.tableScanSchedulingOrder) &&
                    types.equals(that.types) &&
                    partitioningScheme.equals(that.partitioningScheme) &&
                    stageExecutionDescriptor.equals(that.stageExecutionDescriptor) &&
                    statsAndCosts.equals(that.statsAndCosts);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(
                    clazz,
                    variables,
                    partitioning,
                    tableScanSchedulingOrder,
                    types,
                    numberOfRemoteSourceNodes,
                    partitioningScheme,
                    stageExecutionDescriptor,
                    outputTableWriterFragment,
                    statsAndCosts);
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("clazz", clazz)
                    .add("variables", variables)
                    .add("partitioning", partitioning)
                    .add("tableScanSchedulingOrder", tableScanSchedulingOrder)
                    .add("types", types)
                    .add("numberOfRemoteSourceNodes", numberOfRemoteSourceNodes)
                    .add("partitioningScheme", partitioningScheme)
                    .add("stageExecutionDescriptor", stageExecutionDescriptor)
                    .add("outputTableWriterFragment", outputTableWriterFragment)
                    .add("statsAndCosts", statsAndCosts)
                    .toString();
        }
    }
}


text:
require 'gosu_android/graphics/bitmap'
require 'gosu_android/graphics/color'
require 'gosu_android/graphics/graphicsBase'
require 'gosu_android/math'

module Gosu

  class Image

    def initialize(*args)
      case args.length
      #Argument is ImageData
      when 1
        initialize_1 args[0]
      when 2
        if args[1].class == Bitmap
          initialize_3_bitmap(args[0], args[1])
        else
          initialize_3_file_name(args[0], args[1])
        end
      when 3
        if args[1].class == Bitmap
          initialize_3_bitmap(args[0], args[1], args[2])
        else
          initialize_3_file_name(args[0], args[1], args[2])
        end
      when 6
        if args[1].class == Bitmap
          initialize_7_bitmap(args[0], args[1], args[2], args[3], args[4], args[5])
        else
          initialize_7_file_name(args[0], args[1], args[2], args[3], args[4], args[5])
        end
      when 7
        if args[1].class == Bitmap
          initialize_7_bitmap(args[0], args[1], args[2], args[3], args[4], args[5], args[6])
        else
          initialize_7_file_name(args[0], args[1], args[2], args[3], args[4], args[5], args[6])
        end
      else
        raise ArgumentError
      end
    end

    #Private initialize methods
    private
    def initialize_1 data
      @data = data
    end

    def initialize_3_bitmap(window, source, tileable = false)
      initialize_7_bitmap(window, source, 0, 0, source.width, source.height, tileable)
    end

    def initialize_3_file_name(window, file_name, tileable = false)
      bmp = Gosu::load_image_file(window, file_name)
      initialize_3_bitmap(window, bmp, tileable)
    end

    def initialize_7_file_name(window, file_name, src_x, src_y, src_width, src_height,
              tileable = false)
      bmp = Gosu::load_image_file(window, file_name)
      initialize_7_bitmap(window, bmp, src_x, src_y, src_width, src_height, tileable)
    end

    def initialize_7_bitmap(window, source, src_x, src_y, src_width, src_height,
              tileable = false)
      if tileable
        @data = window.create_image(source, src_x, src_y, src_width, src_height, BF_TILEABLE)
      else
        @data = window.create_image(source, src_x, src_y, src_width, src_height, BF_SMOOTH)
      end
      ObjectSpace.define_finalizer(self, Proc.new{@data.finalize})
    end

    public
    def width
      @data.width
    end

    def height
      @data.height
    end

    def draw(x, y, z, factor_x = 1, factor_y = 1, c = Color::WHITE, mode = :default)
      x2 = x + width*factor_x
      y2 = y + height*factor_y
      @data.draw(x, y, c, x2, y, c, x, y2, c, x2, y2, c, z, AM_MODES[mode])
    end

    def draw_rot(x, y, z, angle, center_x = 0.5, center_y = 0.5, factor_x = 1.0,
      factor_y = 1.0, c = Color::WHITE, mode = :default)

      size_y = width  * factor_x
      size_y = height * factor_y
      offs_x = Gosu::offset_x(angle, 1)
      offs_y = Gosu::offset_y(angle, 1)

      #Offset to the centers of the original Image's edges when it is rotated
      #by <angle> degrees.
      dist_to_left_x   = +offs_y * size_y * center_x
      dist_to_left_y   = -offs_x * size_y * center_x
      dist_to_right_x  = -offs_y * size_y * (1 - center_x)
      dist_to_right_y  = +offs_x * size_y * (1 - center_x)
      dist_to_top_x    = +offs_x * size_y * center_y
      dist_to_top_y    = +offs_y * size_y * center_y
      dist_to_bottom_x = -offs_x * size_y * (1 - center_y)
      dist_to_bottom_y = -offs_y * size_y * (1 - center_y)

      @data.draw(x + dist_to_left_x  + dist_to_top_x,
        y + dist_to_left_y  + dist_to_top_y, c,
        x + dist_to_right_x + dist_to_top_x,
        y + dist_to_right_y + dist_to_top_y, c,
        x + dist_to_left_x  + dist_to_bottom_x,
        y + dist_to_left_y  + dist_to_bottom_y, c,
        x + dist_to_right_x + dist_to_bottom_x,
        y + dist_to_right_y + dist_to_bottom_y,
        c, z, AM_MODES[mode])
    end

    def self.load_tiles(window, bmp, tile_width, tile_height, tileable)
      images = []

      #If bmp is a file path
      if bmp.class == String or bmp.class == Fixnum
        bmp = Gosu::load_image_file(window, bmp)
      end

      if (tile_width > 0)
        tiles_x = bmp.width / tile_width
      else
        tiles_x = -tile_width
        tile_width = bmp.width / tiles_x
      end

      if (tile_height > 0)
        tiles_y = bmp.height / tile_height
      else
        tiles_y = -tile_height
        tile_height = bmp.height / tiles_y
      end

      tiles_y.times do |y|
        tiles_x.times do |x|
          images.push Image.new(window, bmp, x * tile_width, y * tile_height, tile_width, tile_height, tileable)
        end
      end
      images
    end

  end

end


text:
package org.test.shop.model.dao.view;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.test.shop.config.settings.NamedFilter;
import org.test.shop.controller.data.types.ScrollableSettings;
import org.test.shop.model.domain.SObject;
import org.test.shop.model.domain.entity.view.TmImageView;
import org.test.shop.util.DaoUtil;
import org.test.shop.util.data.types.DateCompare;
import org.test.shop.util.data.types.FindByDateExample;
import org.test.shop.util.data.types.FindByExample;
import org.test.shop.util.data.types.TotalQuery;

@Repository
public class TmImageViewDao {

	@PersistenceContext
	private EntityManager em;
	private String selectClause = "SELECT tmi0 FROM TmImageView tmi0";
	private String updatePopularityClause = "UPDATE %s SET popularity = :popularity WHERE id = :id";
	private String shortName = "tmi0";
	private String className = "TmImageView";
	private String tableName = "tm_image_view";

	public TmImageView create(TmImageView tmimageview) {
		em.persist(tmimageview);
		return tmimageview;
	}

	public TmImageView update(TmImageView tmimageview) {
		return em.merge(tmimageview);
	}

	public void popularityByKey(Object key) {
		TmImageView tmimageview = findById(key, false);

		if(tmimageview != null){
			if (SObject.class.isAssignableFrom(TmImageView.class)) {
				if (tmimageview.getPopularity() == null) {
					tmimageview.setPopularity(-1);
				}
				tmimageview.setPopularity(tmimageview.getPopularity() + 1);
				try {
					em.createNativeQuery(String.format(updatePopularityClause, tableName), TmImageView.class)
							.setParameter("popularity", tmimageview.getPopularity())
							.setParameter("id", key)
							.executeUpdate();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	public void popularity(TmImageView item) {
		TmImageView tmimageview = null;
		if(item != null){
			tmimageview = findById(item.getId(), false);
		}

		if(tmimageview != null){
			if (SObject.class.isAssignableFrom(TmImageView.class)) {
				if (tmimageview.getPopularity() == null) {
					tmimageview.setPopularity(-1);
				}
				tmimageview.setPopularity(tmimageview.getPopularity() + 1);

				try {
					em.createNativeQuery(String.format(updatePopularityClause, tableName), TmImageView.class)
							.setParameter("popularity", tmimageview.getPopularity())
							.setParameter("id", item.getId())
							.executeUpdate();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	public Integer todayNumber(ScrollableSettings settings) throws Exception {
		String today = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
		Query query = em.createNativeQuery(
				String.format(
						"SELECT count(*) from %s %s WHERE %s.firmid = %s and CAST(%s.createon as DATE) = CAST('%s' as DATE)"
						, tableName, shortName, shortName, settings.getSasUser().getUser().getFirmid(), shortName, today
				)
		);

		return ((BigInteger) query.getSingleResult()).intValue();
	}

	public Integer total(ScrollableSettings settings) throws Exception {
		TotalQuery totalQuery = DaoUtil.total(settings, TmImageView.class, em);

		return ((BigInteger) totalQuery.getQuery().getSingleResult()).intValue();
	}

	public List<TmImageView> namedFilter(ScrollableSettings settings) {
		List<TmImageView> tmimageviews = new ArrayList<TmImageView>();

		try {
			tmimageviews = DaoUtil.sasQueryByNamedFilter(NamedFilter.Items.byName(settings.getNamedfilter(), TmImageView.class), settings,
				TmImageView.class, em).getResultList();
		} catch (Exception e){
			e.printStackTrace();
		}

		return tmimageviews;
	}

	@SuppressWarnings("unchecked")
	public List<TmImageView> search(ScrollableSettings settings){
		if(settings.getFilter() == null || settings.getFilter().replaceAll("\\s+", "").length() == 0){
			return new ArrayList<TmImageView>();
		}

		FindByExample findByExample = DaoUtil.search(new TmImageView(), settings.getFilter(), TmImageView.class, em);
		Query query = null;

		if (findByExample.getIsNativeQuery()) {
			String queryString = DaoUtil.sasQueryRaw(findByExample.getSelectClause(), settings, TmImageView.class, em);
			query = em.createNativeQuery(queryString.replace("SELECT " + shortName, "SELECT *").replace(className, DaoUtil.readTableName(TmImageView.class)), TmImageView.class);

			if(queryString.contains(":firmid")){
				query.setParameter("firmid", settings.getSasUser().getUser().getFirmid());
			}
			else if(queryString.contains(":firm")){
				query.setParameter("firm", settings.getSasUser().getUser().getFirmid());
			}

		}
		else {
			query = DaoUtil.sasQuery(findByExample.getSelectClause(), settings, TmImageView.class, em);
		}

		query.setParameter("filter", findByExample.getFilter());
		if(findByExample.getSelectClause().contains("filterForInteger")){
			query.setParameter("filterForInteger", findByExample.getFilterForInteger());
		}

		return query.setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<TmImageView> findByExample(TmImageView example, String delimitter, ScrollableSettings settings) {
		FindByExample findByExample = DaoUtil.findByExampleQueryRaw(example,
				TmImageView.class, em, " " + delimitter + " ");
		Query query = DaoUtil.sasQuery(findByExample.getSelectClause(),
				settings, TmImageView.class, em);
		for (String key : findByExample.getValues().keySet()) {
			query.setParameter(key, findByExample.getValues().get(key));
		}

		return query.setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<TmImageView> findByExample2(TmImageView example, DateCompare type) {
		FindByDateExample findByExample = DaoUtil.findByExample2(example, TmImageView.class, em, type).init();
		return findByExample.getQuery().setMaxResults(100).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<TmImageView> findAll(ScrollableSettings settings) {
		List<TmImageView> tmimageviews = DaoUtil.sasQuery(selectClause, settings,
				TmImageView.class, em).getResultList();

		if (settings.getList().size() > 0) {
			for (TmImageView item : tmimageviews) {
				item.customInit(item, settings.getList());
			}
		}

		if (settings.getInitLists() || settings.getInitDicts()) {
			for (TmImageView item : tmimageviews) {
				if (settings.getInitDicts()) {
					item.initDicts();
				}
				if (settings.getInitLists()) {
					item.initList();
				}
			}
		}

		return tmimageviews;
	}

	@SuppressWarnings("unchecked")
	public List<TmImageView> findAllScrollable(ScrollableSettings settings) {
		List<TmImageView> tmimageviews = DaoUtil
				.sasQuery(selectClause, settings, TmImageView.class, em)
				.setFirstResult(
						(settings.getPageNumber() - 1) * settings.getPageSize())
				.setMaxResults(settings.getPageSize()).getResultList();

		if (settings.getList().size() > 0) {
			for (TmImageView item : tmimageviews) {
				item.customInit(item, settings.getList());
			}
		}

		if (settings.getInitLists() || settings.getInitDicts()) {
			for (TmImageView item : tmimageviews) {
				if (settings.getInitDicts()) {
					item.initDicts();
				}
				if (settings.getInitLists()) {
					item.initList();
				}
			}
		}

		return tmimageviews;
	}

	public TmImageView findById(Object key, Boolean initAll) {
		TmImageView item = em.find(TmImageView.class, key);

		if(item != null){
			if (initAll) {
				item.init();
			}
		}

		return item;
	}

	public TmImageView findById(ScrollableSettings settings) {
		TmImageView item = em.find(TmImageView.class, settings.getId());

		if(item != null){
			if (settings.getList().size() > 0) {
				item.customInit(item, settings.getList());
			}

			if (settings.getInitDicts()) {
				item.initDicts();
			}

			if (settings.getInitLists()) {
				item.initList();
			}

			try {
				item.specialInit();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return item;
	}

	public Boolean delete(Object id) {
		try {
			em.remove(em.getReference(TmImageView.class, id));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

}


text:
require "spec_helper"

describe "Users" do

  subject { page }

  let!(:user){ FactoryGirl.create(:user, :github => "http://www.github.com/foobar", :about => "I rock") }
  let!(:other_user) { FactoryGirl.create(:user, email: "other_user@example.com") }
  let!(:project) { FactoryGirl.create(:content_bucket) }

  describe "Profile Page (#show)" do

    before do
      user.content_buckets << project
      sign_in(user)
    end

    context "for current user" do
      before do
        visit user_path(user)
      end

      it "should show the user's name" do
        page.source.should have_selector("h2", :text => user.username)
      end
      it "should show the github profile link" do
        page.source.should have_css( "a[href='#{user.github}']" )
      end
      it "should show the about text" do
        page.source.should have_selector("p", :text => user.about)
      end
      it "should show the edit button" do
        page.source.should have_selector("button", :text => "Edit")
      end

      context "without a completed lesson" do

        it "should not list lesson completions" do
          page.source.should_not have_selector("h3", :text => "Completed Lessons")
        end
      end

      context "with a completed lesson" do

        before do
          user.completed_lessons << FactoryGirl.create( :lesson )
          visit user_path( user )
        end

        it "should list the lessons the user has completed" do
          # save_and_open_page
          page.source.should have_selector("h3", :text => "Completed Lessons")
        end

      end

    end

    context "for another user" do
      before { visit user_path(other_user) }

      it "should show that user's name" do
        page.source.should have_selector("h2", :text => other_user.username)
      end
      it "should not have an edit button" do
        page.source.should_not have_selector("button", :text => "Edit")
      end
    end
  end

  describe "Edit Profile Page (#edit)" do

    before do
      sign_in(user)
    end

    context "for not current user" do
      before do
        visit edit_user_path(other_user)
      end

      it "should not allow that edit page to display" do
        current_path.should_not == edit_user_path(other_user)
      end

      it "should redirect to show page for that user" do
        current_path.should == user_path(other_user)
      end
    end

    context "for logged in user" do
      before do
        visit edit_user_path(user)
      end

      it "should allow the edit page to display" do
        current_path.should == edit_user_path(user)
      end

      context "with new data entered" do
        before do
          fill_in "user_facebook", :with => "new facebook"
          fill_in "user_about", :with => "New about me"
          click_button "Update"
        end

        it "should go to show page" do
          current_path.should == user_path(user)
        end
        it "should show facebook changes" do
          user.reload
          page.source.should have_css( "a[href='https://www.facebook.com/#{user.facebook}']" )
        end
        it "should show about changes" do
          page.source.should have_selector("p", :text => "New about me")
        end
      end
    end
  end

  describe "Users index page" do

    context "after signing in" do
      before do
        sign_in(user)
        visit users_path
      end

      it { should have_selector("h2", :text => "Students") }
      it { should have_link(user.username, :href=>user_path(user)) }
      it { should have_selector("img")}

      # Obsolete after changing the algorithm to favor instead
      # students who have most recently completed a lesson
      # Create these specs!
      it "should show the student with the most recently completed lesson first"
      # context "after signing in another user" do

      #   before do
      #     sign_out(user)
      #     sign_in(other_user)
      #     visit users_path
      #   end

      #   it "should show most recently signed in user at top of list" do
      #     users = page.all("div#students-list div.student-info")
      #     users[0].should have_content(other_user.username)
      #     users[1].should have_content(user.username)
      #   end

      #   it "should NOT show most recently signed in user NOT at top of list" do
      #     users = page.all("div#students-list div.student-info")
      #     users[1].should_not have_content(other_user.username)
      #     users[0].should_not have_content(user.username)
      #   end
      # end

    end

    context "list users" do
      before do
        sign_in(user)
        visit users_path
      end

      # Check to see if we get any listing at all
      it { should have_selector('div.student-info') }

    end
  end
end


text:
<?
	if($this->getDoShowHeaders()) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title><?= $this->getPageTitle() ?></title>
		<meta name="description" content="<?= $this->getMetaDescription() ?>">
		<meta name="keywords" content="<?= implode(",",$this->getKeywords()) ?>">
		<meta name="ROBOTS" content="<?= implode(",",$this->getRobotsRules()) ?>">
		<?= $this->getCSS() ?>
		<?= $this->getJavascript() ?>
	</head>
	<body>
<?
		ComponentFactory::getComponent("mainbody",$this)->render();
	}
	echo $this->getOutput();
	if($this->getDoShowHeaders()) {
?>
	</body>
<?
	}
?>


text:
using ModuleInject.Injection;
using Xunit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test.ModuleInject.Injection
{

	public class SingleInstanceInstantiationStrategyTest
	{
		private interface ITestComponent
		{
		}

		private class TestComponent : ITestComponent
		{
		}

		[Fact]
		public void Instance_ReturnsAlwaysSameInstance()
		{
			var singelton = new SingleInstanceInstantiationStrategy<ITestComponent>();

			var instance1 = singelton.GetInstance(() => new TestComponent());
			var instance2 = singelton.GetInstance(() => new TestComponent());

			Assert.NotNull(instance1);
			Assert.Same(instance1, instance2);
		}
	}
}


text:
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Displays a page as a modal dialog with inset appearance and overlay background
//>>label: Dialogs
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.dialog.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.navigation" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

$.widget( "mobile.dialog", $.mobile.widget, {
	options: {
		closeBtn: "left",
		closeBtnText: "Close",
		overlayTheme: "a",
		corners: true,
		initSelector: ":jqmData(role='dialog')"
	},

	// Override the theme set by the page plugin on pageshow
	_handlePageBeforeShow: function() {
		this._isCloseable = true;
		if ( this.options.overlayTheme ) {
			this.element
				.page( "removeContainerBackground" )
				.page( "setContainerBackground", this.options.overlayTheme );
		}
	},

	_create: function() {
		var $el = this.element,
			cornerClass = !!this.options.corners ? " ui-corner-all" : "",
			dialogWrap = $( "
", {
					"role" : "dialog",
					"class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass
				});

		$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );

		// Class the markup for dialog styling
		// Set aria role
		$el.wrapInner( dialogWrap );

		/* bind events
			- clicks and submits should use the closing transition that the dialog opened with
				unless a data-transition is specified on the link/form
			- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
		*/
		$el.bind( "vclick submit", function( event ) {
			var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
				active;

			if ( $target.length && !$target.jqmData( "transition" ) ) {

				active = $.mobile.urlHistory.getActive() || {};

				$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
					.attr( "data-" + $.mobile.ns + "direction", "reverse" );
			}
		});

		this._on( $el, {
			pagebeforeshow: "_handlePageBeforeShow"
		});

		$.extend( this, {
			_createComplete: false
		});

		this._setCloseBtn( this.options.closeBtn );
	},

	_setCorners: function( value ) {
		this.element.children().toggleClass( "ui-corner-all", value );
	},

	_setOverlayTheme: function( value ) {
		this.element
			.removeClass( "ui-overlay-" + this.options.overlayTheme )
			.addClass( "ui-overlay-" + value );
		if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) {
			this.options.overlayTheme = value;
			this._handlePageBeforeShow();
		}
	},

	_setCloseBtnText: function( value ) {
		this.options.closeBtnText = value;
		this._setCloseBtn( this.options.closeBtn );
	},

	_setCloseBtn: function( value ) {
		var self = this, btn, location;

		if ( this._headerCloseButton ) {
			this._headerCloseButton.remove();
			this._headerCloseButton = null;
		}
		if ( value !== "none" ) {
			// Sanitize value
			location = ( value === "left" ? "left" : "right" );
			btn = $( ""+ this.options.closeBtnText + "" );
			this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn );
			if ( this._createComplete && $.fn.buttonMarkup ) {
				btn.buttonMarkup();
			}
			this._createComplete = true;

			// this must be an anonymous function so that select menu dialogs can replace
			// the close method. This is a change from previously just defining data-rel=back
			// on the button and letting nav handle it
			//
			// Use click rather than vclick in order to prevent the possibility of unintentionally
			// reopening the dialog if the dialog opening item was directly under the close button.
			btn.bind( "click", function() {
				self.close();
			});

			this._headerCloseButton = btn;
		}
	},

	_setOption: function( key, value ) {
		var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );

		if ( this[ setter ] !== undefined ) {
			this[ setter ]( value );
		}

		this._super( key, value );
	},

	// Close method goes back in history
	close: function() {
		var idx, dst, hist = $.mobile.navigate.history;

		if ( this._isCloseable ) {
			this._isCloseable = false;
			// If the hash listening is enabled and there is at least one preceding history
			// entry it's ok to go back. Initial pages with the dialog hash state are an example
			// where the stack check is necessary
			if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
				$.mobile.back();
			} else {
				idx = Math.max( 0, hist.activeIndex - 1 );
				dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
				hist.previousIndex = hist.activeIndex;
				hist.activeIndex = idx;
				if ( !$.mobile.path.isPath( dst ) ) {
					dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
				}

				$.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } );
			}
		}
	}
});

//auto self-init widgets
$.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
	$.mobile.dialog.prototype.enhance( this );
});

})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");


text:
from .requester import Requester
from lib.models.collection import Collection
from lib.models.widget import Widget
from .collectionService import CollectionService
from .widgetService import WidgetService

class App(object):

    def __init__(self, email, password, organizationId):
        self.requester = Requester(email, password, organizationId)
        self.widgetService = WidgetService(self.requester)
        self.collectionService = CollectionService(self.requester, self.widgetService)

    def createWeeklyBoard(self, collection_name):
        collectionId = self.collectionService.getCollectionIdFromName(collection_name)
        collection = self.collectionService.getCollection(collectionId)
        nextBoardName = collection.getNextDailyGoalsName()
        self.widgetService.addWeeklyBoard(collection, nextBoardName)
        self.success = True


text:
package com.alibaba.otter.canal.client;

import java.net.InetSocketAddress;
import java.util.List;

import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;

public class SimpleCanalClientExample {

    public static void main(String args[]) {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
                                                                                11111), "example", "", "");
        int batchSize = 1000;
        int emptyCount = 0;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            int totalEmtryCount = 120;
            while (emptyCount < totalEmtryCount) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    emptyCount++;
                    System.out.println("empty count : " + emptyCount);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    emptyCount = 0;
                    // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
                    printEntry(message.getEntries());
                }

                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }

            System.out.println("empty too many times, exit");
        } finally {
            connector.disconnect();
        }
    }

    private static void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }

            RowChange rowChage = null;
            try {
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                                           e);
            }

            EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================> binlog[%s:%s] , name[%s,%s] , eventType : %s",
                                             entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                                             entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                                             eventType));

            for (RowData rowData : rowChage.getRowDatasList()) {
                if (eventType == EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                } else if (eventType == EventType.INSERT) {
                    printColumn(rowData.getAfterColumnsList());
                } else {
                    System.out.println("-------> before");
                    printColumn(rowData.getBeforeColumnsList());
                    System.out.println("-------> after");
                    printColumn(rowData.getAfterColumnsList());
                }
            }
        }
    }

    private static void printColumn(List<Column> columns) {
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }
}


text:
<?php

namespace Sonata\MediaBundle\Metadata;

use Sonata\MediaBundle\Model\MediaInterface;

interface MetadataBuilderInterface
{
    /**
     * Get metadata for media object.
     *
     * @param MediaInterface $media
     * @param string         $filename
     *
     * @return array
     */
    public function get(MediaInterface $media, $filename);
}


text:
/**
 *
 */
// const config = require('../config/db')
const Confirmed = require('../models/confirmed')
const Rejected = require('../models/rejected')
const Profile = require('../models/profile')
const ObjectID = require('mongodb').ObjectID

/**  Get the list of confirmed users for a user, by id from JWT token in Auth header of request
 *
 * @param {HTTP Request} req
 * @param {HTTP Response} res
 *
 * @return {HTTP Response}
 *
 */
function getConfirmedById (req, res) {
  const id = req.user._id
  if (id === undefined || id === null) {
    return res.status(400).json({status: false, msg: 'Malformed Request'})
  }
  Confirmed.getConfirmed(id)
  .then((result) => {
     return  res.status(200).json({success: true, profiles: result})
  })
  .catch((err) => {
    if (err) {
      console.log(err)
    }
  })
}

/**
 *
 * @param {HTTP Request} req
 * @param {HTTP Response} res
 *
 * @return {HTTP Response}
 *
 */
function createConfirmed (req, res) {
  const id = req.body._id
  if (id === undefined || id === null) {
    return res.status(400).json({status: false, msg: 'Malformed Request'})
  }
  const confirmer = {
    _id: new ObjectID(req.user._id),
    partnerId: id,
    status: true
  }

  const confirmee = {
    _id: new ObjectID(id),
    partnerId: req.user._id
  }

  Confirmed.createConfirm(confirmer._id, confirmer.partnerId)
  .then((result) => {
    if (result) {
      return Confirmed.createConfirm(confirmee._id, confirmee.partnerId)
    }
  })
  .then((result) => {
    if (result) {
      return res.status(201).json({status: true, msg: 'confirmer'})
    }
  })
  .catch((err, result) => {
    if (err) {
      console.log(err)
      Confirmed.remove(result.confirmer)
      Confirmed.remove(result.confirmee)
      return res.status(200).json({status: false, msg: 'Unable to Reject', res: result})
    }
  })
}

/**
 *
 * @param {HTTP Request} req
 * @param {HTTP Response} res
 *
 * @return {HTTP Response}
 *
 */
function updateConfirmed (req, res) {
  const id = req.body._id
  if (id === undefined) {
    return res.status(400).json({status: false, msg: 'Malformed Request'})
  }
  const confirmer = {
    _id: new ObjectID(req.user._id),
    partnerId: new ObjectID(id),
    status: true
  }
  const confirmee = {
    _id: new ObjectID(id),
    partnerId: new ObjectID(req.user._id)
  }

  Confirmed.deleteConfirm(confirmer._id, confirmer.partnerId)
  .then((result) => {
    return Confirmed.deleteConfirm(confirmee._id, confirmee.partnerId)
  })
  .then((result) => {
    if (result) {
      return res.status(200).json({status: true, msg: 'Removed confirmer'})
    }
    return res.status(200).json({
      status: false,
      msg: "Unable to Remove Relationship, does not exist",
      res: result
    })
  })
  .catch((err) => {
    if (err) {
      // Confirmed.remove(result.confirmer)
      // Confirmed.remove(result.confirmee)
      console.log(err)
      return res.status(200).json({status: false, msg: 'Unable to Remove confirmer'})
    }
  })
}

/**
 *
 * @param {HTTP Request} req
 * @param {HTTP Response} res
 *
 * @return {HTTP Response}
 *
 */
function rejectConfirmed (req, res) {
  const id = req.body._id
  if (id === undefined) {
    return res.status(400).json({status: false, msg: 'Malformed Request'})
  }
  const confirmer = {
    _id: new ObjectID(req.user._id),
    partnerId: new ObjectID(id),
    status: true
  }

  const confirmee = {
    _id: new ObjectID(id),
    partnerId: new ObjectID(req.user._id)
  }

  Rejected.createRejector(confirmer._id, confirmer.partnerId)
  .then((result) => {
    return Rejected.createRejectee(confirmee._id, confirmee.partnerId)
  })
  .then((result) => {
    return Confirmed.deleteConfirm(confirmer._id, confirmer.partnerId)
  })
  .then((result) => {
    return Confirmed.deleteConfirm(confirmee._id, confirmee.partnerId)
  })
  .then((result) => {
    if (result) {
    return res
      .status(200)
      .json({ status: true, msg: "Relationship Removed, Rejected User." })
    }
      return res
        .status(200)
        .json({
          status: false,
          msg: "Unable to Remove reject relationship",
          res: result
        })
  })
  .catch((err) => {
    if (err) {
      console.log(err)
      return res.status(200).json({status: false, msg: 'Unable to Remove confirmed relationship'})
    }
  })
}

/**
 *
 * @param {HTTP Request} req
 * @param {HTTP Response} res
 *
 * @return {HTTP Response}
 *
 */
function deleteConfirmed (req, res) {

}

/** Exporting Functions defined above
 *  Format: module.export.exportName = functionName
*/
module.exports.getConfirmed = getConfirmedById
module.exports.create = createConfirmed
module.exports.update = updateConfirmed
module.exports.reject = rejectConfirmed
module.exports.delete = deleteConfirmed


text:
package models

import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._

case class Tariff(pence: Int, desc: String)

object TariffJsonProtocol extends DefaultJsonProtocol {
  implicit val TariffFormat = jsonFormat2(Tariff)
}