text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.BaseFluent;
import io.kubernetes.client.fluent.Nested;

/** Generated */
@SuppressWarnings(value = "unchecked")
public class V1LifecycleHandlerFluentImpl<A extends V1LifecycleHandlerFluent<A>>
    extends BaseFluent<A> implements V1LifecycleHandlerFluent<A> {
  public V1LifecycleHandlerFluentImpl() {}

  public V1LifecycleHandlerFluentImpl(V1LifecycleHandler instance) {
    this.withExec(instance.getExec());

    this.withHttpGet(instance.getHttpGet());

    this.withTcpSocket(instance.getTcpSocket());
  }

  private V1ExecActionBuilder exec;
  private V1HTTPGetActionBuilder httpGet;
  private V1TCPSocketActionBuilder tcpSocket;

  /**
   * This method has been deprecated, please use method buildExec instead.
   *
   * @return The buildable object.
   */
  @Deprecated
  public V1ExecAction getExec() {
    return this.exec != null ? this.exec.build() : null;
  }

  public V1ExecAction buildExec() {
    return this.exec != null ? this.exec.build() : null;
  }

  public A withExec(V1ExecAction exec) {
    _visitables.get("exec").remove(this.exec);
    if (exec != null) {
      this.exec = new V1ExecActionBuilder(exec);
      _visitables.get("exec").add(this.exec);
    } else {
      this.exec = null;
      _visitables.get("exec").remove(this.exec);
    }
    return (A) this;
  }

  public Boolean hasExec() {
    return this.exec != null;
  }

  public V1LifecycleHandlerFluent.ExecNested<A> withNewExec() {
    return new V1LifecycleHandlerFluentImpl.ExecNestedImpl();
  }

  public V1LifecycleHandlerFluent.ExecNested<A> withNewExecLike(V1ExecAction item) {
    return new V1LifecycleHandlerFluentImpl.ExecNestedImpl(item);
  }

  public V1LifecycleHandlerFluent.ExecNested<A> editExec() {
    return withNewExecLike(getExec());
  }

  public V1LifecycleHandlerFluent.ExecNested<A> editOrNewExec() {
    return withNewExecLike(getExec() != null ? getExec() : new V1ExecActionBuilder().build());
  }

  public V1LifecycleHandlerFluent.ExecNested<A> editOrNewExecLike(V1ExecAction item) {
    return withNewExecLike(getExec() != null ? getExec() : item);
  }

  /**
   * This method has been deprecated, please use method buildHttpGet instead.
   *
   * @return The buildable object.
   */
  @Deprecated
  public V1HTTPGetAction getHttpGet() {
    return this.httpGet != null ? this.httpGet.build() : null;
  }

  public V1HTTPGetAction buildHttpGet() {
    return this.httpGet != null ? this.httpGet.build() : null;
  }

  public A withHttpGet(V1HTTPGetAction httpGet) {
    _visitables.get("httpGet").remove(this.httpGet);
    if (httpGet != null) {
      this.httpGet = new V1HTTPGetActionBuilder(httpGet);
      _visitables.get("httpGet").add(this.httpGet);
    } else {
      this.httpGet = null;
      _visitables.get("httpGet").remove(this.httpGet);
    }
    return (A) this;
  }

  public Boolean hasHttpGet() {
    return this.httpGet != null;
  }

  public V1LifecycleHandlerFluent.HttpGetNested<A> withNewHttpGet() {
    return new V1LifecycleHandlerFluentImpl.HttpGetNestedImpl();
  }

  public V1LifecycleHandlerFluent.HttpGetNested<A> withNewHttpGetLike(V1HTTPGetAction item) {
    return new V1LifecycleHandlerFluentImpl.HttpGetNestedImpl(item);
  }

  public V1LifecycleHandlerFluent.HttpGetNested<A> editHttpGet() {
    return withNewHttpGetLike(getHttpGet());
  }

  public V1LifecycleHandlerFluent.HttpGetNested<A> editOrNewHttpGet() {
    return withNewHttpGetLike(
        getHttpGet() != null ? getHttpGet() : new V1HTTPGetActionBuilder().build());
  }

  public V1LifecycleHandlerFluent.HttpGetNested<A> editOrNewHttpGetLike(V1HTTPGetAction item) {
    return withNewHttpGetLike(getHttpGet() != null ? getHttpGet() : item);
  }

  /**
   * This method has been deprecated, please use method buildTcpSocket instead.
   *
   * @return The buildable object.
   */
  @Deprecated
  public V1TCPSocketAction getTcpSocket() {
    return this.tcpSocket != null ? this.tcpSocket.build() : null;
  }

  public V1TCPSocketAction buildTcpSocket() {
    return this.tcpSocket != null ? this.tcpSocket.build() : null;
  }

  public A withTcpSocket(V1TCPSocketAction tcpSocket) {
    _visitables.get("tcpSocket").remove(this.tcpSocket);
    if (tcpSocket != null) {
      this.tcpSocket = new V1TCPSocketActionBuilder(tcpSocket);
      _visitables.get("tcpSocket").add(this.tcpSocket);
    } else {
      this.tcpSocket = null;
      _visitables.get("tcpSocket").remove(this.tcpSocket);
    }
    return (A) this;
  }

  public Boolean hasTcpSocket() {
    return this.tcpSocket != null;
  }

  public V1LifecycleHandlerFluent.TcpSocketNested<A> withNewTcpSocket() {
    return new V1LifecycleHandlerFluentImpl.TcpSocketNestedImpl();
  }

  public V1LifecycleHandlerFluent.TcpSocketNested<A> withNewTcpSocketLike(V1TCPSocketAction item) {
    return new V1LifecycleHandlerFluentImpl.TcpSocketNestedImpl(item);
  }

  public V1LifecycleHandlerFluent.TcpSocketNested<A> editTcpSocket() {
    return withNewTcpSocketLike(getTcpSocket());
  }

  public V1LifecycleHandlerFluent.TcpSocketNested<A> editOrNewTcpSocket() {
    return withNewTcpSocketLike(
        getTcpSocket() != null ? getTcpSocket() : new V1TCPSocketActionBuilder().build());
  }

  public V1LifecycleHandlerFluent.TcpSocketNested<A> editOrNewTcpSocketLike(
      V1TCPSocketAction item) {
    return withNewTcpSocketLike(getTcpSocket() != null ? getTcpSocket() : item);
  }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    V1LifecycleHandlerFluentImpl that = (V1LifecycleHandlerFluentImpl) o;
    if (exec != null ? !exec.equals(that.exec) : that.exec != null) return false;
    if (httpGet != null ? !httpGet.equals(that.httpGet) : that.httpGet != null) return false;
    if (tcpSocket != null ? !tcpSocket.equals(that.tcpSocket) : that.tcpSocket != null)
      return false;
    return true;
  }

  public int hashCode() {
    return java.util.Objects.hash(exec, httpGet, tcpSocket, super.hashCode());
  }

  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    if (exec != null) {
      sb.append("exec:");
      sb.append(exec + ",");
    }
    if (httpGet != null) {
      sb.append("httpGet:");
      sb.append(httpGet + ",");
    }
    if (tcpSocket != null) {
      sb.append("tcpSocket:");
      sb.append(tcpSocket);
    }
    sb.append("}");
    return sb.toString();
  }

  class ExecNestedImpl<N> extends V1ExecActionFluentImpl<V1LifecycleHandlerFluent.ExecNested<N>>
      implements V1LifecycleHandlerFluent.ExecNested<N>, Nested<N> {
    ExecNestedImpl(V1ExecAction item) {
      this.builder = new V1ExecActionBuilder(this, item);
    }

    ExecNestedImpl() {
      this.builder = new V1ExecActionBuilder(this);
    }

    V1ExecActionBuilder builder;

    public N and() {
      return (N) V1LifecycleHandlerFluentImpl.this.withExec(builder.build());
    }

    public N endExec() {
      return and();
    }
  }

  class HttpGetNestedImpl<N>
      extends V1HTTPGetActionFluentImpl<V1LifecycleHandlerFluent.HttpGetNested<N>>
      implements V1LifecycleHandlerFluent.HttpGetNested<N>, Nested<N> {
    HttpGetNestedImpl(V1HTTPGetAction item) {
      this.builder = new V1HTTPGetActionBuilder(this, item);
    }

    HttpGetNestedImpl() {
      this.builder = new V1HTTPGetActionBuilder(this);
    }

    V1HTTPGetActionBuilder builder;

    public N and() {
      return (N) V1LifecycleHandlerFluentImpl.this.withHttpGet(builder.build());
    }

    public N endHttpGet() {
      return and();
    }
  }

  class TcpSocketNestedImpl<N>
      extends V1TCPSocketActionFluentImpl<V1LifecycleHandlerFluent.TcpSocketNested<N>>
      implements V1LifecycleHandlerFluent.TcpSocketNested<N>, Nested<N> {
    TcpSocketNestedImpl(V1TCPSocketAction item) {
      this.builder = new V1TCPSocketActionBuilder(this, item);
    }

    TcpSocketNestedImpl() {
      this.builder = new V1TCPSocketActionBuilder(this);
    }

    V1TCPSocketActionBuilder builder;

    public N and() {
      return (N) V1LifecycleHandlerFluentImpl.this.withTcpSocket(builder.build());
    }

    public N endTcpSocket() {
      return and();
    }
  }
}


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='publish-o-matic',
    version="1.0",
    author='NHS England',
    author_email='',
    license="MIT",
    url='http://github.com/nhsengland/publish-o-matic/',
    description="A collections of scripts and tools to simplify publishing NHS England data",
    zip_safe=False,
    packages=find_packages(exclude=['ez_setup']),
    namespace_packages=['datasets', 'publish', 'publish.lib', 'publish.tools'],
    include_package_data=True,
    dependency_links=[
        "http://github.com/davidmiller/ffs/tarball/master#egg=ffs-0.0.8",
        "http://github.com/nhsengland/dc/tarball/master#egg=dc-0.0.1",
        "http://github.com/rossjones/dmswitch/tarball/master#egg=dmswitch-0.0.1"
    ],
    install_requires = [
        "awesome-slugify==1.6.1",
        "beautifulsoup4==4.3.2",
        "ckanapi==3.3",
        "cssselect==0.9.1",
        "html2text==2014.12.29",
        "lxml==3.4.1",
        "requests==2.5.1",
        "urlhelp==0.0.1",
        "dc==0.0.1",
        "ffs==0.0.8",
#        "dmswitch==0.0.1",
        "requests-cache==0.4.9",
        "html2text==2014.12.29",
        "boto==2.36.0"
    ],
    entry_points = {
        'console_scripts': [
            'crontool=publish.tools.crontool:main',
            'run_scraper=publish.tools.run_scraper:main',
            'unzipper=publish.tools.unzipper:main',
            'fix_urls=publish.tools.url_fixer:main'
        ],
        'scrapers': [
            'ascof=datasets.ascof:entrypoints',
            'prescribing=datasets.prescribing:entrypoints',
            'hqip=datasets.hqip:entrypoints',
            'ccgois=datasets.ccgois:entrypoints',
            #'hscic=datasets.hscic:entrypoints',
            'ods=datasets.ods:entrypoints',
            'nhsof=datasets.nhsof:entrypoints',
            'phof=datasets.phof:entrypoints',
            'qof=datasets.qof:entrypoints',
            'mhmds=datasets.mhmds:entrypoints',
            'nhse_stats=datasets.nhse_stats:entrypoints',
            'patient_survey=datasets.patient_survey:entrypoints',
            'practice_patients=datasets.practice_patients:entrypoints',
            'staff_survey=datasets.staff_survey:entrypoints',
        ]
    }
)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Opis\Colibri\Collectors;

/**
 * Collects dispatchers
 */
interface DispatcherCollectorInterface
{

    /**
     * Register a new dispatcher
     *
     * @param   string      $name       Dispatcher's name
     * @param   callable    $builder    A callback that will return an instance of \Opis\Routing\Dispatcher
     *
     * @return  \Opis\Colibri\DispatcherCollectorInterface  Self reference
     */
    public function register($name, $builder);
}


text:
function [table, measured_points] = build_table()
    table = readtable('point_database.csv', 'ReadRowNames', true);
    table = sortrows(table, 'RowNames');
    table.Properties.VariableUnits = {'', '', '', ''};

    % TODO: Comment NAD83 State plane coordinates

    stations = textscan(fopen('gz_measurements.csv', 'r'), '%s %f64 %f64', 'Delimiter',',');

    all_names = stations{1};
    all_errors = stations{2};
    all_measurements = stations{3};
    measured_points = unique(all_names);

    measurement_table = cell2table(cell(size(table, 1), 2), ...
        'VariableNames', {'Measurements', 'Errors'}, ....
        'RowNames', table.Properties.RowNames);

    for name = measured_points',
        is_a_measurement = strcmp(all_names, name);
        assert(any(strcmp(table.Properties.RowNames, name)), ['Station ' name ' is not in the database of points'])
        % TODO: Is this the write way to assign (indexing gives 1x1 cell)
        measurement_table{name, 1:2} = {all_measurements(is_a_measurement), all_errors(is_a_measurement)};
    end

    table = [table, measurement_table];
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>com.ameliant.examples</groupId>
	<artifactId>smx-ent-osgi</artifactId>
	<packaging>pom</packaging>
	<version>1.0-SNAPSHOT</version>

	<name>smx-ent-osgi</name>

	<properties>
		<camel.version>2.10.3</camel.version>
        <camel-feature.range>[${camel.version},3)</camel-feature.range>
        <activemq-camel.version>5.7.0</activemq-camel.version>
        <activemq-feature.range>[${activemq-camel.version},6)</activemq-feature.range>

        <jpa-spec.range>[2,3)</jpa-spec.range>
        <openjpa.version>2.3.0</openjpa.version>
        <openjpa.range>[${openjpa.version},3)</openjpa.range>
        <geronimo-jpa_2.0_spec.version>1.1</geronimo-jpa_2.0_spec.version>
        <derby.version>10.9.1.0_1</derby.version>
        <slf4j.version>1.7.3</slf4j.version>

		<maven-compiler-plugin.version>2.5</maven-compiler-plugin.version>
		<maven-bundle-plugin.version>2.3.6</maven-bundle-plugin.version>
		<build-plugins-plugin.version>2.5</build-plugins-plugin.version>
		<build-helper-plugin.version>1.7</build-helper-plugin.version>

		<osgi-import-package>*</osgi-import-package>
	</properties>

	<modules>
        <module>bundle-parent</module>
        <module>fancyfoods-api</module>
        <module>fancyfoods-datasource</module>
        <module>fancyfoods-persistence</module>
        <module>fancyfoods-dept-chocolate</module>
        <module>fancyfoods-dept-cheese</module>
        <module>fancyfoods-business</module>
        <module>fancyfoods-web</module>
        <module>fancyfoods-web-nls-fr</module>
        <module>fancyfoods-features</module>
  </modules>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>${maven-compiler-plugin.version}</version>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>

				<!-- used to generate the MANIFEST-FILE of a bundle -->
				<plugin>
					<groupId>org.apache.felix</groupId>
					<artifactId>maven-bundle-plugin</artifactId>
					<version>${maven-bundle-plugin.version}</version>
					<extensions>true</extensions>
					<configuration>
						<!-- see https://ops4j1.jira.com/wiki/display/ops4j/Getting+the+benefits+of+maven-bundle-plugin+in+other+project+types -->
						<supportedProjectTypes>
							<supportedProjectType>bundle</supportedProjectType>
							<supportedProjectType>war</supportedProjectType>
						</supportedProjectTypes>
						<instructions>
							<Bundle-SymbolicName>${project.name}</Bundle-SymbolicName>
							<Import-Package>${osgi-import-package}</Import-Package>
						</instructions>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>


text:
Run ECMAScript in a unix terminal: http://stackoverflow.com/questions/8532960/how-do-you-run-javascript-script-through-the-terminal

## Rhino shell (Mozilla)

Debian package: `rhino`

Open the interactive javascript console: `$ rhino` or `$ js`

Open and interprete a javascript file: `$ rhino FILENAME.js` or `$ js FILENAME.js`

Misc: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Shell

## SpiderMonkey shell (Mozilla)

Debian package: `libmozjs-24-bin`

## Node.js (based on Google V8 engine)

Debian package: `nodejs`

Open the interactive javascript console: `$ node`

## D8 (Google V8 shell)

See: http://stackoverflow.com/questions/1802478/running-v8-javascript-engine-standalone

## Others shells

- http://discerning.com/burstproject.org/build/doc/shells.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shells

## Recommended Vim plugins for JavaScript coding

- http://stackoverflow.com/questions/4777366/recommended-vim-plugins-for-javascript-coding


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Wax.Util.Disk;

namespace Wax
{
    /*
        An assortment of file util functions that take into consideration that part of the path
        may possibly be a CryPkg.

        Attempts to read real files from disk first, and then falls back to checking each directory
        if a CryPkg exists. Caches results.

        If caching is no longer wanted, use Purge()

        A .crypkg file's name will be that of the directory it represents.
        e.g. "C:\foo\bar\baz.crypkg" will represent "C:\foo\bar\baz\..."
    */
    public class PkgAwareFileUtil
    {
        // TODO: I don't like that this is static. Should pass around an instance.
        private static Dictionary<string, Wax.CryPkgDecoder> packageStatuses = new Dictionary<string, Wax.CryPkgDecoder>();

        public PkgAwareFileUtil()
        { }

        public void Purge() { packageStatuses.Clear(); }

        public bool FileExists(string path)
        {
            string fullPath = System.IO.Path.GetFullPath(path);
            if (File.Exists(fullPath)) return true;

            CryPkgPath pkgPath = GetPackagedPath(fullPath, false);
            if (pkgPath == null) return false;
            return pkgPath.Package.FileExists(pkgPath.Path);
        }

        public bool DirectoryExists(string path)
        {
            string fullPath = System.IO.Path.GetFullPath(path);
            if (Directory.Exists(fullPath)) return true;

            CryPkgPath pkgPath = GetPackagedPath(fullPath, true);
            if (pkgPath == null) return false;
            return pkgPath.Package.DirectoryExists(pkgPath.Path);
        }

        public byte[] ReadFileBytes(string path)
        {
            string fullPath = System.IO.Path.GetFullPath(path);
            if (File.Exists(fullPath)) return File.ReadBytes(fullPath);

            CryPkgPath pkgPath = GetPackagedPath(fullPath, false);
            if (pkgPath == null) throw new System.IO.FileNotFoundException(path);
            return pkgPath.Package.ReadFileBytes(pkgPath.Path);
        }

        public string ReadFileText(string path)
        {
            return Wax.Util.UniversalTextDecoder.Decode(ReadFileBytes(path));
        }

        public string[] ListFiles(string path)
        {
            return this.ListDirectoryContents(path, true, false);
        }

        public string[] ListDirectories(string path)
        {
            return this.ListDirectoryContents(path, false, true);
        }

        private static string[] emptyStringArray = new string[0];
        private string[] ListDirectoryContents(string path, bool includeFiles, bool includeDirectories)
        {
            string fullPath = System.IO.Path.GetFullPath(path);
            if (Directory.Exists(fullPath))
            {
                IEnumerable<string> files = includeFiles ? Directory.ListFilesWithAbsolutePaths(fullPath) : emptyStringArray;
                IEnumerable<string> dirs = includeDirectories ? Directory.ListDirectoriesWithAbsolutePaths(fullPath) : emptyStringArray;
                return dirs.Concat(files).ToArray();
            }

            CryPkgPath pkgPath = GetPackagedPath(fullPath, true);
            if (pkgPath == null) throw new System.IO.DirectoryNotFoundException(path);
            return pkgPath.Package.ListDirectory(pkgPath.Path, includeFiles, includeDirectories);
        }

        private CryPkgPath GetPackagedPath(string fullPath, bool isDir)
        {
            string canonicalPath = fullPath.Replace('\\', '/');
            this.EnsureCachePopulated(canonicalPath, isDir);

            string pkgPath = this.GetPathOfHighestCryPkg(canonicalPath, isDir);
            if (pkgPath == null) return null;
            string pkgDir = pkgPath.Substring(0, pkgPath.Length - ".crypkg".Length);
            Wax.CryPkgDecoder pkg = packageStatuses[pkgPath];
            string relativeDir = (pkgDir == canonicalPath)
                ? "."
                : canonicalPath.Substring(pkgDir.Length + 1);
            return new CryPkgPath(relativeDir, pkg);
        }

        private class CryPkgPath
        {
            public CryPkgPath(string path, Wax.CryPkgDecoder package)
            {
                this.Package = package;
                this.Path = path;
            }

            public Wax.CryPkgDecoder Package { get; set; }
            public string Path { get; set; }
        }

        private string[] GetAllPossiblePkgPaths(string path, bool isDir)
        {
            string[] segments = path.Replace('\\', '/').Split('/');
            int segmentsLength = segments.Length;
            if (!isDir) segmentsLength--;

            string[] cumulative = new string[segmentsLength];
            cumulative[0] = segments[0];
            for (int i = 1; i < segmentsLength; ++i)
            {
                cumulative[i] = cumulative[i - 1] + "/" + segments[i];
            }
            string[] pkgPaths = new string[segmentsLength - 1];
            for (int i = 0; i < segmentsLength - 1; ++i)
            {
                pkgPaths[i] = cumulative[i] + "/" + segments[i + 1] + ".crypkg";
            }
            return pkgPaths;
        }

        private void EnsureCachePopulated(string path, bool isDir)
        {
            foreach (string pkgPath in GetAllPossiblePkgPaths(path, isDir))
            {
                if (!packageStatuses.ContainsKey(pkgPath))
                {
                    string pkgRealPath = pkgPath.Replace("/", Path.Separator);
                    if (File.Exists(pkgRealPath))
                    {
                        Wax.CryPkgDecoder pkg = new Wax.CryPkgDecoder(File.ReadBytes(pkgRealPath));
                        packageStatuses[pkgPath] = pkg;
                    }
                    else
                    {
                        packageStatuses[pkgPath] = null;
                    }
                }
            }
        }

        private string GetPathOfHighestCryPkg(string path, bool isDir)
        {
            foreach (string pkgPath in GetAllPossiblePkgPaths(path, isDir).Reverse())
            {
                if (!packageStatuses.ContainsKey(pkgPath)) throw new Exception();
                if (packageStatuses[pkgPath] != null)
                {
                    return pkgPath;
                }
            }
            return null;
        }
    }
}


text:
(function() {

    angular.module('formobject')
        .controller('NgObjectCtrl', Controller);

    function Controller($scope) {

        $scope.$ngObject = {
            array: isArray()
        };

        $scope.add = function () {
            if(isArray()) {
                $scope.model.push('');
            } else {
                $scope.model['new ' + (Object.keys($scope.model).length + 1)] = '';
            }

        }

        function isArray() {
            return angular.isArray($scope.model);
        }

    }

})();


text:
package org.apache.flink.table.expressions.utils

import java.sql.{Date, Time, Timestamp}

import org.apache.commons.lang3.StringUtils
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.table.api.Types
import org.apache.flink.table.functions.{FunctionContext, ScalarFunction}
import org.apache.flink.types.Row
import org.junit.Assert

import scala.annotation.varargs
import scala.collection.mutable
import scala.io.Source

case class SimplePojo(name: String, age: Int)

object Func0 extends ScalarFunction {
  def eval(index: Int): Int = {
    index
  }
}

object Func1 extends ScalarFunction {
  def eval(index: Integer): Integer = {
    index + 1
  }

  def eval(b: Byte): Byte = (b + 1).toByte

  def eval(s: Short): Short = (s + 1).toShort

  def eval(f: Float): Float = f + 1
}

object Func2 extends ScalarFunction {
  def eval(index: Integer, str: String, pojo: SimplePojo): String = {
    s"$index and $str and $pojo"
  }
}

object Func3 extends ScalarFunction {
  def eval(index: Integer, str: String): String = {
    s"$index and $str"
  }
}

object Func4 extends ScalarFunction {
  def eval(): Integer = {
    null
  }
}

object Func5 extends ScalarFunction {
  def eval(): Int = {
    -1
  }
}

object Func6 extends ScalarFunction {
  def eval(date: Date, time: Time, timestamp: Timestamp): (Date, Time, Timestamp) = {
    (date, time, timestamp)
  }
}

object Func7 extends ScalarFunction {
  def eval(a: Integer, b: Integer): Integer = {
    a + b
  }
}

object Func8 extends ScalarFunction {
  def eval(a: Int): String = {
    "a"
  }

  def eval(a: Int, b: Int): String = {
    "b"
  }

  def eval(a: String, b: String): String = {
    "c"
  }
}

object Func9 extends ScalarFunction {
  def eval(a: Int, b: Int, c: Long): String = {
    s"$a and $b and $c"
  }
}

object Func10 extends ScalarFunction {
  def eval(c: Long): Long = {
    c
  }

  override def getResultType(signature: Array[Class[_]]): TypeInformation[_] = {
    Types.SQL_TIMESTAMP
  }
}

object Func11 extends ScalarFunction {
  def eval(a: Int, b: Long): String = {
    s"$a and $b"
  }
}

object Func12 extends ScalarFunction {
  def eval(a: Long): Long = {
    a
  }

  override def getResultType(signature: Array[Class[_]]): TypeInformation[_] = {
    Types.INTERVAL_MILLIS
  }
}

object ShouldNotExecuteFunc extends ScalarFunction {
  def eval(s: String): Boolean = {
    throw new Exception("This func should never be executed")
  }
}

class RichFunc0 extends ScalarFunction {
  var openCalled = false
  var closeCalled = false

  override def open(context: FunctionContext): Unit = {
    super.open(context)
    if (openCalled) {
      Assert.fail("Open called more than once.")
    } else {
      openCalled = true
    }
    if (closeCalled) {
      Assert.fail("Close called before open.")
    }
  }

  def eval(index: Int): Int = {
    if (!openCalled) {
      Assert.fail("Open was not called before eval.")
    }
    if (closeCalled) {
      Assert.fail("Close called before eval.")
    }

    index + 1
  }

  override def close(): Unit = {
    super.close()
    if (closeCalled) {
      Assert.fail("Close called more than once.")
    } else {
      closeCalled = true
    }
    if (!openCalled) {
      Assert.fail("Open was not called before close.")
    }
  }
}

class RichFunc1 extends ScalarFunction {
  var added = Int.MaxValue

  override def open(context: FunctionContext): Unit = {
    added = context.getJobParameter("int.value", "0").toInt
  }

  def eval(index: Int): Int = {
    index + added
  }

  override def close(): Unit = {
    added = Int.MaxValue
  }
}

class RichFunc2 extends ScalarFunction {
  var prefix = "ERROR_VALUE"

  override def open(context: FunctionContext): Unit = {
    prefix = context.getJobParameter("string.value", "")
  }

  def eval(value: String): String = {
    prefix + "#" + value
  }

  override def close(): Unit = {
    prefix = "ERROR_VALUE"
  }
}

class RichFunc3 extends ScalarFunction {
  private val words = mutable.HashSet[String]()

  override def open(context: FunctionContext): Unit = {
    val file = context.getCachedFile("words")
    for (line <- Source.fromFile(file.getCanonicalPath).getLines) {
      words.add(line.trim)
    }
  }

  def eval(value: String): Boolean = {
    words.contains(value)
  }

  override def close(): Unit = {
    words.clear()
  }
}

class Func13(prefix: String) extends ScalarFunction {
  def eval(a: String): String = {
    s"$prefix-$a"
  }
}

object Func14 extends ScalarFunction {

  @varargs
  def eval(a: Int*): Int = {
    a.sum
  }
}

object Func15 extends ScalarFunction {

  @varargs
  def eval(a: String, b: Int*): String = {
    a + b.length
  }

  def eval(a: String): String = {
    a
  }
}

object Func16 extends ScalarFunction {

  def eval(a: Seq[String]): String = {
    a.mkString(", ")
  }
}

object Func17 extends ScalarFunction {

  // Without @varargs, we will throw an exception
  def eval(a: String*): String = {
    a.mkString(", ")
  }
}

object Func18 extends ScalarFunction {
  def eval(str: String, prefix: String): Boolean = {
    str.startsWith(prefix)
  }
}

object Func19 extends ScalarFunction {
  def eval(row: Row): Row = {
    row
  }

  override def getParameterTypes(signature: Array[Class[_]]): Array[TypeInformation[_]] =
    Array(Types.ROW(Types.INT, Types.BOOLEAN, Types.ROW(Types.INT, Types.INT, Types.INT)))

  override def getResultType(signature: Array[Class[_]]): TypeInformation[_] =
    Types.ROW(Types.INT, Types.BOOLEAN, Types.ROW(Types.INT, Types.INT, Types.INT))

}

class SplitUDF(deterministic: Boolean) extends ScalarFunction {
  def eval(x: String, sep: String, index: Int): String = {
    val splits = StringUtils.splitByWholeSeparator(x, sep)
    if (splits.length > index) {
      splits(index)
    } else {
      null
    }
  }
  override def isDeterministic: Boolean = deterministic
}


text:
package org.renjin.parser;

import org.renjin.sexp.SEXP;

/**
 * Reference to a specific point in the source code.
 * <p/>
 * Translated from the C {@code SrcRefState }
 */
public class SrcRefState {

  /**
   * Whether to attach srcrefs to objects as they are parsed
   */
  public boolean keepSrcRefs;

  /**
   * The srcfile object currently being parsed
   */
  public SEXP SrcFile;

  /**
   * The SrcFile may change
   */
  public int SrcFileProt;

  /**
   * Position information about the current parse
   */
  public int xxlineno;
  public int xxcolno;
  public int xxbyteno;

}


text:
require 'spec_helper'

class Kid
  attr_accessor :iq

  def initialize(iq)
    @iq = iq
  end
end

class School
  def educate(who)
    who.iq *= 2
  end
end

describe "object references" do
  it "passes by reference" do
    kid = Kid.new(50)
    school = School.new

    school.educate(kid)
    kid.iq.should == 100
  end
end


text:
#include "policy/update_status_manager.h"
#include "policy/policy_listener.h"
#include "utils/logger.h"
#include "utils/make_shared.h"

namespace policy {

CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")

UpdateStatusManager::UpdateStatusManager()
    : listener_(NULL)
    , current_status_(utils::MakeShared<UpToDateStatus>())
    , last_processed_event_(kNoEvent)
    , apps_search_in_progress_(false)
    , app_registered_from_non_consented_device_(true) {}

UpdateStatusManager::~UpdateStatusManager() {}

void UpdateStatusManager::ProcessEvent(UpdateEvent event) {
  sync_primitives::AutoLock lock(status_lock_);
  current_status_->ProcessEvent(this, event);
  last_processed_event_ = event;
  DoTransition();
}

void UpdateStatusManager::SetNextStatus(utils::SharedPtr<Status> status) {
  next_status_ = status;
}

void UpdateStatusManager::SetPostponedStatus(utils::SharedPtr<Status> status) {
  postponed_status_ = status;
}

void UpdateStatusManager::set_listener(PolicyListener* listener) {
  listener_ = listener;
}

void UpdateStatusManager::OnUpdateSentOut() {
  LOG4CXX_AUTO_TRACE(logger_);
  ProcessEvent(kOnUpdateSentOut);
}

void UpdateStatusManager::OnUpdateTimeoutOccurs() {
  LOG4CXX_AUTO_TRACE(logger_);
  ProcessEvent(kOnUpdateTimeout);
}

void UpdateStatusManager::OnValidUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  ProcessEvent(kOnValidUpdateReceived);
}

void UpdateStatusManager::OnWrongUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  ProcessEvent(kOnWrongUpdateReceived);
}

void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (is_update_required) {
    ProcessEvent(kOnResetPolicyTableRequireUpdate);
    return;
  }
  ProcessEvent(kOnResetPolicyTableNoUpdate);
}

void UpdateStatusManager::OnResetRetrySequence() {
  LOG4CXX_AUTO_TRACE(logger_);
  ProcessEvent(kOnResetRetrySequence);
}

void UpdateStatusManager::OnNewApplicationAdded(const DeviceConsent consent) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (kDeviceAllowed != consent) {
    app_registered_from_non_consented_device_ = true;
    return;
  }
  app_registered_from_non_consented_device_ = false;
  ProcessEvent(kOnNewAppRegistered);
}

void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (is_update_required) {
    current_status_.reset(new UpToDateStatus());
    ProcessEvent(kScheduleUpdate);
  }
}

void UpdateStatusManager::OnDeviceConsented() {
  LOG4CXX_AUTO_TRACE(logger_);
  if (app_registered_from_non_consented_device_) {
    ProcessEvent(kOnNewAppRegistered);
  }
}

bool UpdateStatusManager::IsUpdateRequired() const {
  return current_status_->IsUpdateRequired();
}

bool UpdateStatusManager::IsUpdatePending() const {
  return current_status_->IsUpdatePending();
}

void UpdateStatusManager::ScheduleUpdate() {
  ProcessEvent(kScheduleUpdate);
}

void UpdateStatusManager::ScheduleManualUpdate() {
  ProcessEvent(kScheduleManualUpdate);
}

std::string UpdateStatusManager::StringifiedUpdateStatus() const {
  return current_status_->get_status_string();
}

void policy::UpdateStatusManager::OnAppsSearchStarted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = true;
}

void policy::UpdateStatusManager::OnAppsSearchCompleted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = false;
}

bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  return apps_search_in_progress_;
}

void UpdateStatusManager::DoTransition() {
  DCHECK_OR_RETURN_VOID(listener_);
  if (!next_status_) {
    return;
  }

  current_status_ = next_status_;
  next_status_.reset();
  LOG4CXX_DEBUG(logger_, "last_processed_event_ = " << last_processed_event_);
  if (last_processed_event_ != kScheduleManualUpdate) {
    listener_->OnUpdateStatusChanged(current_status_->get_status_string());
  }
  if (!postponed_status_) {
    return;
  }

  current_status_ = postponed_status_;
  if (last_processed_event_ != kScheduleManualUpdate) {
    listener_->OnUpdateStatusChanged(current_status_->get_status_string());
  }
  postponed_status_.reset();
}

}  // namespace policy


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>play.data.validation Class Hierarchy (Play! API)</title>
<meta name="date" content="2017-10-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package play.data.validation

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

net.sf.oval.AbstractCheck (implements net.sf.oval.Check)

net.sf.oval.configuration.annotation.AbstractAnnotationCheck<ConstraintAnnotation> (implements net.sf.oval.configuration.annotation.AnnotationCheck<ConstraintAnnotation>)

play.data.validation.CheckWithCheck

play.data.validation.EmailCheck

play.data.validation.EqualsCheck

play.data.validation.InFutureCheck

play.data.validation.InPastCheck

play.data.validation.IPv4AddressCheck

play.data.validation.IPv6AddressCheck

play.data.validation.IsTrueCheck

play.data.validation.MatchCheck

play.data.validation.MaxCheck

play.data.validation.MaxSizeCheck

play.data.validation.MinCheck

play.data.validation.MinSizeCheck

play.data.validation.PhoneCheck

play.data.validation.RangeCheck

play.data.validation.RequiredCheck

play.data.validation.UniqueCheck

play.data.validation.URLCheck

play.data.validation.ValidCheck

play.data.validation.Check

play.data.validation.Error

play.PlayPlugin (implements java.lang.Comparable<T>)

play.data.validation.ValidationPlugin

play.data.validation.Validation

play.data.validation.Validation.ValidationResult

play.data.validation.Validation.Validator

Annotation Type Hierarchy

play.data.validation.Valid (implements java.lang.annotation.Annotation)

play.data.validation.URL (implements java.lang.annotation.Annotation)

play.data.validation.Unique (implements java.lang.annotation.Annotation)

play.data.validation.Required (implements java.lang.annotation.Annotation)

play.data.validation.Range (implements java.lang.annotation.Annotation)

play.data.validation.Phone (implements java.lang.annotation.Annotation)

play.data.validation.Password (implements java.lang.annotation.Annotation)

play.data.validation.MinSize (implements java.lang.annotation.Annotation)

play.data.validation.Min (implements java.lang.annotation.Annotation)

play.data.validation.MaxSize (implements java.lang.annotation.Annotation)

play.data.validation.Max (implements java.lang.annotation.Annotation)

play.data.validation.Match (implements java.lang.annotation.Annotation)

play.data.validation.IsTrue (implements java.lang.annotation.Annotation)

play.data.validation.IPv6Address (implements java.lang.annotation.Annotation)

play.data.validation.IPv4Address (implements java.lang.annotation.Annotation)

play.data.validation.InPast (implements java.lang.annotation.Annotation)

play.data.validation.InFuture (implements java.lang.annotation.Annotation)

play.data.validation.Equals (implements java.lang.annotation.Annotation)

play.data.validation.Email (implements java.lang.annotation.Annotation)

play.data.validation.CheckWith (implements java.lang.annotation.Annotation)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
from __future__ import unicode_literals

import re
import random
import string
from unittest.mock import patch
from datetime import datetime

# from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, RequestFactory
from django.urls import reverse

from django_comments.views import comments

from django_comments_xtd import django_comments, signals, signed, views
from django_comments_xtd.conf import settings
from django_comments_xtd.models import XtdComment
from django_comments_xtd.tests.models import Article, Diary

request_factory = RequestFactory()

def post_article_comment(data, article, auth_user=None):
    request = request_factory.post(
        reverse('article-detail', kwargs={'year': article.publish.year,
                                          'month': article.publish.month,
                                          'day': article.publish.day,
                                          'slug': article.slug}),
        data=data, follow=True)
    if auth_user:
        request.user = auth_user
    else:
        request.user = AnonymousUser()
    request._dont_enforce_csrf_checks = True
    return comments.post_comment(request)

def post_diary_comment(data, diary_entry, auth_user=None):
    request = request_factory.post(
        reverse('diary-detail', kwargs={'year': diary_entry.publish.year,
                                        'month': diary_entry.publish.month,
                                        'day': diary_entry.publish.day}),
        data=data, follow=True)
    if auth_user:
        request.user = auth_user
    else:
        request.user = AnonymousUser()
    request._dont_enforce_csrf_checks = True
    return comments.post_comment(request)

def confirm_comment_url(key, follow=True):
    request = request_factory.get(reverse("comments-xtd-confirm",
                                          kwargs={'key': key}),
                                  follow=follow)
    request.user = AnonymousUser()
    return views.confirm(request, key)

app_model_options_mock = {
    'tests.article': {
        'who_can_post': 'users'
    }
}

class OnCommentWasPostedTestCase(TestCase):
    def setUp(self):
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        self.article = Article.objects.create(
            title="October", slug="october", body="What I did on October...")
        self.form = django_comments.get_form()(self.article)
        self.user = AnonymousUser()

    def post_valid_data(self, auth_user=None, response_code=302):
        data = {"name": "Bob", "email": "bob@example.com", "followup": True,
                "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal eine kleine..."}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article, auth_user)
        self.assertEqual(response.status_code, response_code)
        if response.status_code == 302:
            self.assertTrue(response.url.startswith('/comments/posted/?c='))

    def test_post_as_authenticated_user(self):
        self.user = User.objects.create_user("bob", "bob@example.com", "pwd")
        self.assertTrue(self.mock_mailer.call_count == 0)
        self.post_valid_data(auth_user=self.user)
        # no confirmation email sent as user is authenticated
        self.assertTrue(self.mock_mailer.call_count == 0)

    def test_confirmation_email_is_sent(self):
        self.assertTrue(self.mock_mailer.call_count == 0)
        self.post_valid_data()
        self.assertTrue(self.mock_mailer.call_count == 1)

    @patch.multiple('django_comments_xtd.conf.settings',
                    COMMENTS_XTD_APP_MODEL_OPTIONS=app_model_options_mock)
    def test_post_as_visitor_when_only_users_can_post(self):
        self.assertTrue(self.mock_mailer.call_count == 0)
        self.post_valid_data(response_code=400)
        self.assertTrue(self.mock_mailer.call_count == 0)

class ConfirmCommentTestCase(TestCase):
    def setUp(self):
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        # Create random string so that it's harder for zlib to compress
        content = ''.join(random.choice(string.printable) for _ in range(6096))
        self.article = Article.objects.create(title="September",
                                              slug="september",
                                              body="In September..." + content)
        self.form = django_comments.get_form()(self.article)
        data = {"name": "Bob", "email": "bob@example.com", "followup": True,
                "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal iene kleine..."}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article)
        self.assertTrue(self.mock_mailer.call_count == 1)
        self.key = str(
            re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                      self.mock_mailer.call_args[0][1]
            ).group("key")
        )
        self.addCleanup(patcher.stop)

    def test_confirm_url_is_short_enough(self):
        # Tests that the length of the confirm url's length isn't
        # dependent on the article length.
        l = len(reverse("comments-xtd-confirm",
                        kwargs={'key': self.key}))
        # print("\nXXXXXXXXXXX:", l)
        self.assertLessEqual(l, 4096, "Urls can only be a max of 4096")

    def test_400_on_bad_signature(self):
        response = confirm_comment_url(self.key[:-1])
        self.assertEqual(response.status_code, 400)

    def test_consecutive_confirmation_url_visits_doesnt_fail(self):
        # test that consecutives visits to the same confirmation URL produce
        # an Http 404 code, as the comment has already been verified in the
        # first visit
        response = confirm_comment_url(self.key)
        self.assertEqual(response.status_code, 302)
        confirm_comment_url(self.key)
        self.assertEqual(response.status_code, 302)

    def test_signal_receiver_may_discard_the_comment(self):
        # test that receivers of signal confirmation_received may return False
        # and thus rendering a template_discarded output
        def on_signal(sender, comment, request, **kwargs):
            return False

        self.assertEqual(self.mock_mailer.call_count, 1)  # sent during setUp
        signals.confirmation_received.connect(on_signal)
        response = confirm_comment_url(self.key)
        # mailing avoided by on_signal:
        self.assertEqual(self.mock_mailer.call_count, 1)
        self.assertTrue(response.content.find(b'Comment discarded') > -1)

    def test_comment_is_created_and_view_redirect(self):
        # testing that visiting a correct confirmation URL creates a XtdComment
        # and redirects to the article detail page
        Site.objects.get_current().domain = "testserver"  # django bug #7743
        response = confirm_comment_url(self.key, follow=False)
        data = signed.loads(self.key, extra_key=settings.COMMENTS_XTD_SALT)
        try:
            comment = XtdComment.objects.get(
                content_type=data["content_type"],
                user_name=data["user_name"],
                user_email=data["user_email"],
                submit_date=data["submit_date"])
        except:
            comment = None
        self.assertTrue(comment is not None)
        self.assertEqual(response.url, comment.get_absolute_url())

    def test_notify_comment_followers(self):
        # send a couple of comments to the article with followup=True and check
        # that when the second comment is confirmed a followup notification
        # email is sent to the user who sent the first comment
        self.assertEqual(self.mock_mailer.call_count, 1)
        confirm_comment_url(self.key)
        # no comment followers yet:
        self.assertEqual(self.mock_mailer.call_count, 1)
        # send 2nd comment
        self.form = django_comments.get_form()(self.article)
        data = {"name": "Alice", "email": "alice@example.com",
                "followup": True, "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal eine kleine..."}
        data.update(self.form.initial)
        response = post_article_comment(data, article=self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.assertEqual(self.mock_mailer.call_count, 2)
        self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                             self.mock_mailer.call_args[0][1]).group("key")
        confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 3)
        self.assertTrue(
            # We can find the 'comment' in the text_message.
            self.mock_mailer.call_args[0][1].index(data['comment']) > -1
        )
        articles_title = f"Post: {self.article.title}"
        self.assertTrue(
            # We can find article's title (comment.content_object.title).
            self.mock_mailer.call_args[0][1].index(articles_title) > -1
        )
        self.assertTrue(self.mock_mailer.call_args[0][3] == ["bob@example.com"])
        self.assertTrue(self.mock_mailer.call_args[0][1].find(
            "There is a new comment following up yours.") > -1)

    def test_notify_followers_dupes(self):
        # first of all confirm Bob's comment otherwise it doesn't reach DB
        confirm_comment_url(self.key)
        # then put in play pull-request-15's assert...
        # https://github.com/danirus/django-comments-xtd/pull/15
        diary = Diary.objects.create(
            body='Lorem ipsum',
            allow_comments=True
        )
        self.assertEqual(diary.pk, self.article.pk)

        self.form = django_comments.get_form()(diary)
        data = {"name": "Charlie", "email": "charlie@example.com",
                "followup": True, "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal eine kleine..."}
        data.update(self.form.initial)
        response = post_diary_comment(data, diary_entry=diary)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.key = str(re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                                 self.mock_mailer.call_args[0][1]).group("key"))
        # 1) confirmation for Bob (sent in `setUp()`)
        # 2) confirmation for Charlie
        self.assertEqual(self.mock_mailer.call_count, 2)
        response = confirm_comment_url(self.key)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/cr/'))
        self.assertEqual(self.mock_mailer.call_count, 2)

        self.form = django_comments.get_form()(self.article)
        data = {"name": "Alice", "email": "alice@example.com",
                "followup": True, "reply_to": 0, "level": 1, "order": 1,
                "comment": "Es war einmal iene kleine..."}
        data.update(self.form.initial)
        response = post_article_comment(data, article=self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.assertEqual(self.mock_mailer.call_count, 3)
        self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                             self.mock_mailer.call_args[0][1]).group("key")
        confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 4)
        self.assertTrue(self.mock_mailer.call_args[0][3] == ["bob@example.com"])
        self.assertTrue(self.mock_mailer.call_args[0][1].find(
            "There is a new comment following up yours.") > -1)

    def test_no_notification_for_same_user_email(self):
        # test that a follow-up user_email don't get a notification when
        # sending another email to the thread
        self.assertEqual(self.mock_mailer.call_count, 1)
        confirm_comment_url(self.key)  # confirm Bob's comment
        # no comment followers yet:
        self.assertEqual(self.mock_mailer.call_count, 1)
        # send Bob's 2nd comment
        self.form = django_comments.get_form()(self.article)
        data = {"name": "Alice", "email": "bob@example.com", "followup": True,
                "reply_to": 0, "level": 1, "order": 1,
                "comment": "Bob's comment he shouldn't get notified about"}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article)
        self.assertEqual(self.mock_mailer.call_count, 2)
        self.key = re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                             self.mock_mailer.call_args[0][1]).group("key")
        confirm_comment_url(self.key)
        self.assertEqual(self.mock_mailer.call_count, 2)

class ReplyNoCommentTestCase(TestCase):
    def test_reply_non_existing_comment_raises_404(self):
        response = self.client.get(reverse("comments-xtd-reply",
                                           kwargs={"cid": 1}))
        self.assertContains(response, "404", status_code=404)

class ReplyCommentTestCase(TestCase):
    def setUp(self):
        article = Article.objects.create(title="September",
                                         slug="september",
                                         body="What I did on September...")
        article_ct = ContentType.objects.get(app_label="tests", model="article")
        site = Site.objects.get(pk=1)

        # post Comment 1 to article, level 0
        XtdComment.objects.create(content_type=article_ct,
                                  object_pk=article.id,
                                  content_object=article,
                                  site=site,
                                  comment="comment 1 to article",
                                  submit_date=datetime.now())

        # post Comment 2 to article, level 1
        XtdComment.objects.create(content_type=article_ct,
                                  object_pk=article.id,
                                  content_object=article,
                                  site=site,
                                  comment="comment 1 to comment 1",
                                  submit_date=datetime.now(),
                                  parent_id=1)

        # post Comment 3 to article, level 2 (max according to test settings)
        XtdComment.objects.create(content_type=article_ct,
                                  object_pk=article.id,
                                  content_object=article,
                                  site=site,
                                  comment="comment 1 to comment 1",
                                  submit_date=datetime.now(),
                                  parent_id=2)

    @patch.multiple('django_comments_xtd.conf.settings',
                    COMMENTS_XTD_MAX_THREAD_LEVEL=2)
    def test_not_allow_threaded_reply_raises_403(self):
        response = self.client.get(reverse("comments-xtd-reply",
                                           kwargs={"cid": 3}))
        self.assertEqual(response.status_code, 403)

    @patch.multiple('django_comments_xtd.conf.settings',
                    COMMENTS_XTD_APP_MODEL_OPTIONS=app_model_options_mock)
    def test_reply_as_visitor_when_only_users_can_post(self):
        response = self.client.get(reverse("comments-xtd-reply",
                                           kwargs={"cid": 1}))
        self.assertEqual(response.status_code, 302)  # Redirect to login.
        self.assertTrue(response.url.startswith(settings.LOGIN_URL))

class MuteFollowUpTestCase(TestCase):
    def setUp(self):
        # Creates an article and send two comments to the article with
        # follow-up notifications. First comment doesn't have to send any
        #  notification.
        # Second comment has to send one notification (to Bob).
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        self.article = Article.objects.create(
            title="September", slug="september", body="John's September")
        self.form = django_comments.get_form()(self.article)

        # Bob sends 1st comment to the article with follow-up
        data = {"name": "Bob", "email": "bob@example.com", "followup": True,
                "reply_to": 0, "level": 1, "order": 1,
                "comment": "Nice September you had..."}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.assertTrue(self.mock_mailer.call_count == 1)
        bobkey = str(re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                               self.mock_mailer.call_args[0][1]).group("key"))
        confirm_comment_url(bobkey)  # confirm Bob's comment

        # Alice sends 2nd comment to the article with follow-up
        data = {"name": "Alice", "email": "alice@example.com",
                "followup": True, "reply_to": 1, "level": 1, "order": 1,
                "comment": "Yeah, great photos"}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.assertTrue(self.mock_mailer.call_count == 2)
        alicekey = str(re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                                 self.mock_mailer.call_args[0][1]).group("key"))
        confirm_comment_url(alicekey)  # confirm Alice's comment

        # Bob receives a follow-up notification
        self.assertTrue(self.mock_mailer.call_count == 3)
        self.bobs_mutekey = str(re.search(
            r'http://.+/mute/(?P<key>[\S]+)/',
            self.mock_mailer.call_args[0][1]).group("key"))
        self.addCleanup(patcher.stop)

    def get_mute_followup_url(self, key):
        request = request_factory.get(reverse("comments-xtd-mute",
                                              kwargs={'key': key}),
                                      follow=True)
        request.user = AnonymousUser()
        response = views.mute(request, key)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.content.find(b'Comment thread muted') > -1)
        return response

    def test_mute_followup_notifications(self):
        # Bob's receive a notification and click on the mute link to
        # avoid additional comment messages on the same article.
        self.get_mute_followup_url(self.bobs_mutekey)
        # Alice sends 3rd comment to the article with follow-up
        data = {"name": "Alice", "email": "alice@example.com",
                "followup": True, "reply_to": 2, "level": 1, "order": 1,
                "comment": "And look at this and that..."}
        data.update(self.form.initial)
        response = post_article_comment(data, self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        # Alice confirms her comment...
        self.assertTrue(self.mock_mailer.call_count == 4)
        alicekey = str(
            re.search(r'http://.+/confirm/(?P<key>[\S]+)/',
                      self.mock_mailer.call_args[0][1]
            ).group("key")
        )
        confirm_comment_url(alicekey)  # confirm Alice's comment
        # Alice confirmed her comment, but this time Bob won't receive any
        # notification, neither do Alice being the sender
        self.assertTrue(self.mock_mailer.call_count == 4)

class HTMLDisabledMailTestCase(TestCase):
    def setUp(self):
        # Create an article and send a comment. Test method will chech headers
        # to see wheter messages has multiparts or not.
        patcher = patch('django_comments_xtd.views.send_mail')
        self.mock_mailer = patcher.start()
        self.article = Article.objects.create(
            title="September", slug="september", body="John's September")
        self.form = django_comments.get_form()(self.article)

        # Bob sends 1st comment to the article with follow-up
        self.data = {"name": "Bob", "email": "bob@example.com",
                     "followup": True, "reply_to": 0, "level": 1, "order": 1,
                     "comment": "Nice September you had..."}
        self.data.update(self.form.initial)

    @patch.multiple('django_comments_xtd.conf.settings',
                    COMMENTS_XTD_SEND_HTML_EMAIL=False)
    def test_mail_does_not_contain_html_part(self):
        with patch.multiple('django_comments_xtd.conf.settings',
                            COMMENTS_XTD_SEND_HTML_EMAIL=False):
            response = post_article_comment(self.data, self.article)
            self.assertEqual(response.status_code, 302)
            self.assertTrue(response.url.startswith('/comments/posted/?c='))
            self.assertTrue(self.mock_mailer.call_count == 1)
            self.assertTrue(self.mock_mailer.call_args[1]['html'] is None)

    def test_mail_does_contain_html_part(self):
        response = post_article_comment(self.data, self.article)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/comments/posted/?c='))
        self.assertTrue(self.mock_mailer.call_count == 1)
        self.assertTrue(self.mock_mailer.call_args[1]['html'] is not None)


text:
<?php
/**
 * This file host two test case classes for the MediaWiki FormOptions class:
 *  - FormOptionsInitializationTest : tests initialization of the class.
 *  - FormOptionsTest : tests methods an on instance
 *
 * The split let us take advantage of setting up a fixture for the methods
 * tests.
 */

/**
 * Test class for FormOptions methods.
 * Generated by PHPUnit on 2011-02-28 at 20:46:27.
 *
 * Copyright © 2011, Antoine Musso
 *
 * @author Antoine Musso
 */
class FormOptionsTest extends MediaWikiTestCase {
	/**
	 * @var FormOptions
	 */
	protected $object;

	/**
	 * Instanciates a FormOptions object to play with.
	 * FormOptions::add() is tested by the class FormOptionsInitializationTest
	 * so we assume the function is well tested already an use it to create
	 * the fixture.
	 */
	protected function setUp() {
		parent::setUp();
		$this->object = new FormOptions;
		$this->object->add( 'string1', 'string one' );
		$this->object->add( 'string2', 'string two' );
		$this->object->add( 'integer', 0 );
		$this->object->add( 'float', 0.0 );
		$this->object->add( 'intnull', 0, FormOptions::INTNULL );
	}

	/** Helpers for testGuessType() */
	/* @{ */
	private function assertGuessBoolean( $data ) {
		$this->guess( FormOptions::BOOL, $data );
	}
	private function assertGuessInt( $data ) {
		$this->guess( FormOptions::INT, $data );
	}
	private function assertGuessFloat( $data ) {
		$this->guess( FormOptions::FLOAT, $data );
	}
	private function assertGuessString( $data ) {
		$this->guess( FormOptions::STRING, $data );
	}

	/** Generic helper */
	private function guess( $expected, $data ) {
		$this->assertEquals(
			$expected,
			FormOptions::guessType( $data )
		);
	}
	/* @} */

	/**
	 * Reuse helpers above assertGuessBoolean assertGuessInt assertGuessString
	 * @covers FormOptions::guessType
	 */
	public function testGuessTypeDetection() {
		$this->assertGuessBoolean( true );
		$this->assertGuessBoolean( false );

		$this->assertGuessInt( 0 );
		$this->assertGuessInt( -5 );
		$this->assertGuessInt( 5 );
		$this->assertGuessInt( 0x0F );

		$this->assertGuessFloat( 0.0 );
		$this->assertGuessFloat( 1.5 );
		$this->assertGuessFloat( 1e3 );

		$this->assertGuessString( 'true' );
		$this->assertGuessString( 'false' );
		$this->assertGuessString( '5' );
		$this->assertGuessString( '0' );
		$this->assertGuessString( '1.5' );
	}

	/**
	 * @expectedException MWException
	 * @covers FormOptions::guessType
	 */
	public function testGuessTypeOnArrayThrowException() {
		$this->object->guessType( [ 'foo' ] );
	}
	/**
	 * @expectedException MWException
	 * @covers FormOptions::guessType
	 */
	public function testGuessTypeOnNullThrowException() {
		$this->object->guessType( null );
	}
}


text:
require 'pathname'
require 'securerandom'
require 'thor'

module ROR
  module BuildTestApp
    ROOT = Pathname.new('../../..').expand_path(__FILE__)
    TEST_DIR = ROOT.join('tmp/scaffold')
    BUNDLE_CACHE = ROOT.join('vendor/bundle-scaffold').join(RUBY_VERSION)
    RAILS_NEW_BASE_OPTIONS = '--skip-test --skip-git --skip-spring --skip-bundle --skip-bootsnap'.freeze

    class Helper < Thor::Group
      include Thor::Actions

      def initialize(database: 'sqlite3', keep_scaffold: false)
        super()

        @database = database
        @keep_scaffold = keep_scaffold
      end

      def shell_run(command)
        say_status 'running', command.gsub(Dir.pwd, '$PWD')
        output = `#{command}`

        if $CHILD_STATUS.success?
          output
        else
          puts output
          raise "command: `#{command}` failed"
        end
      end

      def ensure_scaffold
        return self if scaffold_path.exist?
        scaffold_dir.rmtree if scaffold_dir.exist?
        TEST_DIR.mkpath

        require 'rails'

        if Rails::VERSION::MAJOR > 5
          shell_run "rails new #{scaffold_dir} #{rails_new_options} --skip-javascript"
        else
          shell_run "rails new #{scaffold_dir} #{rails_new_options}"
        end

        if Rails::VERSION::MAJOR < 6
          # There are compatibility problems with sqlite3 1.4.x and older Rails versions
          gsub_file scaffold_dir.join('Gemfile'), /^\s*gem 'sqlite3'.*/, 'gem "sqlite3", "~> 1.3.6"'
        end

        append_to_file scaffold_dir.join('Gemfile'), %{
          gem 'roo_on_rails', path: '#{ROOT}'
        }

        Bundler.with_clean_env do
          shell_run "cd #{scaffold_dir} && bundle install -j4 --retry=3 --path=#{BUNDLE_CACHE}"
        end

        shell_run "tar -C #{scaffold_dir} -cf #{scaffold_path} ."
        scaffold_dir.rmtree unless @keep_scaffold
        self
      end

      def write_dotenv_file(path, app_env_vars)
        create_file path.join('.env'), app_env_vars
      end

      def unpack_scaffold_at(path)
        shell_run "mkdir -p #{path}"
        shell_run "tar -C #{path} -xf #{scaffold_path}"
        self
      end

      def clear_test_app_at(path)
        path.rmtree if path.exist?
        self
      end

      def self.clear_scaffolds
        new.say_status 'removing', 'scaffold app cache'
        TEST_DIR.rmtree if TEST_DIR.exist?
      end

      private

      def id
        @id ||= Digest::MD5.hexdigest(rails_new_options)
      end

      def rails_new_options
        options = [RAILS_NEW_BASE_OPTIONS]

        options << case @database
        when nil
          '--skip-active-record'
        else
          "--database=#{@database}"
        end

        options.join(' ')
      end

      def scaffold_dir
        TEST_DIR.join("app-#{id}")
      end

      def scaffold_path
        TEST_DIR.join("app-#{id}.tar")
      end
    end

    def build_test_app
      let(:app_id) { '%s.%s' % [Time.now.strftime('%F.%H%M%S'), SecureRandom.hex(4)] }
      let(:app_path) { TEST_DIR.join(app_id) }
      let(:app_helper) { Helper.new(**app_options) }
      let(:app_options) { {} }
      let(:app_env_vars) { "" }

      before do
        app_helper.ensure_scaffold
          .unpack_scaffold_at(app_path)
          .write_dotenv_file(app_path, app_env_vars)
      end

      after do
        app_helper.clear_test_app_at(app_path)
      end
    end
  end
end

RSpec.configure do |config|
  config.extend ROR::BuildTestApp

  config.before(:suite) do
    ROR::BuildTestApp::Helper.clear_scaffolds
  end
end


text:
class UsersController < ApplicationController
  before_filter :skip_first_page, :only => :new

  def index
    @users = []
    User.all.each do |user|
      if user.referrals.count >= 1 && user.referrals.count < 5
        @users << user
      end
    end
  end

  def new
    @bodyId = 'home'
    @is_mobile = mobile_device?

    @user = User.new

    @ip_limit = false

    if params.has_key?(:ip_limit)
      @ip_limit = true
    end

    if Time.now.to_i > Time.parse("2015-09-06 00:00:00 -0800").to_i
      redirect_to "http://ultimate-bundles.com/healthy-living-bundle-2015/"
    else
      respond_to do |format|
        format.html # new.html.erb
      end
    end
  end

  def create
    unless params.has_key?(:user) && params[:user][:email] != '' && params[:user][:name] != ''
      return redirect_to :action => "new"
    end

    # Get user to see if they have already signed up
    @user = User.find_by_email(params[:user][:email]);

    # If user doesnt exist, make them, and attach referrer
    if @user.nil?

      cur_ip = IpAddress.find_by_address(request.env['HTTP_X_FORWARDED_FOR'])

      if !cur_ip
        cur_ip = IpAddress.create(
          :address => request.env['HTTP_X_FORWARDED_FOR'],
          :count => 0
        )
      end

      if cur_ip.count > 2
        return redirect_to :action => "new", :ip_limit => true
      else
        cur_ip.count = cur_ip.count + 1
        cur_ip.save
      end

      @user = User.new(:email => params[:user][:email], :name => params[:user][:name].titleize)

      @referred_by = User.find_by_referral_code(cookies[:h_ref])

      puts '------------'
      puts @referred_by.email if @referred_by
      puts params[:user][:email].inspect
      puts request.env['HTTP_X_FORWARDED_FOR'].inspect
      puts '------------'

      if !@referred_by.nil?
        @user.referrer = @referred_by
        @user.infusionsoft_affiliate_link = @referred_by.infusionsoft_affiliate_link
      end

      @user.name = @user.name.titleize
      @user.save

      if @referred_by
        @referred_by.delay.infusionsoft_referral
        #contact = Infusionsoft.contact_find_by_email(@referred_by.email, ['id'])
        #puts '------------ CALLING INFUSIONSOFT'
        #puts @referred_by.email
        #puts contact.inspect

        #if contact.count > 0 && @referred_by.referrals.count == 1
        #  ifs_result = Infusionsoft.contact_add_to_group(contact[0]["id"], 1216)
        #elsif contact.count > 0 && @referred_by.referrals.count == 5
        #  ifs_result = Infusionsoft.contact_add_to_group(contact[0]["id"], 1218)
        #elsif contact.count > 0 && @referred_by.referrals.count == 10
        #  ifs_result = Infusionsoft.contact_add_to_group(contact[0]["id"], 1220)
        #end

        #puts ifs_result
        #puts '------------'
      end

      #contact_id = Infusionsoft.contact_add_with_dup_check({:FirstName => @user.name, :Email => @user.email}, 'Email');
      #if contact_id
      #  Infusionsoft.contact_add_to_group(contact_id, 1208)
      #  Infusionsoft.email_optin(@user.email, "RAF App Opt-In")
      #end

      @user.delay.add_to_infusionsoft
    end

    # Send them over refer action
    respond_to do |format|
      if !@user.nil?
        cookies[:h_email] = { :value => @user.email }
        unless @user.infusionsoft_affiliate_link.blank?
          format.html { redirect_to @user.infusionsoft_affiliate_link }
        else
          format.html { redirect_to '/thank-you' }
        end
      else
        format.html { redirect_to root_path, :alert => "Something went wrong!" }
      end
    end
  end

  def thankyou
    email = cookies[:h_email]

    @bodyId = 'refer'
    @is_mobile = mobile_device?

    @user = User.find_by_email(email)

    respond_to do |format|
      if !@user.nil?
        format.html
      else
        format.html { redirect_to root_path, :alert => "Something went wrong!" }
      end
    end
  end

  def refer
    email = cookies[:h_email]

    @bodyId = 'refer'
    @is_mobile = mobile_device?

    @user = User.find_by_email(email)

    respond_to do |format|
      if !@user.nil?
        format.html
      else
        format.html { redirect_to root_path, :alert => "Something went wrong!" }
      end
    end
  end

  def policy

  end

  def redirect
    redirect_to root_path, :status => 404
  end

  private

  def user_params
    params.require(:episode).permit(:name, :email, :infusionsoft_affiliate_link)
  end

  def skip_first_page
    if !Rails.application.config.ended
      email = cookies[:h_email]
      if email and !User.find_by_email(email).nil?
        redirect_to '/thank-you'
      else
        cookies.delete :h_email
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>tsearch2</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Additional Supplied Modules"
HREF="contrib.html"><LINK
REL="PREVIOUS"
TITLE="test_parser"
HREF="test-parser.html"><LINK
REL="NEXT"
TITLE="unaccent"
HREF="unaccent.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29">

PostgreSQL 9.2.8 Documentation

Prev	Up	Appendix F. Additional Supplied Modules	Next

F.38. tsearch2

  The tsearch2 module provides backwards-compatible
  text search functionality for applications that used
  tsearch2 before text searching was integrated
  into core PostgreSQL in release 8.3.

F.38.1. Portability Issues

   Although the built-in text search features were based on
   tsearch2 and are largely similar to it,
   there are numerous small differences that will create portability
   issues for existing applications:

     Some functions' names were changed, for example rank
     to ts_rank.
     The replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module
     provides aliases having the old names.

     The built-in text search data types and functions all exist within
     the system schema <TT
CLASS="LITERAL"
>pg_catalog</TT
>.  In an installation using
     tsearch2, these objects would usually have been in
     the <TT
CLASS="LITERAL"
>public</TT
> schema, though some users chose to place them
     in a separate schema of their own.  Explicitly schema-qualified
     references to the objects will therefore fail in either case.
     The replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module
     provides alias objects that are stored in <TT
CLASS="LITERAL"
>public</TT
>
     (or another schema if necessary) so that such references will still work.

     There is no concept of a "current parser" or "current
     dictionary" in the built-in text search features, only of a current
     search configuration (set by the <TT
CLASS="VARNAME"
>default_text_search_config</TT
>
     parameter).  While the current parser and current dictionary were used
     only by functions intended for debugging, this might still pose
     a porting obstacle in some cases.
     The replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module emulates these
     additional state variables and provides backwards-compatible functions
     for setting and retrieving them.

   There are some issues that are not addressed by the replacement
   <TT
CLASS="LITERAL"
>tsearch2</TT
> module, and will therefore require
   application code changes in any case:

     The old tsearch2 trigger function allowed items in its
     argument list to be names of functions to be invoked on the text data
     before it was converted to <TT
CLASS="TYPE"
>tsvector</TT
> format.  This was removed
     as being a security hole, since it was not possible to guarantee that
     the function invoked was the one intended.  The recommended approach
     if the data must be massaged before being indexed is to write a custom
     trigger that does the work for itself.

     Text search configuration information has been moved into core
     system catalogs that are noticeably different from the tables used
     by tsearch2.  Any applications that examined
     or modified those tables will need adjustment.

     If an application used any custom text search configurations,
     those will need to be set up in the core
     catalogs using the new text search configuration SQL commands.
     The replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module offers a little
     bit of support for this by making it possible to load an old set
     of tsearch2 configuration tables into
     PostgreSQL 8.3.  (Without the module,
     it is not possible to load the configuration data because values in the
     <TT
CLASS="TYPE"
>regprocedure</TT
> columns cannot be resolved to functions.)
     While those configuration tables won't actually do
     anything, at least their contents will be available to be consulted
     while setting up an equivalent custom configuration in 8.3.

     The old reset_tsearch() and get_covers()
     functions are not supported.

     The replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module does not define
     any alias operators, relying entirely on the built-in ones.
     This would only pose an issue if an application used explicitly
     schema-qualified operator names, which is very uncommon.

F.38.2. Converting a pre-8.3 Installation

   The recommended way to update a pre-8.3 installation that uses
   tsearch2 is:

     Make a dump from the old installation in the usual way,
     but be sure not to use <TT
CLASS="LITERAL"
>-c</TT
> (<TT
CLASS="LITERAL"
>--clean</TT
>)
     option of pg_dump or pg_dumpall.

     In the new installation, create empty database(s) and install
     the replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module into each
     database that will use text search.  This must be done
     before loading the dump data!  If your old installation
     had the tsearch2 objects in a schema other
     than <TT
CLASS="LITERAL"
>public</TT
>, be sure to adjust the
     <TT
CLASS="COMMAND"
>CREATE EXTENSION</TT
> command so that the replacement
     objects are created in that same schema.

     Load the dump data.  There will be quite a few errors reported
     due to failure to recreate the original tsearch2
     objects.  These errors can be ignored, but this means you cannot
     restore the dump in a single transaction (eg, you cannot use
     pg_restore's <TT
CLASS="OPTION"
>-1</TT
> switch).

     Examine the contents of the restored tsearch2
     configuration tables (<TT
CLASS="STRUCTNAME"
>pg_ts_cfg</TT
> and so on), and
     create equivalent built-in text search configurations as needed.
     You may drop the old configuration tables once you've extracted
     all the useful information from them.

     Test your application.

   At a later time you may wish to rename application references
   to the alias text search objects, so that you can eventually
   uninstall the replacement <TT
CLASS="LITERAL"
>tsearch2</TT
> module.

F.38.3. References

   Tsearch2 Development Site
   http://www.sai.msu.su/~megera/postgres/gist/tsearch/V2/

Prev	Home	Next

test_parser	Up	unaccent


text:
package com.siyeh.ig.bitwise;

import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.siyeh.ig.LightInspectionTestCase;
import org.jetbrains.annotations.NotNull;

public class IncompatibleMaskInspectionTest extends LightCodeInsightFixtureTestCase {
  @Override
  protected String getBasePath() {
    return LightInspectionTestCase.INSPECTION_GADGETS_TEST_DATA_PATH + "com/siyeh/igtest/bitwise/incompatible_mask";
  }

  @NotNull
  @Override
  protected LightProjectDescriptor getProjectDescriptor() {
    return JAVA_8;
  }

  private void doTest() {
    myFixture.enableInspections(new IncompatibleMaskInspection());
    myFixture.testHighlighting(getTestName(false) + ".java");
  }

  public void testIncompatibleMask() {
    doTest();
  }

}


text:
package com.medmax.potholedetector.views;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;

import com.medmax.potholedetector.BaseSensorActivity;
import com.medmax.potholedetector.config.AppSettings;
import com.medmax.potholedetector.utilities.CSVHelper;
import com.medmax.potholedetector.utilities.DateTimeHelper;
import com.medmax.potholedetector.utilities.PotholeCSVContract;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;

/**
 * Created by Max Medina on 2017-07-06.
 */

public class LoggerActivity extends BaseSensorActivity {

    // Constants
    public final static String LOG_TAG = LoggerActivity.class.getSimpleName();

    // Variables
    protected boolean isLogging = false;
    private long mIdSeed = 0;
    private long mLogStartTime = 0;

    // Helpers
    private CSVHelper csvHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        csvHelper = new CSVHelper();
    }

    @Override
    public void onClick(View v) {
        isLogging = !isLogging;
        if (isLogging) {
            initLogger();
        } else {
            stopLogger();
        }
    }

    @Override
    protected void onAccelerometerSensorChanged(float[] values) {
        super.onAccelerometerSensorChanged(values);

        if(isLogging) {
            mTimestamp = (System.currentTimeMillis() - mLogStartTime) / 1000.0f;

            new LogTask(++mIdSeed, mTimestamp, mRawAccelerometerValues).execute();
        }
    }

    private void initLogger() {
        mLogStartTime = System.currentTimeMillis();
        mIdSeed = 0;
        if (!mPreferenceManager.isDebuggerOn()) {
            String fileName = String.format("%s_%s.%s",
                    AppSettings.POTHOLE_FILENAME,
                    DateTimeHelper.getCurrentDateTime("yyyy-MM-dd hh-mm-ss"),
                    AppSettings.CSV_EXTENSION_NAME
            );

            File exportDir = new File(Environment.getExternalStorageDirectory(), AppSettings.LOGGER_DIRECTORY);
            try {
                csvHelper.open(exportDir, fileName, true);
                csvHelper.setHeader(PotholeCSVContract.PotholeCSV.getHeaders());
            } catch (FileNotFoundException e) {
                sendToast("File was not found!");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopLogger() {
        if (!mPreferenceManager.isDebuggerOn() && csvHelper.isOpen()) {
            try {
                sendToast(String.format("file %s was created", csvHelper.getCurrentFileName()));
                csvHelper.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void logData(float timestamp, long logId, float[] data) throws IOException {
        if (csvHelper.isOpen()) {
            csvHelper.write(String.format(
                    Locale.US,
                    "%d,%s,%s,%.06f,%.6f,%.6f,%.6f",
                    logId,
                    DateTimeHelper.getCurrentDateTime("yyyy-MM-dd hh:mm:ss.SSS"),
                    mDeviceName,
                    timestamp,
                    data[0],
                    data[1],
                    data[2])
            );
        }
    }

    private class LogTask extends AsyncTask<Void, Void, Integer> {
        private long logId;
        private float timeStamp;
        private float[] data;

        LogTask(long logId, float timeStamp, float[] data) {
            this.logId = logId;
            this.timeStamp = timeStamp;
            this.data = data;
        }

        @Override
        protected Integer doInBackground(Void... params) {
            try {
                logData(timeStamp, logId, data);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }

    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>keycloak-parent</artifactId>
        <groupId>org.keycloak</groupId>
        <version>1.4.0.Final-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <name>Distribution Parent</name>
    <description/>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>distribution-pom</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>adapters</module>
        <module>demo-dist</module>
        <module>docs-dist</module>
        <module>examples-dist</module>
        <module>proxy-dist</module>
        <module>server-dist</module>
        <module>server-overlay</module>
        <module>src-dist</module>
        <module>subsystem-war</module>
        <module>feature-packs</module>
    </modules>
</project>


text:
package org.itachi.cms.util;

import org.itachi.cms.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;

import java.sql.SQLException;
import java.util.Map;

/**
 * Created by itachi on 2017/3/18.
 * User: itachi
 * Date: 2017/3/18
 * Time: 17:07
 */
public final class ThrowableUtil {
    private ThrowableUtil() {
    }

    public static ThrowableUtil getInstance() {
        return instance;
    }

    private static ThrowableUtil instance = new ThrowableUtil();
    private static final String MESSAGE = "message";
    private static final String CODE = "code";

    private static final Logger LOGGER = LoggerFactory.getLogger(ThrowableUtil.class);

    public HttpStatus handleThrowable(Map<String, Object> result, Throwable throwable) throws Exception {
        LOGGER.debug("==========handleThrowable==========");
        /*
        if (throwable instanceof HystrixBadRequestException) {
            return handleHystrixBadRequestException(result, (HystrixBadRequestException) throwable);
        }
        if (throwable instanceof HystrixRuntimeException) {
            return handleHystrixRuntimeException(result, (HystrixRuntimeException) throwable);
        }
        if (throwable instanceof HystrixTimeoutException) {
            return handleHystrixTimeoutException(result, (HystrixTimeoutException) throwable);
        }
        */
        return handleCommonThrowable(result, throwable);
    }

    /*
    private HttpStatus handleHystrixBadRequestException(Map<String, Object> result, HystrixBadRequestException e) throws Exception {
        LOGGER.debug("==========handleHystrixBadRequestException==========");
        String message = "Hystrix Observable Bad Request Exception!";
        if (e.getCause() != null && e.getCause() != e) {
            return handleException(result, e.getCause(), message);
        }
        return handleCommonThrowable(result, e, message);
    }

    private HttpStatus handleHystrixRuntimeException(Map<String, Object> result, HystrixRuntimeException e) {
        LOGGER.debug("==========handleHystrixRuntimeException==========");
        String message = "Hystrix Observable Runtime Exception!";
        if (e.getFallbackException() != null && e.getFallbackException() != e) {
            return handleException(result, e.getFallbackException(), message);
        }
        if (e.getCause() != null && e.getCause() != e) {
            return handleException(result, e.getCause(), message);
        }
        return handleCommonThrowable(result, e, message);
    }

    private HttpStatus handleHystrixTimeoutException(Map<String, Object> result, HystrixTimeoutException e) {
        LOGGER.debug("==========handleHystrixTimeoutException==========");
        String message = "Hystrix Observable Time Out Exception!";
        if (e.getCause() != null && e.getCause() != e) {
            return handleException(result, e.getCause(), message);
        }
        return handleCommonThrowable(result, e, message);
    }
    */

    public HttpStatus handleException(Map<String, Object> result, Throwable cause, String message) {
        try {
            if (cause instanceof BaseException) {
                return handleBaseException(result, (BaseException) cause);
            }
            if (cause instanceof SQLException) {
                return handleSQLException(result, (SQLException) cause);
            }
            if (cause instanceof BadSqlGrammarException) {
                return handleBadSqlGrammarException(result, (BadSqlGrammarException) cause);
            }
            /*
            if (cause instanceof HystrixBadRequestException) {
                return handleHystrixBadRequestException(result, (HystrixBadRequestException) throwable);
            }
            if (cause instanceof HystrixRuntimeException) {
                return handleHystrixRuntimeException(result, (HystrixRuntimeException) throwable);
            }
            if (cause instanceof HystrixTimeoutException) {
                return handleHystrixTimeoutException(result, (HystrixTimeoutException) throwable);
            }
            */
            return handleCommonThrowable(result, cause, message);
        } catch (Exception e) {
            return handleCommonThrowable(result, cause, message);
        }
    }

    public HttpStatus handleException(Map<String, Object> result, Throwable cause) {
        return handleException(result, cause, "web server handle data exception!");
    }

    private HttpStatus handleBadSqlGrammarException(Map<String, Object> result, BadSqlGrammarException cause) {
        LOGGER.error("====BadSqlGrammarException: {} \n\n {} \n\n {}", cause, cause.getSql(), cause.getMessage());
        result.put(CODE, (cause.getSQLException() == null || cause.getSQLException().getErrorCode() == 200) ? 417 : cause.getSQLException().getErrorCode());
        result.put(MESSAGE, cause.getMessage());
        return HttpStatus.SERVICE_UNAVAILABLE;
    }

    private HttpStatus handleSQLException(Map<String, Object> result, SQLException cause) {
        LOGGER.error("====SQLException: {} \n\n {} \n\n {}", cause, cause.getErrorCode(), cause.getMessage());
        result.put(CODE, cause.getErrorCode() == 200 ? 417 : cause.getErrorCode());
        result.put(MESSAGE, cause.getMessage());
        return HttpStatus.SERVICE_UNAVAILABLE;
    }

    private HttpStatus handleBaseException(Map<String, Object> result, BaseException cause) {
        HttpStatus status = HttpStatus.SERVICE_UNAVAILABLE;
        if (cause.getStatus() != null) {
            try {
                status = HttpStatus.valueOf(cause.getStatus().intValue());
            } catch (Exception e) {
                status = HttpStatus.SERVICE_UNAVAILABLE;
            }
        }
        result.put(CODE, cause.getCode());
        result.put(MESSAGE, cause.getMessage());
        return status;
    }

    public HttpStatus handleCommonThrowable(Map<String, Object> result, Throwable cause) {
        return handleCommonThrowable(result, cause, "web server handle data exception!");
    }

    public HttpStatus handleCommonThrowable(Map<String, Object> result, Throwable cause, String message) {
        if (cause != null && cause.getMessage() != null && !cause.getMessage().isEmpty()) {
            result.put(MESSAGE, cause.getMessage());
        } else if (message != null) {
            result.put(MESSAGE, message);
        }

        return HttpStatus.SERVICE_UNAVAILABLE;
    }
}


text:
<?php

require_once '../koneksi.php';

$id = $_GET['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$nama = $_POST['nama'];
$email = $_POST['email'];
$level = $_POST['level'];

$update = mysqli_query($koneksi, "UPDATE admin SET  username = '$username', password = '$password', nama = '$nama', email = '$email', level = '$level' WHERE id_admin = '$id'");

if ($update) {
    echo "<script>alert('Admin Berhasil Ubah'); window.location = '../kelola-admin.php';</script>";
  } else {
    // echo "Error: ". mysqli_error($koneksi);
    echo "<script>alert('Ubah Admin Gagal'); window.location = '../edit-admin.php?act=edit&id=".$id."';</script>";
  }

  mysqli_close($koneksi);

?>


text:
require 'celluloid'
require 'celluloid/io'
require 'celluloid/redis'

class RedisSubscriber
  include Celluloid::IO
  include Celluloid::Logger

  # The Redis connection used for the subscription.
  attr_reader :lredis

  # The Redis connection used to shut down the subscription.  Can also be used
  # to run the usual Redis commands.
  attr_reader :uredis

  # The pubsub channel name.
  attr_reader :channel

  # The shutdown sentinel.  Set at initialization.
  attr_reader :shutdown_message

  def initialize(redis_url, update_channel, *)
    @lredis = ::Redis.new(:url => redis_url, :driver => :celluloid)
    @uredis = ::Redis.new(:url => redis_url, :driver => :celluloid)
    @channel = update_channel
    @shutdown_message = "--ArchiveBot-Shutdown-#{object_id}--".freeze

    async.start
  end

  def on_shutdown
    # implement in a subclass
  end

  def on_receive(msg)
    # implement in a subclass
  end

  def start
    lredis.subscribe(channel) do |on|
      on.message do |chan, msg|
        if msg == shutdown_message
          info "#{self.class.name} shutting down"
          lredis.unsubscribe
          on_shutdown
        else
          on_receive(msg)
        end
      end
    end
  end

  def stop
    uredis.publish(channel, shutdown_message)
  end
end


text:
<?php

namespace DrinkWith\Bundle\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * User bundle
 *
 * @author Philippe Gibert <philippe.gibert@gmail.com>
 */
class DrinkWithUserBundle extends Bundle
{
    /**
     * (non-PHPdoc)
     * @see Symfony\Component\HttpKernel\Bundle.Bundle::getParent()
     *
     * @return string
     */
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
@protocol NZAlertViewDelegate <NSObject>

@optional

- (void)willPresentNZAlertView:(NZAlertView *)alertView;
- (void)didPresentNZAlertView:(NZAlertView *)alertView;

- (void)NZAlertViewWillDismiss:(NZAlertView *)alertView;
- (void)NZAlertViewDidDismiss:(NZAlertView *)alertView;

@end