text:
<?php

namespace Exporter\Test\Source;

use Exporter\Source\PDOStatementSourceIterator;

class PDOStatementSourceIteratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PDO
     */
    protected $dbh;

    /**
     * @var string
     */
    protected $pathToDb;

    public function setUp()
    {
        $this->pathToDb = tempnam(sys_get_temp_dir(), 'Sonata_exporter_');

        if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('the sqlite extension is not available');
        }

        if (is_file($this->pathToDb)) {
            unlink($this->pathToDb);
        }

        $this->dbh = new \PDO('sqlite:'.$this->pathToDb);
        $this->dbh->exec('CREATE TABLE `user` (`id` int(11), `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL )');

        $data = array(
            array(1, 'john', 'john@foo.bar'),
            array(2, 'john 2', 'john@foo.bar'),
            array(3, 'john 3', 'john@foo.bar'),
        );

        foreach ($data as $user) {
            $query = $this->dbh->prepare('INSERT INTO user (id, username, email) VALUES(?, ?, ?)');

            $query->execute($user);
        }
    }

    public function tearDown()
    {
        $this->dbh = null;

        if (is_file($this->pathToDb)) {
            unlink($this->pathToDb);
        }
    }

    public function testHandler()
    {
        $stm = $this->dbh->prepare('SELECT id, username, email FROM user');
        $stm->execute();

        $iterator = new PDOStatementSourceIterator($stm);

        $data = array();
        foreach ($iterator as $user) {
            $data[] = $user;
        }

        $this->assertEquals(3, count($data));
    }
}


text:
const request = require('request')
const getMessageList = (spreadsheetId) => {
  return new Promise((resolve, reject) => {
    const url = `https://spreadsheets.google.com/feeds/list/${spreadsheetId}/od6/public/values?alt=json`
    request.get(url, (error, response, body) => {
      if (error) {
        reject(error)
        return
      }

      const bodyAsJson = JSON.parse(body)
      const messages = bodyAsJson.feed.entry.map((entry) => {
        const date = entry.gsx$date.$t
        const message = entry.gsx$message.$t

        return {
          date,
          message
        }
      })

      resolve(messages)
    })
  })
}
export default getMessageList

redpajama_set_name: RedPajamaGithub


text:
/*
 * lifted from fs/ncpfs/getopt.c
 *
 * $FreeBSD: soc2013/dpl/head/sys/contrib/rdma/krping/getopt.h 178827 2008-05-05 18:35:55Z kmacy $
 */
#ifndef _KRPING_GETOPT_H
#define _KRPING_GETOPT_H

#define OPT_NOPARAM	1
#define OPT_INT		2
#define OPT_STRING	4
struct krping_option {
	const char *name;
	unsigned int has_arg;
	int val;
};

extern int krping_getopt(const char *caller, char **options, const struct krping_option *opts,
		      char **optopt, char **optarg, unsigned long *value);

#endif /* _KRPING_GETOPT_H */


text:
void register_IntersectionList_class();

#endif//IntersectionList_hpp__pyplusplus_wrapper


text:
export default (ngModule) => {
    require('./pagination.scss');
    require('./mobile').default(ngModule);
    require('./desktop').default(ngModule);
    require('./pagination').default(ngModule);
    require('./pagination.model').default(ngModule);

    /*if(MODE.ON_TTPC_TEST){
        require('./pagination.test')(ngModule);
    }*/

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="phpunit.php">
  <testsuites>
	<testsuite name="Core tests">
	  <directory suffix=".php">./tests/</directory>
	</testsuite>
  </testsuites>
</phpunit>


text:
FROM python:3.9-slim-buster

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

RUN apt-get update \
    # dependencies for building Python packages
    && apt-get install -y build-essential \
    # psycopg2 dependencies
    && apt-get install -y libpq-dev \
    # Translations dependencies
    && apt-get install -y gettext \
    # Uncomment below lines to enable Sphinx output to latex and pdf
    # && apt-get install -y texlive-latex-recommended \
    # && apt-get install -y texlive-fonts-recommended \
    # && apt-get install -y texlive-latex-extra \
    # && apt-get install -y latexmk \
    # cleaning up unused files
    && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
    && rm -rf /var/lib/apt/lists/*

# Requirements are installed here to ensure they will be cached.
COPY ./requirements /requirements
# All imports needed for autodoc.
RUN pip install -r /requirements/local.txt -r /requirements/production.txt

COPY ./infrastructure/local/docs/start /start-docs
RUN sed -i 's/\r$//g' /start-docs
RUN chmod +x /start-docs

WORKDIR /docs


text:
package org.apache.camel.component.olingo4.api.batch;

import java.util.Map;

/**
 * Batch Query part.
 */
public class Olingo4BatchQueryRequest extends Olingo4BatchRequest {

    private Map<String, String> queryParams;

    public Map<String, String> getQueryParams() {
        return queryParams;
    }

    public static Olingo4BatchQueryRequestBuilder resourcePath(String resourcePath) {
        if (resourcePath == null) {
            throw new IllegalArgumentException("resourcePath");
        }
        return new Olingo4BatchQueryRequestBuilder().resourcePath(resourcePath);
    }

    @Override
    public String toString() {
        return new StringBuilder("Batch Query Request{ ").append(resourceUri).append("/").append(resourcePath).append(", headers=").append(headers).append(", queryParams=")
            .append(queryParams).append('}').toString();
    }

    public static class Olingo4BatchQueryRequestBuilder {
        private Olingo4BatchQueryRequest request = new Olingo4BatchQueryRequest();

        public Olingo4BatchQueryRequest build() {
            // avoid later NPEs
            if (request.resourcePath == null) {
                throw new IllegalArgumentException("Null resourcePath");
            }
            return request;
        }

        public Olingo4BatchQueryRequestBuilder resourceUri(String resourceUri) {
            request.resourceUri = resourceUri;
            return this;
        }

        public Olingo4BatchQueryRequestBuilder resourcePath(String resourcePath) {
            request.resourcePath = resourcePath;
            return this;
        }

        public Olingo4BatchQueryRequestBuilder headers(Map<String, String> headers) {
            request.headers = headers;
            return this;
        }

        public Olingo4BatchQueryRequestBuilder queryParams(Map<String, String> queryParams) {
            request.queryParams = queryParams;
            return this;
        }
    }
}


text:
'use strict';

const ReflectApply = Reflect.apply;

// This function is borrowed from the function with the same name on V8 Extras'
// `utils` object. V8 implements Reflect.apply very efficiently in conjunction
// with the spread syntax, such that no additional special case is needed for
// function calls w/o arguments.
// Refs: https://github.com/v8/v8/blob/d6ead37d265d7215cf9c5f768f279e21bd170212/src/js/prologue.js#L152-L156
function uncurryThis(func) {
  return (thisArg, ...args) => ReflectApply(func, thisArg, args);
}

const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);

const TypedArrayProto_toStringTag =
    uncurryThis(
      Object.getOwnPropertyDescriptor(TypedArrayPrototype,
                                      Symbol.toStringTag).get);

// Cached to make sure no userland code can tamper with it.
const isArrayBufferView = ArrayBuffer.isView;

function isTypedArray(value) {
  return TypedArrayProto_toStringTag(value) !== undefined;
}

function isUint8Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Uint8Array';
}

function isUint8ClampedArray(value) {
  return TypedArrayProto_toStringTag(value) === 'Uint8ClampedArray';
}

function isUint16Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Uint16Array';
}

function isUint32Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Uint32Array';
}

function isInt8Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Int8Array';
}

function isInt16Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Int16Array';
}

function isInt32Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Int32Array';
}

function isFloat32Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Float32Array';
}

function isFloat64Array(value) {
  return TypedArrayProto_toStringTag(value) === 'Float64Array';
}

function isBigInt64Array(value) {
  return TypedArrayProto_toStringTag(value) === 'BigInt64Array';
}

function isBigUint64Array(value) {
  return TypedArrayProto_toStringTag(value) === 'BigUint64Array';
}

module.exports = {
  isArrayBufferView,
  isTypedArray,
  isUint8Array,
  isUint8ClampedArray,
  isUint16Array,
  isUint32Array,
  isInt8Array,
  isInt16Array,
  isInt32Array,
  isFloat32Array,
  isFloat64Array,
  isBigInt64Array,
  isBigUint64Array
};


text:
<?php

namespace Zend\XmlRpc\Request;

use Zend\Stdlib\ErrorHandler;
use Zend\XmlRpc\Fault;
use Zend\XmlRpc\Request as XmlRpcRequest;

/**
 * XmlRpc Request object -- Request via HTTP
 *
 * Extends {@link Zend\XmlRpc\Request} to accept a request via HTTP. Request is
 * built at construction time using a raw POST; if no data is available, the
 * request is declared a fault.
 */
class Http extends XmlRpcRequest
{
    /**
     * Array of headers
     * @var array
     */
    protected $headers;

    /**
     * Raw XML as received via request
     * @var string
     */
    protected $xml;

    /**
     * Constructor
     *
     * Attempts to read from php://input to get raw POST request; if an error
     * occurs in doing so, or if the XML is invalid, the request is declared a
     * fault.
     *
     */
    public function __construct()
    {
        ErrorHandler::start();
        $xml = file_get_contents('php://input');
        ErrorHandler::stop();
        if (!$xml) {
            $this->fault = new Fault(630);
            return;
        }

        $this->xml = $xml;

        $this->loadXml($xml);
    }

    /**
     * Retrieve the raw XML request
     *
     * @return string
     */
    public function getRawRequest()
    {
        return $this->xml;
    }

    /**
     * Get headers
     *
     * Gets all headers as key => value pairs and returns them.
     *
     * @return array
     */
    public function getHeaders()
    {
        if (null === $this->headers) {
            $this->headers = array();
            foreach ($_SERVER as $key => $value) {
                if ('HTTP_' == substr($key, 0, 5)) {
                    $header = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
                    $this->headers[$header] = $value;
                }
            }
        }

        return $this->headers;
    }

    /**
     * Retrieve the full HTTP request, including headers and XML
     *
     * @return string
     */
    public function getFullRequest()
    {
        $request = '';
        foreach ($this->getHeaders() as $key => $value) {
            $request .= $key . ': ' . $value . "\n";
        }

        $request .= $this->xml;

        return $request;
    }
}


text:
import { Marker } from './marker';

export abstract class SpiderClusterMarker extends Marker {

    /** The parent pushpin in which the spider pushpin is derived from. */
    public ParentMarker: Marker;

    /** The stick that connects the spider pushpin to the cluster. */
    public Stick: any;

}


text:
require File.join(File.dirname(__FILE__), "..", "spec_helper")

describe BlabberMouth::Validatable do

  class QuestionEmail
    include BlabberMouth
    include BlabberMouth::Validatable

    validates_presence_of :subject
  end

  class AnswerEmail
    include BlabberMouth
    include BlabberMouth::Validatable

    common_notifier_validations
  end

  before(:each) do
    @qe = QuestionEmail.new
    @ae = AnswerEmail.new
  end

  describe "common_notifier_validations" do

    it "should validates_presence_of :to, :from, :subject" do
      @ae.should_not be_valid
      @ae.errors.on(:to).should include("can't be empty")
      @ae.errors.on(:from).should include("can't be empty")
      @ae.errors.on(:subject).should include("can't be empty")
    end

    it "should validates_email_format_of of :to, :from" do
      @ae.to = "foo-bar.com"
      @ae.from = ["me-bar.com", "you-bar.com"]
      @ae.should_not be_valid
      @ae.errors.on(:to).should include("[foo-bar.com] is not valid")
      @ae.errors.on(:from).should include("[me-bar.com] is not valid")
      @ae.errors.on(:from).should include("[you-bar.com] is not valid")
    end

  end

  describe "validates_email_format_of" do

    class HelpEmail
      include BlabberMouth
      include BlabberMouth::Validatable

      validates_email_format_of :to

    end

    it "should validate that email address is the proper format" do
      he = HelpEmail.new
      he.to = "lksadjflsdjf"
      he.should_not be_valid
      he.errors.on(:to).should == "[lksadjflsdjf] is not valid"
      he.to = "mark@example.com"
      he.should be_valid
    end

    it "should validate that email address is the proper format in an array" do
      he = HelpEmail.new
      he.to = ["lksadjflsdjf", "skjfkljsdlj"]
      he.should_not be_valid
      he.errors.on(:to).should == ["[lksadjflsdjf] is not valid", "[skjfkljsdlj] is not valid"]
      he.to = ["MARK@example.com", "testing@example.com"]
      he.should be_valid
    end

  end

  it "should add any exceptions on deliver to the errors array" do
    @qe.errors.should be_empty
    @qe.subject = "hello world"
    @qe.deliver(:smtp).should == false
    @qe.errors.should_not be_empty
    @qe.errors.size.should == 1
    if RUBY_VERSION == '1.8.6'
      @qe.errors.on(:deliver).should include("mail destination not given")
    elsif RUBY_VERSION == '1.8.7'
      @qe.errors.on(:deliver).should include("could not get 3xx (554)")
    end
  end

  it "should not try and deliver! if the mail isn't valid" do
    @qe.errors.should be_empty
    lambda{@qe.deliver!(:smtp)}.should raise_error(RuntimeError)
  end

  it "should include the validatable library" do
    QuestionEmail.new.should be_is_a(::Validatable)
  end

end


text:
/*___INFO__MARK_BEGIN__*/
/*************************************************************************
 *
 *  The Contents of this file are made available subject to the terms of
 *  the Sun Industry Standards Source License Version 1.2
 *
 *  Sun Microsystems Inc., March, 2001
 *
 *
 *  Sun Industry Standards Source License Version 1.2
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.2 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *   The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *   Copyright: 2001 by Sun Microsystems, Inc.
 *
 *   All Rights Reserved.
 *
 ************************************************************************/
/*___INFO__MARK_END__*/
package org.ggf.drmaa;

/**
 * DRM system disengagement failed.
 * @author dan.templeton@sun.com
 * @since 0.5
 * @version 1.0
 */
public class DrmsExitException extends DrmaaException {
    /**
     * Creates a new instance of DrmsExitException without detail
     * message.
     */
    public DrmsExitException() {
    }

    /**
     * Constructs an instance of DrmsExitException with the specified detail message.
     * @param msg the detail message.
     */
    public DrmsExitException(String msg) {
        super(msg);
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dirent = void 0;
var constants_1 = require("./constants");
var encoding_1 = require("./encoding");
var S_IFMT = constants_1.constants.S_IFMT, S_IFDIR = constants_1.constants.S_IFDIR, S_IFREG = constants_1.constants.S_IFREG, S_IFBLK = constants_1.constants.S_IFBLK, S_IFCHR = constants_1.constants.S_IFCHR, S_IFLNK = constants_1.constants.S_IFLNK, S_IFIFO = constants_1.constants.S_IFIFO, S_IFSOCK = constants_1.constants.S_IFSOCK;
/**
 * A directory entry, like `fs.Dirent`.
 */
var Dirent = /** @class */ (function () {
    function Dirent() {
        this.name = '';
        this.mode = 0;
    }
    Dirent.build = function (link, encoding) {
        var dirent = new Dirent();
        var mode = link.getNode().mode;
        dirent.name = (0, encoding_1.strToEncoding)(link.getName(), encoding);
        dirent.mode = mode;
        return dirent;
    };
    Dirent.prototype._checkModeProperty = function (property) {
        return (this.mode & S_IFMT) === property;
    };
    Dirent.prototype.isDirectory = function () {
        return this._checkModeProperty(S_IFDIR);
    };
    Dirent.prototype.isFile = function () {
        return this._checkModeProperty(S_IFREG);
    };
    Dirent.prototype.isBlockDevice = function () {
        return this._checkModeProperty(S_IFBLK);
    };
    Dirent.prototype.isCharacterDevice = function () {
        return this._checkModeProperty(S_IFCHR);
    };
    Dirent.prototype.isSymbolicLink = function () {
        return this._checkModeProperty(S_IFLNK);
    };
    Dirent.prototype.isFIFO = function () {
        return this._checkModeProperty(S_IFIFO);
    };
    Dirent.prototype.isSocket = function () {
        return this._checkModeProperty(S_IFSOCK);
    };
    return Dirent;
}());
exports.Dirent = Dirent;
exports.default = Dirent;


text:
namespace MvcTemplate.Web.Infrastructure.Mapping
{
    using AutoMapper;

    public interface IHaveCustomMappings
    {
        void CreateMappings(IMapperConfigurationExpression configuration);
    }
}


text:
C++11 wrapper of [state-threads library](http://state-threads.sourceforge.net/)

`state-threads library` is a network preferred co-routines library, it is
written in C, in here a C++11 wrapper is offered, to simply working with
morder C++.

the project is proposed to run under Linux.

make sure the compiled `state-threads library` lib/include files are placed in
folder `st`.

to run the test, `gtest` is required.

to build the library and test, just:

1. create a folder named `build` in the project root directory.

2. change to the directory `build`.

3. run `cmake .. && make`

typical usage:

```cpp
stcpp::JoinableThread*  threads[COUNT_LOOP];
for(int i = 0; i < COUNT_LOOP; i++){
    threads[i] = new stcpp::JoinableThread(
        [](int a ) {
            stcpp::Thread::usleep(1);
            somework();
            count++;
            stcpp::Thread::exit();
        }, 100 );
}

for(int i = 0; i < COUNT_LOOP; i++){
    threads[i]->join();
}
```


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

<title>SignedMailValidatorTest (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.mail.smime.test

Class SignedMailValidatorTest

java.lang.Object

junit.framework.Assert

junit.framework.TestCase

org.bouncycastle.mail.smime.test.SignedMailValidatorTest

All Implemented Interfaces:

junit.framework.Test

public class SignedMailValidatorTest
extends junit.framework.TestCase

Constructor Summary

Constructors

Constructor and Description

SignedMailValidatorTest()

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] args)

void
setUp()

static junit.framework.Test
suite()

void
testCircular()

void
testCreateCertPath()

void
testExpired()

void
testExtendedReviewer()

void
testExtKeyUsage()

void
testKeyUsage()

void
testLongValidity()

void
testNoEmail()

void
testNotYetValid()

void
testRevoked()

void
testSelfSignedCert()

void
testShortKey()

Methods inherited from class junit.framework.TestCase

countTestCases, createResult, getName, run, run, runBare, runTest, setName, tearDown, toString

Methods inherited from class junit.framework.Assert

assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail

Methods inherited from class java.lang.Object

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

Constructor Detail

SignedMailValidatorTest

public SignedMailValidatorTest()

Method Detail

testShortKey

public void testShortKey()
                  throws java.lang.Exception

Throws:

java.lang.Exception

testKeyUsage

public void testKeyUsage()
                  throws java.lang.Exception

Throws:

java.lang.Exception

testExtKeyUsage

public void testExtKeyUsage()
                     throws java.lang.Exception

Throws:

java.lang.Exception

testNoEmail

public void testNoEmail()
                 throws java.lang.Exception

Throws:

java.lang.Exception

testNotYetValid

public void testNotYetValid()
                     throws java.lang.Exception

Throws:

java.lang.Exception

testExpired

public void testExpired()
                 throws java.lang.Exception

Throws:

java.lang.Exception

testRevoked

public void testRevoked()
                 throws java.lang.Exception

Throws:

java.lang.Exception

testLongValidity

public void testLongValidity()
                      throws java.lang.Exception

Throws:

java.lang.Exception

testSelfSignedCert

public void testSelfSignedCert()
                        throws java.lang.Exception

Throws:

java.lang.Exception

testCircular

public void testCircular()
                  throws java.lang.Exception

Throws:

java.lang.Exception

testExtendedReviewer

public void testExtendedReviewer()
                          throws java.lang.Exception

Throws:

java.lang.Exception

testCreateCertPath

public void testCreateCertPath()
                        throws java.lang.Exception

Throws:

java.lang.Exception

setUp

public void setUp()

Overrides:

setUp in class junit.framework.TestCase

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception

Throws:

java.lang.Exception

suite

public static junit.framework.Test suite()
                                  throws java.lang.Exception

Throws:

java.lang.Exception

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
class AstronomicalObjectType {
    static get NONE()  { return 0; }
    static get STAR()  { return 1; }
    static get SOLID() { return 2; }
    static get GAS()   { return 3; }
    static get SHIP()  { return 4; }
}

export default AstronomicalObjectType;


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}
  {{>includes/elements_scripts}}
{{/head}}

{{$propositionHeader}}
  {{>includes/propositional_navigation4}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

  {{>includes/phase_banner}}

    Step 2 of 7

    Your medical conditions

  <form id="medical-form" action="medical-conditions" method="get" class="form">

    <input type="hidden" id="flow" name="flow" value="{{flow}}"/>

Search for your condition

            <input type="text" id="search" name="search" list="conditions-list" value="{{conditions}}" placeholder="eg. diabetes" class="form-control" style="background-image: url(''); padding-left: 5px; width: 53%; display: inline;"/>

            <datalist id="conditions-list">
            <option value="Diabetes" />
            <option value="Diabetes (Type 1)"/>
            <option value="Diabetes (Type 2)"/>
            <option value="» DIAB1 (Online Form)"/>
            <option value="Epilepsy" />
            <option value="Glaucoma" />
            <option value="Dementia" />
            <option value="Pacemaker" />
            <option value="Stroke" />
            <option value="Sleep Apnoea" />
            <option value="Hypertension" />
            </datalist>

            <button style="top: 0;" type="submit" class="search-button-blue button">
              Search
            </button>

              You have not selected a medical condition.

              You searched for: {{search}}

              Did you mean ...

Diabetes

Diabetes (Type 1)

Diabetes (Type 2)

You have selected these condition(s):

            - Diabetes
            - Epilepsy
            - Glaucoma
            - Dementia
            - Pacemaker
            - Stroke
            - Sleep Apnoea
            - Hypertension

Or, add a common one:

+ Diabetes

+ Epilepsy

+ Glaucoma

+ Dementia

+ Pacemaker

+ Stroke

+ Sleep Apnoea

+ Hypertension

      <input id="continue" type="button" class="button" value="Save and continue" onclick="next()" disabled="true" />

Back

  </form>

{{/content}}

{{$bodyEnd}}
{{/bodyEnd}}

{{/govuk_template}}


text:
package model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

import res.Messages;

import utility.StringUtil;
import utility.TemporaryFileManager;

public class ClonesetMetricModel {
	private static final String[] predefinedMetricNames = new String[] {
		"LEN", "POP", "NIF", "RAD", "RNR", "TKS", "LOOP", "COND", "McCabe"
	};

	public static String fieldIDToName(int field) throws IndexOutOfBoundsException {
		return predefinedMetricNames[field];
	}

	public static int fieldNameToID(String name) throws IndexOutOfBoundsException {
		for (int field = 0; field < predefinedMetricNames.length; ++field) {
			if (predefinedMetricNames[field].equals(name)) {
				return field;
			}
		}
		throw new IndexOutOfBoundsException();
	}

	public static String[] getFieldNames() {
		return predefinedMetricNames.clone();
	}

	private static final String GEMXCLONESETMETRIC_TEMPFILE = TemporaryFileManager.createTemporaryFileName();

	private FileChannel cloneSetDataStore = null;

	private long maxCloneSetID;
	private long cloneSetIDCount;
	private int fields;
	private boolean[] isFloatingPoints;
	private String[] metricNames;
	private MetricsSummaryData summaryData;

	public void readCloneSetMetricFile(String path, long maxCloneSetID) throws DataFileReadError, IOException {
		this.maxCloneSetID = maxCloneSetID;
		cloneSetIDCount = 0;

		{
			File f = new File(GEMXCLONESETMETRIC_TEMPFILE);
			f.deleteOnExit();
			RandomAccessFile raFile = new RandomAccessFile(f, "rw"); //$NON-NLS-1$
			cloneSetDataStore = raFile.getChannel();
			cloneSetDataStore.truncate(0);
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF8")); //$NON-NLS-1$
		String line;
		line = reader.readLine();
		String supposedTitleLine = "CID" + "\t" + StringUtil.join(ClonesetMetricModel.getFieldNames(), "\t");
		if (! line.equals(supposedTitleLine)) { //$NON-NLS-1$
			throw new DataFileReadError("invalid clone-set metric file"); //$NON-NLS-1$
		}

		String[] ss = StringUtil.split(line, '\t');
		fields = ss.length - 1;
		metricNames = new String[fields];
		for (int i = 0; i < fields; ++i) {
			metricNames[i] = ss[i + 1];
		}
		isFloatingPoints = new boolean[fields];
		for (int i = 0; i < fields; ++i) {
			isFloatingPoints[i] = false;
		}

		ByteBuffer bbuffer = ByteBuffer.allocate(8/* size of double */ * fields);
		bbuffer.order(ByteOrder.LITTLE_ENDIAN);
		{
			ByteBuffer clearBuffer = ByteBuffer.allocate(8/* size of double */ * fields);
			clearBuffer.order(ByteOrder.LITTLE_ENDIAN);
			clearBuffer.putDouble(-1.0);
			for (int i = 1; i < fields; ++i) {
				clearBuffer.putDouble(0.0);
			}
			long pos = 0;
			for (long d = 0; d < maxCloneSetID + 1; ++d) {
				cloneSetDataStore.position(pos);
				clearBuffer.rewind();
				cloneSetDataStore.write(clearBuffer);
				pos += 8 * fields;
			}
		}
		double[] values = new double[fields];
		while (true) {
			line = reader.readLine();
			if (line == null) {
				throw new DataFileReadError(Messages.getString("gemx.CloneSetMetricModel.S_INVALID_CLONE_SET_METRIC_FILE")); //$NON-NLS-1$
			}
			String[] subs = StringUtil.split(line, '\t');
			if (subs[0].equals("ave.")) { //$NON-NLS-1$
				break;
			}
			if (subs.length != fields + 1) {
				throw new DataFileReadError(Messages.getString("gemx.CloneSetMetricModel.S_INVALID_CLONE_SET_METRIC_FILE")); //$NON-NLS-1$
			}
			long cloneSetID = Long.parseLong(subs[0]);
			if (! (0 <= cloneSetID && cloneSetID <= maxCloneSetID)) {
				throw new DataFileReadError(Messages.getString("gemx.CloneSetMetricModel.S_INVALID_CLONE_SET_ID_IN_CLONE_SET_METRIC_FILE")); //$NON-NLS-1$
			}
			++cloneSetIDCount;
			for (int i = 0; i < fields; ++i) {
				double v = Double.parseDouble(subs[i + 1]);
				if (Math.floor(v) != v) {
					isFloatingPoints[i] = true;
				}
				values[i] = v;
			}

			// write data
			long csPosition = cloneSetID * 8/* size of double */ * fields;
			bbuffer.clear();
			cloneSetDataStore.position(csPosition);
			cloneSetDataStore.read(bbuffer);
			double clen = bbuffer.getDouble(0);
			if (clen == -1.0) {
				bbuffer.clear();
				for (int i = 0; i < fields; ++i) {
					bbuffer.putDouble(values[i]);
				}
				bbuffer.rewind();
				cloneSetDataStore.position(csPosition);
				cloneSetDataStore.write(bbuffer);
			}
		}
		summaryData = new MetricsSummaryData();
		summaryData.read(fields, reader, line);

		reader.close();
	}

	public int getFieldCount() {
		return fields;
	}

	long getCloneSetIDCount() {
		return cloneSetIDCount;
	}

	long getMaxCloneSetID() {
		return maxCloneSetID;
	}

	public double getNthMetricDataOfCloneSet(long cloneSetID, int fieldIndex) throws IndexOutOfBoundsException {
		if (cloneSetID > maxCloneSetID) {
			throw new IndexOutOfBoundsException();
		}
		if (! (0 <= fieldIndex && fieldIndex < fields)) {
			throw new IndexOutOfBoundsException();
		}

		ByteBuffer bbuffer = ByteBuffer.allocate(8/* size of double */);
		bbuffer.order(ByteOrder.LITTLE_ENDIAN);

		try {
			long csPosition = (cloneSetID * fields + fieldIndex) * 8/* size of double */;

			bbuffer.clear();
			cloneSetDataStore.position(csPosition);
			cloneSetDataStore.read(bbuffer);
			bbuffer.rewind();

			double value = bbuffer.getDouble(0);
			return value;
		} catch (IOException e) {
			return 0.0;
		}
	}

	private double[] getMetricDataOfCloneSet_i(long cloneSetID) throws IndexOutOfBoundsException {
		if (cloneSetID > maxCloneSetID) {
			throw new IndexOutOfBoundsException();
		}

		ByteBuffer bbuffer = ByteBuffer.allocate(8/* size of double */ * fields);
		bbuffer.order(ByteOrder.LITTLE_ENDIAN);

		try {
			long csPosition = cloneSetID * 8/* size of double */ * fields;

			bbuffer.clear();
			cloneSetDataStore.position(csPosition);
			cloneSetDataStore.read(bbuffer);
			bbuffer.rewind();

			double[] values = new double[fields];
			for (int i = 0; i < fields; ++i) {
				values[i] = bbuffer.getDouble(i * 8/* size of double */);
			}

			return values;
		} catch (IOException e) {
			double[] values = new double[fields];
			return values;
		}
	}

	public double[] getMetricDataOfCloneSet(long cloneSetID) throws IndexOutOfBoundsException {
		return getMetricDataOfCloneSet_i(cloneSetID);
	}

	public void dispose() {
		if (cloneSetDataStore != null) {
			try {
				cloneSetDataStore.close();
			} catch (IOException e) {
				// can do nothing
			}
		}
	}

	public boolean isFlotingPoint(int metricIndex) {
		assert 0 <= metricIndex && metricIndex < isFloatingPoints.length;
		return isFloatingPoints[metricIndex];
	}

	public boolean[] getFlotingPointValueMap() {
		return isFloatingPoints.clone();
	}

	public String getMetricName(int metricIndex) {
		assert 0 <= metricIndex && metricIndex < metricNames.length;
		return metricNames[metricIndex];
	}

	public String[] getMetricNames() {
		return metricNames.clone();
	}

	public MetricsSummaryData getSummaryData() {
		return summaryData.clone();
	}

	public double getNthRelativeMetricDataOfCloneSet(long cloneSetID, int fieldIndex) throws IndexOutOfBoundsException {
		double value = getNthMetricDataOfCloneSet(cloneSetID, fieldIndex);
		return summaryData.toRelativeValue(fieldIndex, value);
	}

	public double[] getRelativeMetricDataOfCloneSet(long cloneSetID) throws IndexOutOfBoundsException {
		if (! (0 <= cloneSetID && cloneSetID <= maxCloneSetID)) {
			throw new IndexOutOfBoundsException();
		}
		double[] values = getMetricDataOfCloneSet_i(cloneSetID);
		double[] vs = new double[fields];
		for (int i = 0; i < fields; ++i) {
			vs[i] = summaryData.toRelativeValue(i, values[i]);
		}
		return vs;
	}
}


text: Slurm Image to inherite a slurm controler and client from


text:
  struct IPCZ_ALIGN(8) name##_Params {              \
    name##_Params();                                \
    ~name##_Params();                               \
    id_decl;                                        \
    version_decl;                                   \
    internal::StructHeader header;

#define IPCZ_MSG_END() \
  }                    \
  ;

#define IPCZ_MSG_PARAM(type, name) type name;
#define IPCZ_MSG_PARAM_ARRAY(type, name) uint32_t name;
#define IPCZ_MSG_PARAM_DRIVER_OBJECT(name) uint32_t name;
#define IPCZ_MSG_PARAM_DRIVER_OBJECT_ARRAY(name) \
  internal::DriverObjectArrayData name;


text:
package io.appium.java_client.pagefactory_tests;

import static io.appium.java_client.pagefactory.LocatorGroupStrategy.ALL_POSSIBLE;
import static java.time.Duration.ofSeconds;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidElement;

import io.appium.java_client.android.BaseAndroidTest;

import io.appium.java_client.pagefactory.AndroidBy;
import io.appium.java_client.pagefactory.AndroidFindAll;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.AndroidFindBys;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import io.appium.java_client.pagefactory.HowToUseLocators;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import java.util.ArrayList;
import java.util.List;

public class AndroidPageObjectTest extends BaseAndroidTest {

    private boolean populated = false;

    @FindBy(className = "android.widget.TextView")
    private List<WebElement> textVieWs;

    @AndroidFindBy(className = "android.widget.TextView")
    private List<WebElement> androidTextViews;

    @AndroidFindBy(className = "android.widget.TextView")
    private List<WebElement> androidOriOsTextViews;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private List<WebElement> androidUIAutomatorViews;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private List<MobileElement> mobileElementViews;

    @FindBy(className = "android.widget.TextView")
    private List<MobileElement> mobiletextVieWs;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private List<RemoteWebElement> remoteElementViews;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(className = "android.widget.TextView")
    private List<WebElement> chainElementViews;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/text1")
    private List<WebElement> chainAndroidOrIOSUIAutomatorViews;

    @FindBy(id = "android:id/text1")
    private WebElement textView;

    @AndroidFindBy(className = "android.widget.TextView")
    private WebElement androidTextView;

    @AndroidFindBy(className = "android.widget.TextView")
    private WebElement androidOriOsTextView;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private WebElement androidUIAutomatorView;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private MobileElement mobileElementView;

    @FindBy(className = "android.widget.TextView")
    private MobileElement mobiletextVieW;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")")
    private RemoteWebElement remotetextVieW;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(className = "android.widget.TextView")
    private WebElement chainElementView;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/text1")
    private WebElement chainAndroidOrIOSUIAutomatorView;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/text1")
    private AndroidElement androidElementView;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/text1")
    private List<AndroidElement> androidElementViews;

    @HowToUseLocators(androidAutomation = ALL_POSSIBLE)
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/Fakecontent\")")
    @AndroidFindBy(id = "android:id/Faketext1")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    //by this locator element is found
    @AndroidFindBy(id = "android:id/FakeId")
    private List<WebElement> findAllElementViews;

    @HowToUseLocators(androidAutomation = ALL_POSSIBLE)
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/Fakecontent\")")
    @AndroidFindBy(id = "android:id/Faketext1")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    //by this locator element is found
    @AndroidFindBy(id = "android:id/FakeId")
    private WebElement findAllElementView;

    @AndroidFindBy(id = "android:id/text1")
    private WebElement textAndroidId;

    @FindBy(css = "e.e1.e2")
    private List<WebElement> elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy;

    @FindBy(css = "e.e1.e2")
    private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy;

    @FindBy(id = "fakeId")
    private WebElement fakeElement;

    @FindBy(id = "fakeId")
    private List<WebElement> fakeElements;

    @CacheLookup
    @FindBy(className = "android.widget.TextView")
    private MobileElement cached;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/Faketext1")
    @AndroidFindBy(id = "android:id/text1")
    private WebElement elementFoundByInvalidChainedSelector;

    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")
    @AndroidFindBy(id = "android:id/Faketext1")
    @AndroidFindBy(id = "android:id/text1")
    private List<WebElement> elementsFoundByInvalidChainedSelector;

    @AndroidFindBy(id = "android:id/text1", priority = 2)
    @AndroidFindAll(value = {
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"),
            @AndroidBy(id = "android:id/fakeId")}, priority = 1)
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    private AndroidElement androidElementViewFoundByMixedSearching;

    @AndroidFindBy(id = "android:id/text1", priority = 2)
    @AndroidFindAll(value = {
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"),
            @AndroidBy(id = "android:id/fakeId")}, priority = 1)
    @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")")
    private List<AndroidElement> androidElementsViewFoundByMixedSearching;

    @AndroidFindBys({
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")", priority = 1),
            @AndroidBy(className = "android.widget.FrameLayout")})
    @AndroidFindBys({@AndroidBy(id = "android:id/text1", priority = 1),
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")})
    private AndroidElement androidElementViewFoundByMixedSearching2;

    @AndroidFindBys({
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")", priority = 1),
            @AndroidBy(className = "android.widget.FrameLayout")})
    @AndroidFindBys({
            @AndroidBy(id = "android:id/text1", priority = 1),
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")")})
    private List<AndroidElement> androidElementsViewFoundByMixedSearching2;

    @HowToUseLocators(androidAutomation = ALL_POSSIBLE)
    @AndroidFindBy(id = "android:id/fakeId1")
    @AndroidFindBy(id = "android:id/fakeId2", priority = 1)
    @AndroidFindBys(value = {
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")", priority = 1),
            @AndroidBy(id = "android:id/text1", priority = 3),
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")", priority = 2),
            @AndroidBy(className = "android.widget.FrameLayout")}, priority = 2)
    @AndroidFindBy(id = "android:id/fakeId3", priority = 3)
    @AndroidFindBy(id = "android:id/fakeId4", priority = 4)
    private AndroidElement androidElementViewFoundByMixedSearching3;

    @HowToUseLocators(androidAutomation = ALL_POSSIBLE)
    @AndroidFindBy(id = "android:id/fakeId1")
    @AndroidFindBy(id = "android:id/fakeId2", priority = 1)
    @AndroidFindBys(value = {
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")", priority = 1),
            @AndroidBy(id = "android:id/text1", priority = 3),
            @AndroidBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")", priority = 2),
            @AndroidBy(className = "android.widget.FrameLayout")}, priority = 2)
    @AndroidFindBy(id = "android:id/fakeId3", priority = 3)
    @AndroidFindBy(id = "android:id/fakeId4", priority = 4)
    private List<AndroidElement> androidElementsViewFoundByMixedSearching3;

    /**
     * The setting up.
     */
    @Before public void setUp() {
        if (!populated) {
            //This time out is set because test can be run on slow Android SDK emulator
            PageFactory.initElements(new AppiumFieldDecorator(driver, ofSeconds(5)), this);
        }

        populated = true;
    }

    @Test public void findByElementsTest() {
        assertNotEquals(0, textVieWs.size());
    }

    @Test public void findByElementTest() {
        assertNotEquals(null, textView.getAttribute("text"));
    }

    @Test public void androidFindByElementsTest() {
        assertNotEquals(0, androidTextViews.size());
    }

    @Test public void androidFindByElementTest() {
        assertNotEquals(null, androidTextView.getAttribute("text"));
    }

    @Test public void androidOrIOSFindByElementsTest() {
        assertNotEquals(0, androidOriOsTextViews.size());
    }

    @Test public void androidOrIOSFindByElementTest() {
        assertNotEquals(null, androidOriOsTextView.getAttribute("text"));
    }

    @Test public void androidFindByUIAutomatorElementsTest() {
        assertNotEquals(0, androidUIAutomatorViews.size());
    }

    @Test public void androidFindByUIAutomatorElementTest() {
        assertNotEquals(null, androidUIAutomatorView.getAttribute("text"));
    }

    @Test public void areMobileElementsTest() {
        assertNotEquals(0, mobileElementViews.size());
    }

    @Test public void isMobileElementTest() {
        assertNotEquals(null, mobileElementView.getAttribute("text"));
    }

    @Test public void areMobileElementsFindByTest() {
        assertNotEquals(0, mobiletextVieWs.size());
    }

    @Test public void isMobileElementFindByTest() {
        assertNotEquals(null, mobiletextVieW.getAttribute("text"));
    }

    @Test public void areRemoteElementsTest() {
        assertNotEquals(0, remoteElementViews.size());
    }

    @Test public void isRemoteElementTest() {
        assertNotEquals(null, remotetextVieW.getAttribute("text"));
    }

    @Test public void androidChainSearchElementsTest() {
        assertNotEquals(0, chainElementViews.size());
    }

    @Test public void androidChainSearchElementTest() {
        assertNotEquals(null, chainElementView.getAttribute("text"));
    }

    @Test public void androidOrIOSFindByElementsTestChainSearches() {
        assertNotEquals(0, chainAndroidOrIOSUIAutomatorViews.size());
    }

    @Test public void androidOrIOSFindByElementTestChainSearches() {
        assertNotEquals(null, chainAndroidOrIOSUIAutomatorView.getAttribute("text"));
    }

    @Test public void isAndroidElementTest() {
        assertNotEquals(null, androidElementView.getAttribute("text"));
    }

    @Test public void areAndroidElementsTest() {
        assertNotEquals(0, androidElementViews.size());
    }

    @Test public void findAllElementTest() {
        assertNotEquals(null, findAllElementView.getAttribute("text"));
    }

    @Test public void findAllElementsTest() {
        assertNotEquals(0, findAllElementViews.size());
    }

    @Test public void findByAndroidAnnotationOnlyTest() {
        assertNotEquals(null, textAndroidId.getAttribute("text"));
    }

    @Test(expected = NoSuchElementException.class) public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy() {
        assertNotNull(
                elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text"));
    }

    @Test public void checkThatTestWillNotBeFailedBecauseOfInvalidFindByList() {
        assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size());
    }

    @Test public void checkThatClassObjectMethodsDoNotInvokeTheSearching() {
        assertTrue(AndroidElement.class.isAssignableFrom(fakeElement.getClass()));
        assertNotEquals(AndroidElement.class, fakeElement.getClass());
        assertEquals(driver, ((WrapsDriver) fakeElement).getWrappedDriver());
    }

    @Test public void checkThatClassObjectMethodsDoNotInvokeTheSearchingOfElementLest() {
        assertTrue(List.class.isAssignableFrom(fakeElements.getClass()));
        assertNotEquals(ArrayList.class, fakeElements.getClass());
    }

    @Test public void checkCached() {
        assertEquals(cached.getId(), cached.getId());
    }

    @Test(expected = NoSuchElementException.class)
    public void checkThatElementSearchingThrowsExpectedExceptionIfChainedLocatorIsInvalid() {
        assertNotNull(elementFoundByInvalidChainedSelector.getAttribute("text"));
    }

    @Test public void checkThatListSearchingWorksIfChainedLocatorIsInvalid() {
        assertEquals(0, elementsFoundByInvalidChainedSelector.size());
    }

    @Test public void checkMixedElementSearching1() {
        assertNotNull(androidElementViewFoundByMixedSearching.getAttribute("text"));
    }

    @Test public void checkMixedElementsSearching1() {
        assertNotEquals(0, androidElementsViewFoundByMixedSearching.size());
    }

    @Test public void checkMixedElementSearching2() {
        assertNotNull(androidElementViewFoundByMixedSearching2.getAttribute("text"));
    }

    @Test public void checkMixedElementsSearching2() {
        assertNotEquals(0, androidElementsViewFoundByMixedSearching2.size());
    }

    @Test public void checkMixedElementSearching3() {
        assertNotNull(androidElementViewFoundByMixedSearching3.getAttribute("text"));
    }

    @Test public void checkMixedElementsSearching3() {
        assertNotEquals(0, androidElementsViewFoundByMixedSearching3.size());
    }
}


text:
    <title>kalshagar - ardColorLamp</title>
    <link rel="stylesheet" href="static/style.css" type="text/css" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

 Feature list

See the page How to generate a colormixer about how to make that nice color mixer.

        Feature

        Comment

        Priority

        Version Impl

        other

        Select color from HSL/HSV

        Behind the touchscreen, set a image (printed) with a HSL/HSV space and transform this to RGB according position. I just need the formula to draw a HSL/HSV space...

        Med

        Sensitive to sound

        Add a mic and make the stuff sensitive to sound (easy : average volumne, hard : color according frequencies)

        Low

        Add modes accessible by buttons

Sine : around the selected color, make the brightness evolve slowly like a sine

Random : like the MagicSango, from the start color, evolve randomly

Flame : make the brightness evolve randomly while keeping the base color (little amplitude but quite fast to emulate a flame pulse)

Stable : nothing (but you need it)

1 hour fade out : light will slowly turn off for 1h and the stop the whole arduino and led completely

        Med/High

 Pictures

Top part : Color for the lamp.

Bottom part : brightness.

 Interesting links

 RGB colors and HSV

http://www.johngineer.com/blog/?p=1022

http://academe.co.uk/2012/04/arduino-cycling-through-colours-of-the-rainbow/

http://julioterra.com/journal/2011/08/hsb-to-rgb-arduino-library/

 Leds light effects

Candle like led effect http://fightpc.blogspot.com/2008/03/arduino-mood-light.html

 Leds

BlinkM MaxM RGB superpower led http://www.switch-science.com/products/detail.php?product_id=104 http://www.sparkfun.com/commerce/product_info.php?products_id=9000

ThingM Forum http://getsatisfaction.com/thingm

... or leds one by one ? http://www.sparkfun.com/commerce/product_info.php?products_id=9000

 DS Touchscreen and colorpicker

Touchscreen : see my dedicated page here Arduino and a Nintendo DS touch screen

C%20%20 Color picker with HSL 2 RGB explanation http://www.codeproject.com/KB/miscctrl/CPicker.aspx

Color wheel formula http://www.codeproject.com/KB/miscctrl/colorwheelv1.aspx

A la Photoshop with a color hexagon http://www.codeproject.com/KB/miscctrl/colorspace.aspx

http://en.wikipedia.org/wiki/HSL_color_space


text:
<?xml version="1.0" encoding="utf-8"?>

<appendix xml:id="xmlreader.constants" xmlns="http://docbook.org/ns/docbook">
 &reftitle.constants;
 &extension.constants;
  <warning>
   <para>
    XMLReader uses class constants since PHP 5.1. Prior releases use global
    constants in the form <constant>XMLREADER_ELEMENT</constant>.
   </para>
  </warning>

   <title>XMLReader Node Types</title>
   <tgroup cols="3">

     <row>
      <entry>Constant</entry>
      <entry>Value</entry>
      <entry>Description</entry>
     </row>

     <row xml:id="xmlreader.constants.none">
      <entry>
       <constant>XMLReader::NONE</constant>
       (<type>integer</type>)
      </entry>
      <entry>0</entry>
      <entry>No node type</entry>
     </row>
     <row xml:id="xmlreader.constants.element">
      <entry>
       <constant>XMLReader::ELEMENT</constant>
       (<type>integer</type>)
      </entry>
      <entry>1</entry>
      <entry>Start element</entry>
     </row>
     <row xml:id="xmlreader.constants.attribute">
      <entry>
       <constant>XMLReader::ATTRIBUTE</constant>
      (<type>integer</type>)
      </entry>
      <entry>2</entry>
      <entry>Attribute node</entry>
     </row>
     <row xml:id="xmlreader.constants.text">
      <entry>
       <constant>XMLReader::TEXT</constant>
       (<type>integer</type>)
      </entry>
      <entry>3</entry>
      <entry>Text node</entry>
     </row>
     <row xml:id="xmlreader.constants.cdata">
      <entry>
       <constant>XMLReader::CDATA</constant>
       (<type>integer</type>)
      </entry>
      <entry>4</entry>
      <entry>CDATA node</entry>
     </row>
     <row xml:id="xmlreader.constants.entity-ref">
      <entry>
       <constant>XMLReader::ENTITY_REF</constant>
       (<type>integer</type>)
      </entry>
      <entry>5</entry>
      <entry>Entity Reference node</entry>
     </row>
     <row xml:id="xmlreader.constants.entity">
      <entry>
       <constant>XMLReader::ENTITY</constant>
       (<type>integer</type>)
      </entry>
      <entry>6</entry>
      <entry>Entity Declaration node</entry>
     </row>
     <row xml:id="xmlreader.constants.pi">
      <entry>
       <constant>XMLReader::PI</constant>
       (<type>integer</type>)
      </entry>
      <entry>7</entry>
      <entry>Processing Instruction node</entry>
     </row>
     <row xml:id="xmlreader.constants.comment">
      <entry>
       <constant>XMLReader::COMMENT</constant>
       (<type>integer</type>)
      </entry>
      <entry>8</entry>
      <entry>Comment node</entry>
     </row>
     <row xml:id="xmlreader.constants.doc">
      <entry>
       <constant>XMLReader::DOC</constant>
       (<type>integer</type>)
      </entry>
      <entry>9</entry>
      <entry>Document node</entry>
     </row>
     <row xml:id="xmlreader.constants.doc-type">
      <entry>
       <constant>XMLReader::DOC_TYPE</constant>
       (<type>integer</type>)
      </entry>
      <entry>10</entry>
      <entry>Document Type node</entry>
     </row>
     <row xml:id="xmlreader.constants.doc-fragment">
      <entry>
       <constant>XMLReader::DOC_FRAGMENT</constant>
       (<type>integer</type>)
      </entry>
      <entry>11</entry>
      <entry>Document Fragment node</entry>
     </row>
     <row xml:id="xmlreader.constants.notation">
      <entry>
       <constant>XMLReader::NOTATION</constant>
       (<type>integer</type>)
      </entry>
      <entry>12</entry>
      <entry>Notation node</entry>
     </row>
     <row xml:id="xmlreader.constants.whitespace">
      <entry>
       <constant>XMLReader::WHITESPACE</constant>
       (<type>integer</type>)
      </entry>
      <entry>13</entry>
      <entry>Whitespace node</entry>
     </row>
     <row xml:id="xmlreader.constants.significant-whitespace">
      <entry>
       <constant>XMLReader::SIGNIFICANT_WHITESPACE</constant>
       (<type>integer</type>)
      </entry>
      <entry>14</entry>
      <entry>Significant Whitespace node</entry>
     </row>
     <row xml:id="xmlreader.constants.end-element">
      <entry>
       <constant>XMLReader::END_ELEMENT</constant>
       (<type>integer</type>)
      </entry>
      <entry>15</entry>
      <entry>End Element</entry>
     </row>
     <row xml:id="xmlreader.constants.end-entity">
      <entry>
       <constant>XMLReader::END_ENTITY</constant>
       (<type>integer</type>)
      </entry>
      <entry>16</entry>
      <entry>End Entity</entry>
     </row>
     <row xml:id="xmlreader.constants.xml-declaration">
      <entry>
       <constant>XMLReader::XML_DECLARATION</constant>
       (<type>integer</type>)
      </entry>
      <entry>17</entry>
      <entry>XML Declaration node</entry>
     </row>

   </tgroup>

   <title>XMLReader Parser Options</title>
   <tgroup cols="3">

     <row>
      <entry>Constant</entry>
      <entry>Value</entry>
      <entry>Description</entry>
     </row>

     <row xml:id="xmlreader.constants.loaddtd">
      <entry>
       <constant>XMLReader::LOADDTD</constant>
       (<type>integer</type>)
      </entry>
      <entry>1</entry>
      <entry>Load DTD but do not validate</entry>
     </row>
     <row xml:id="xmlreader.constants.defaultattrs">
      <entry>
       <constant>XMLReader::DEFAULTATTRS</constant>
       (<type>integer</type>)
      </entry>
      <entry>2</entry>
      <entry>Load DTD and default attributes but do not validate</entry>
     </row>
     <row xml:id="xmlreader.constants.validate">
      <entry>
       <constant>XMLReader::VALIDATE</constant>
       (<type>integer</type>)
      </entry>
      <entry>3</entry>
      <entry>Load DTD and validate while parsing</entry>
     </row>
     <row xml:id="xmlreader.constants.subst-entities">
      <entry>
       <constant>XMLReader::SUBST_ENTITIES</constant>
       (<type>integer</type>)
      </entry>
      <entry>4</entry>
      <entry>Substitute entities and expand references</entry>
     </row>

   </tgroup>

</appendix>


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ModColumnInHrPositionTasks extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('hr_position_tasks', function (Blueprint $table) {
            $table->dropForeign('hr_position_tasks_position_name_foreign');
            $table->renameColumn('position_name', 'position_id');
            $table->foreign('position_id')
                  ->references('id')
                  ->on('hr_position')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('hr_position_tasks', function (Blueprint $table) {
            $table->dropForeign('hr_position_tasks_position_id_foreign');
            $table->renameColumn('position_id', 'position_name');
            $table->foreign('position_name')
                  ->references('position_name')
                  ->on('hr_position')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }
}


text:
/**
 *
 */
package cn.ieclipse.af.demo.sample.orm.bean;

import java.io.Serializable;

import cn.ieclipse.aorm.annotation.Column;
import cn.ieclipse.aorm.annotation.Table;

/**
 * @author Jamling
 *
 */
@Table(name = "course")
public class Course implements Serializable {

    private static final long serialVersionUID = 4957742859044875650L;

    @Column(name = "_id", id = true)
    private long id;

    @Column(name = "_name")
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
package org.openspaces.core;

import com.gigaspaces.async.AsyncFuture;
import com.gigaspaces.async.AsyncFutureListener;
import com.gigaspaces.metadata.SpaceTypeDescriptor;
import com.gigaspaces.metadata.index.AddTypeIndexesResult;
import com.gigaspaces.metadata.index.SpaceIndex;

/**
 * Interface encapsulating operations for getting and managing space type descriptors.
 *
 * Use {@link GigaSpace#getTypeManager()} to retrieve the type manager of a GigaSpace instance.
 *
 *  @see org.openspaces.core.GigaSpace
 *  @see com.gigaspaces.metadata.SpaceTypeDescriptor
 *  @see com.gigaspaces.metadata.SpaceTypeDescriptorBuilder
 *  @see com.gigaspaces.metadata.index.SpaceIndex
 *  @see com.gigaspaces.metadata.index.SpaceIndexFactory
 *
 * @author Niv Ingberg
 * @since 8.0
 */
public interface GigaSpaceTypeManager {

    /**
     * Gets the space type descriptor of the specified type.
     * @param typeName Name of type.
     * @return Type descriptor of the type, if available (if not, returns null).
     */
    SpaceTypeDescriptor getTypeDescriptor(String typeName);

    /**
     * Gets the space type descriptor of the specified type.
     * @param type Java class.
     * @return Type descriptor of the type, if available (if not, returns null).
     */
    SpaceTypeDescriptor getTypeDescriptor(Class<?> type);

    /**
     * Registers the specified space type descriptor in the space.
     * @param typeDescriptor
     */
    void registerTypeDescriptor(SpaceTypeDescriptor typeDescriptor);

    /**
     * Creates a type descriptor for the specified type and registers it in the space.
     * @param type
     */
    void registerTypeDescriptor(Class<?> type);

    /**
     * Adds the specified index to the specified type.
     *
     * @param typeName Name of type to enhance.
     * @param index Index to add.
     * @return A Future to monitor completion of the operation, whose get() method will return the add index result upon completion.
     */
    AsyncFuture<AddTypeIndexesResult> asyncAddIndex(String typeName , SpaceIndex index);
    /**
     * Adds the specified index to the specified type.
     *
     * @param typeName Name of type to enhance.
     * @param index Index to add.
     * @param listener A listener to be notified when a result arrives
     * @return A Future to monitor completion of the operation, whose get() method will return the add index result upon completion.
     */
    AsyncFuture<AddTypeIndexesResult> asyncAddIndex(String typeName, SpaceIndex index, AsyncFutureListener<AddTypeIndexesResult> listener);
    /**
     * Adds the specified indexes to the specified type.
     *
     * @param typeName Name of type to enhance.
     * @param indexes Indexes to add.
     * @param listener A listener to be notified when a result arrives.
     * @return A Future to monitor completion of the operation, whose get() method will return the add index result upon completion.
     */
    AsyncFuture<AddTypeIndexesResult> asyncAddIndexes(String typeName, SpaceIndex[] indexes, AsyncFutureListener<AddTypeIndexesResult> listener);
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("wimbledon", "0007_admininfo_ballot_time")]

    operations = [
        migrations.AlterField(model_name="admininfo", name="ballot_date", field=models.DateField()),
        migrations.AlterField(model_name="admininfo", name="ballot_time", field=models.TimeField()),
    ]


text:
module GraphQL
  module DefinitionHelpers
  end
end

require 'graphql/definition_helpers/definable'
require 'graphql/definition_helpers/non_null_with_bang'
require 'graphql/definition_helpers/defined_by_config'
require 'graphql/definition_helpers/string_named_hash'
require 'graphql/definition_helpers/type_definer'


text:
@interface CAIExcellentCourseResult : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong)NSString * message;
@property (nonatomic, assign)NSInteger success;
@property (nonatomic, strong)NSArray *list;

@end


text:
/*jslint node: true */
module.exports = function (RED) {
    "use strict";
    var common = require('../lib/common');

    /*
        Defines the output node for a rule. Copied to a large extent from 66-mongodb.js
    */
    function NoreliteTellstickOutNode(config) {
        RED.nodes.createNode(this, config);
        var node = this;
        node.code = config.code;
        node.dimmable = config.dimmable;

        common.setStatus(node);

        /* When a message is received */
        node.on("input", function (msg) {
            //Validate input
            var validate = common.validatePayload(msg.payload);
            if (!validate.valid) {
                node.warn(validate.error);
                return;
            }

            var nmsg = {
                device: node.code
            };

            var method;
            var dimlevel;
            if (node.dimmable) {
                if (msg.payload.status === 1 && msg.payload.value > 0) {
                    nmsg.method = "dim";
                    nmsg.dimlevel = parseInt(255 * msg.payload.value / 100);
                    common.setStatus(node, 1, "Dim " + msg.payload.value + "%");
                } else {
                    nmsg.method = "turnoff";
                    common.setStatus(node, -1, "Off");
                }
            } else {
                if (msg.payload.status === 1 && msg.payload.value > 0) {
                    nmsg.method = "turnon";
                    common.setStatus(node, 1, "On");
                } else {
                    nmsg.method = "turnoff";
                    common.setStatus(node, -1, "Off");
                }
            }

            //Also passing the original instruction if
            nmsg.instruction = msg.payload;
            nmsg.instruction.lid = node.id;

            node.send(nmsg);
        });

    }
    RED.nodes.registerType("nrl-tellstick-out", NoreliteTellstickOutNode);
};


text:
'use strict';

var async = require('async'),
    hoek  = require('hoek'),
    joi   = require('joi');

var all = function(collection, predicate) {
    for(var i = 0; i < collection.length; i++) {
        if(predicate(collection[i]) === false) {
            return false;
        }
    }
    return true;
};

exports.register = function(plugin, options, next) {
    var validation = joi.validate(options, require('./schema'));
    if(validation.error) {
        return next(validation.error);
    }

    plugin.route([
        {
            method: 'GET',
            path: '/service-status',
            handler: function(req, reply) {
                var monitors = [];
                options.monitors.forEach(function(monitor) {
                    monitors.push(function(done) {
                        monitor(req, reply, done);
                    });
                });

                async.parallel(monitors, function(err, results) {
                    if(err) {
                        throw err;
                    }

                    var response = {
                        status: all(results, function(result) { return result.status === 'healthy'; }) ? 'ok' : 'faulting'
                    };

                    response = hoek.applyToDefaults(response, options.metadata || {});
                    response.monitors = results;

                    reply(response).type('application/json').code(200);
                });
            },
            config: {
                auth: false,
                description: 'service-status',
                tags: ['non-cacheable'],
                plugins: {
                    'ot-hapi-request-metrics': {
                        endpoint: 'service-status',
                        version: '1'
                    }
                }
            }
        }
    ]);

    next();
};


text:
/*
This file contains all actions that are passed to the node server using socket.io.
Most of them are handled by the facebook chat api.
*/

export const LOGIN = "login";
export const LISTEN = "listen";
export const LOGOUT = "logout";
export const GET_THREAD_LIST = "getThreadList";
export const GET_THREAD_HISTORY = "getThreadHistory";
export const GET_THREAD_PICTURES = "getThreadPictures";
export const GET_USER_ID = "getUserID";
export const GET_USER_INFO = "getUserInfo";
export const GET_FRIENDS_LIST = "getFriendsList";
export const RESOLVE_PHOTO_URL = "resolvePhotoUrl";
export const SEND_MESSAGE = "sendMessage";
export const DELETE_MESSAGE = "deleteMessage";
export const UPLOAD_IMAGE = "uploadImage";
export const LOAD_MEMES = "loadMemes";

export function login(args) {
  return {
    type: LOGIN,
    args: [args]
  };
}

export function listen() {
  return {
    type: LISTEN,
    args: []
  }
}

export function logout() {
  return {
    type: LOGOUT,
    args: []
  }
}

export function getThreadList() {
  return {
    type: GET_THREAD_LIST,
    args: [0, 20, "inbox"] //"archived"
  }
}

/**
* Get a thread history
* @param {Integer} threadID Thread ID
* @param {Timestamp} [startAt] Timestamp at which the thread history chunk shall start
* @param {Integer} [count] Number of messages to fetch with one request. Avoid requesting large chunks at once.
*/
export function getThreadHistory(threadID, startAt, count = 20) {
  return {
    type: GET_THREAD_HISTORY,
    args: [threadID, count, startAt || Date.now()]
  }
}

export function getThreadPictures(threadID, limit = 20, offset = 0) {
  return {
    type: GET_THREAD_PICTURES,
    args: [threadID, offset, limit]
  }
}

export function getUserID(name) {
  return {
    type: GET_USER_ID,
    args: [name]
  }
}

export function getUserInfo(userIDs) {
  return {
    type: GET_USER_INFO,
    args: [userIDs]
  }
}

export function getFriendsList() {
  return {
    type: GET_FRIENDS_LIST,
    args: []
  }
}

export function resolvePhotoUrl(photoID) {
  return {
    type: RESOLVE_PHOTO_URL,
    args: [photoID]
  }
}

export function sendMessage(threadID, message, attachment) {
  let action = {
    type: SEND_MESSAGE,
    args: [{
      body: message
    }, threadID]
  };
  if (attachment)
    action.args[0].attachment = attachment;
  return action;
}

export function deleteMessage(messageID) {
  return {
    type: DELETE_MESSAGE,
    args: [messageID],
  }
}

export function uploadImage(dataURL) {
  return {
    type: UPLOAD_IMAGE,
    args: dataURL
  }
}

export function loadMemes() {
  return {
    type: LOAD_MEMES,
    args: []
  }
}


text:
from __future__ import print_function
import string
import sys
import threading
import time

import ddt
import mock
from six.moves import queue as Queue
import testtools

from rally.common import utils
from rally import exceptions
from tests.unit import test

class ImmutableMixinTestCase(test.TestCase):

    def test_without_base_values(self):
        im = utils.ImmutableMixin()
        self.assertRaises(exceptions.ImmutableException,
                          im.__setattr__, "test", "test")

    def test_with_base_values(self):

        class A(utils.ImmutableMixin):
            def __init__(self, test):
                self.test = test
                super(A, self).__init__()

        a = A("test")
        self.assertRaises(exceptions.ImmutableException,
                          a.__setattr__, "abc", "test")
        self.assertEqual(a.test, "test")

class EnumMixinTestCase(test.TestCase):

    def test_enum_mix_in(self):

        class Foo(utils.EnumMixin):
            a = 10
            b = 20
            CC = "2000"

        self.assertEqual(set(list(Foo())), set([10, 20, "2000"]))

    def test_with_underscore(self):

        class Foo(utils.EnumMixin):
            a = 10
            b = 20
            _CC = "2000"

        self.assertEqual(set(list(Foo())), set([10, 20]))

class StdIOCaptureTestCase(test.TestCase):

    def test_stdout_capture(self):
        stdout = sys.stdout
        messages = ["abcdef", "defgaga"]
        with utils.StdOutCapture() as out:
            for msg in messages:
                print(msg)

        self.assertEqual(out.getvalue().rstrip("\n").split("\n"), messages)
        self.assertEqual(stdout, sys.stdout)

    def test_stderr_capture(self):
        stderr = sys.stderr
        messages = ["abcdef", "defgaga"]
        with utils.StdErrCapture() as err:
            for msg in messages:
                print(msg, file=sys.stderr)

        self.assertEqual(err.getvalue().rstrip("\n").split("\n"), messages)
        self.assertEqual(stderr, sys.stderr)

class TimerTestCase(test.TestCase):

    def test_timer_duration(self):
        start_time = time.time()
        end_time = time.time()

        with mock.patch("rally.common.utils.time") as mock_time:
            mock_time.time = mock.MagicMock(return_value=start_time)
            with utils.Timer() as timer:
                mock_time.time = mock.MagicMock(return_value=end_time)

        self.assertIsNone(timer.error)
        self.assertEqual(end_time - start_time, timer.duration())

    def test_timer_exception(self):
        try:
            with utils.Timer() as timer:
                raise Exception()
        except Exception:
            pass
        self.assertEqual(3, len(timer.error))
        self.assertEqual(timer.error[0], type(Exception()))

def module_level_method():
    pass

class MethodClassTestCase(test.TestCase):

    @testtools.skipIf(sys.version_info > (2, 9), "Problems with access to "
                                                 "class from <locals>")
    def test_method_class_for_class_level_method(self):
        class A(object):
            def m(self):
                pass
        self.assertEqual(A, utils.get_method_class(A.m))

    def test_method_class_for_module_level_method(self):
        self.assertIsNone(utils.get_method_class(module_level_method))

class FirstIndexTestCase(test.TestCase):

    def test_list_with_existing_matching_element(self):
        lst = [1, 3, 5, 7]
        self.assertEqual(utils.first_index(lst, lambda e: e == 1), 0)
        self.assertEqual(utils.first_index(lst, lambda e: e == 5), 2)
        self.assertEqual(utils.first_index(lst, lambda e: e == 7), 3)

    def test_list_with_non_existing_matching_element(self):
        lst = [1, 3, 5, 7]
        self.assertIsNone(utils.first_index(lst, lambda e: e == 2))

class EditDistanceTestCase(test.TestCase):

    def test_distance_empty_strings(self):
        dist = utils.distance("", "")
        self.assertEqual(0, dist)

    def test_distance_equal_strings(self):
        dist = utils.distance("abcde", "abcde")
        self.assertEqual(0, dist)

    def test_distance_replacement(self):
        dist = utils.distance("abcde", "__cde")
        self.assertEqual(2, dist)

    def test_distance_insertion(self):
        dist = utils.distance("abcde", "ab__cde")
        self.assertEqual(2, dist)

    def test_distance_deletion(self):
        dist = utils.distance("abcde", "abc")
        self.assertEqual(2, dist)

class TenantIteratorTestCase(test.TestCase):

    def test_iterate_per_tenant(self):
        users = []
        tenants_count = 2
        users_per_tenant = 5
        for tenant_id in range(tenants_count):
            for user_id in range(users_per_tenant):
                users.append({"id": str(user_id),
                              "tenant_id": str(tenant_id)})

        expected_result = [
            ({"id": "0", "tenant_id": str(i)}, str(i)) for i in range(
                tenants_count)]
        real_result = [i for i in utils.iterate_per_tenants(users)]

        self.assertEqual(expected_result, real_result)

class RAMIntTestCase(test.TestCase):

    def test__int__(self):
        self.assertEqual(0, int(utils.RAMInt()))
        self.assertEqual(10, int(utils.RAMInt(10)))

    def test__str__(self):
        self.assertEqual("0", str(utils.RAMInt()))
        self.assertEqual("20", str(utils.RAMInt(20)))

    def test__next__(self):
        ri = utils.RAMInt()
        for i in range(0, 3):
            self.assertEqual(i, next(ri))

    def test_next(self):
        ri = utils.RAMInt()
        for i in range(0, 3):
            self.assertEqual(i, ri.next())

    def test_reset(self):
        ri = utils.RAMInt()
        ri.next()
        ri.reset()
        self.assertEqual(0, int(ri))

@ddt.ddt
class RandomNameTestCase(test.TestCase):

    @ddt.data(
        {},
        {"task_id": "fake-task"},
        {"task_id": "2short", "expected": "s_rally_blargles_dweebled"},
        {"task_id": "fake!task",
         "expected": "s_rally_blargles_dweebled"},
        {"fmt": "XXXX-test-XXX-test",
         "expected": "fake-test-bla-test"})
    @ddt.unpack
    @mock.patch("random.choice")
    def test_generate_random_name(self, mock_choice, task_id="faketask",
                                  expected="s_rally_faketask_blargles",
                                  fmt="s_rally_XXXXXXXX_XXXXXXXX"):
        class FakeNameGenerator(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = fmt
            task = {"uuid": task_id}

        generator = FakeNameGenerator()

        mock_choice.side_effect = iter("blarglesdweebled")
        self.assertEqual(generator.generate_random_name(), expected)

        class FakeNameGenerator(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = fmt
            verification = {"uuid": task_id}

        generator = FakeNameGenerator()

        mock_choice.side_effect = iter("blarglesdweebled")
        self.assertEqual(generator.generate_random_name(), expected)

    def test_generate_random_name_bogus_name_format(self):
        class FakeNameGenerator(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = "invalid_XXX_format"
            task = {"uuid": "fake-task-id"}

        generator = FakeNameGenerator()
        self.assertRaises(ValueError,
                          generator.generate_random_name)

    @ddt.data(
        {"good": ("rally_abcdefgh_abcdefgh", "rally_12345678_abcdefgh",
                  "rally_ABCdef12_ABCdef12"),
         "bad": ("rally_abcd_efgh", "rally_abcd!efg_12345678",
                 "rally_", "rally__", "rally_abcdefgh_",
                 "rally_abcdefghi_12345678", "foo", "foo_abcdefgh_abcdefgh")},
        {"task_id": "abcd1234",
         "good": ("rally_abcd1234_abcdefgh", "rally_abcd1234_abcd1234",
                  "rally_abcd1234_AbCdEf12"),
         "bad": ("rally_12345678_abcdefgh", "rally_12345678_abcd1234",
                 "rally_abcd1234_", "rally_abcd1234_!!!!!!!!",
                 "rally_ABCD1234_abcdefgh")},
        {"fmt": "][*_XXX_XXX",
         "chars": "abc(.*)",
         "good": ("][*_abc_abc", "][*_abc_((("),
         "bad": ("rally_ab_cd", "rally_ab!_abc", "rally_", "rally__",
                 "rally_abc_", "rally_abcd_abc", "foo", "foo_abc_abc")},
        {"fmt": "XXXX-test-XXX-test",
         "good": ("abcd-test-abc-test",),
         "bad": ("rally-abcdefgh-abcdefgh", "abc-test-abc-test",
                 "abcd_test_abc_test", "abc-test-abcd-test")})
    @ddt.unpack
    def test_cls_name_matches_object(
            self, good=(), bad=(), fmt="rally_XXXXXXXX_XXXXXXXX",
            chars=string.ascii_letters + string.digits, task_id=None):
        class FakeNameGenerator(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = fmt
            RESOURCE_NAME_ALLOWED_CHARACTERS = chars
            task = {"uuid": task_id or "fakeuuid"}

        for name in good:
            self.assertTrue(
                FakeNameGenerator.name_matches_object(name, task_id),
                "%s unexpectedly didn't match RESOURCE_NAME_FORMAT %s" %
                (name, fmt))

        for name in bad:
            self.assertFalse(
                FakeNameGenerator.name_matches_object(name, task_id),
                "%s unexpectedly matched RESOURCE_NAME_FORMAT %s" %
                (name, fmt))

    def test_name_matches_object(self):
        name = "foo"
        obj = mock.Mock()
        self.assertTrue(utils.name_matches_object(name, obj))
        obj.name_matches_object.assert_called_once_with(name, task_id=None)

    def test_name_matches_object_task_id(self):
        name = "foo"
        obj = mock.Mock()
        self.assertTrue(utils.name_matches_object(name, obj, task_id="taskid"))
        obj.name_matches_object.assert_called_once_with(name, task_id="taskid")

    def test_name_matches_object_identical_list(self):
        class One(utils.RandomNameGeneratorMixin):
            name_matches_object = mock.Mock(return_value=False)

        class Two(utils.RandomNameGeneratorMixin):
            name_matches_object = mock.Mock(return_value=False)

        name = "foo"
        self.assertFalse(utils.name_matches_object(name, One, Two))
        # ensure that exactly one of the two objects is checked
        self.assertItemsEqual(
            One.name_matches_object.call_args_list +
            Two.name_matches_object.call_args_list,
            [mock.call(name, task_id=None)])

    def test_name_matches_object_differing_list(self):
        class One(utils.RandomNameGeneratorMixin):
            name_matches_object = mock.Mock(return_value=False)

        class Two(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = "foo_XXX_XXX"
            name_matches_object = mock.Mock(return_value=False)

        class Three(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_ALLOWED_CHARACTERS = "12345"
            name_matches_object = mock.Mock(return_value=False)

        class Four(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = "bar_XXX_XXX"
            RESOURCE_NAME_ALLOWED_CHARACTERS = "abcdef"
            name_matches_object = mock.Mock(return_value=False)

        classes = (One, Two, Three, Four)
        name = "foo"
        self.assertFalse(utils.name_matches_object(name, *classes))
        for cls in classes:
            cls.name_matches_object.assert_called_once_with(name, task_id=None)

    def test_cls_name_matches_object_identity(self):
        generator = utils.RandomNameGeneratorMixin()
        generator.task = {"uuid": "faketask"}

        self.assertTrue(generator.name_matches_object(
            generator.generate_random_name()))
        self.assertTrue(utils.RandomNameGeneratorMixin.name_matches_object(
            generator.generate_random_name()))

    def test_name_matches_object_identity(self):
        generator = utils.RandomNameGeneratorMixin()
        generator.task = {"uuid": "faketask"}

        self.assertTrue(utils.name_matches_object(
            generator.generate_random_name(), generator))
        self.assertTrue(utils.name_matches_object(
            generator.generate_random_name(), utils.RandomNameGeneratorMixin))

    def test_consistent_task_id_part(self):
        class FakeNameGenerator(utils.RandomNameGeneratorMixin):
            RESOURCE_NAME_FORMAT = "XXXXXXXX_XXXXXXXX"

        generator = FakeNameGenerator()
        generator.task = {"uuid": "good-task-id"}

        names = [generator.generate_random_name() for i in range(100)]
        task_id_parts = set([n.split("_")[0] for n in names])
        self.assertEqual(len(task_id_parts), 1)

        generator.task = {"uuid": "bogus! task! id!"}

        names = [generator.generate_random_name() for i in range(100)]
        task_id_parts = set([n.split("_")[0] for n in names])
        self.assertEqual(len(task_id_parts), 1)

@ddt.ddt
class MergeTestCase(test.TestCase):
    @ddt.data(
        # regular data
        {"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
                     [[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
                     [[5], [5, 7, 11, 14, 14, 19, 23]]],
         "expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
                             [7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
                             [19, 19, 21, 23, 23, 26, 36, 41, 91]]},
        # with one empty source
        {"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
                     [[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
                     [[5], [5, 7, 11, 14, 14, 19, 23]],
                     []],
         "expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
                             [7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
                             [19, 19, 21, 23, 23, 26, 36, 41, 91]]},
        # with one source that produces an empty list
        {"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]],
                     [[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
                     [[5], [5, 7, 11, 14, 14, 19, 23]],
                     [[]]],
         "expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
                             [7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
                             [19, 19, 21, 23, 23, 26, 36, 41, 91]]},
        # with empty lists appered in sources
        {"sources": [[[1, 3, 5], [], [], [5, 7, 9, 14], [17, 21, 36, 41]],
                     [[], [2, 2, 4], [9, 10], [16, 19, 23, 26, 91]],
                     [[5], [5, 7, 11, 14, 14, 19, 23], []]],
         "expected_output": [[1, 2, 2, 3, 4, 5, 5, 5, 5, 7],
                             [7, 9, 9, 10, 11, 14, 14, 14, 16, 17],
                             [19, 19, 21, 23, 23, 26, 36, 41, 91]]},
        # only one source
        {"sources": [[[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]]],
         "expected_output": [[1, 3, 5, 5, 7, 9, 14, 17, 21, 36], [41]]},
        # no sources passed in
        {"sources": [],
         "expected_output": []},
        # several sources, all empty
        {"sources": [[], [], [], []],
         "expected_output": []}

    )
    @ddt.unpack
    def test_merge(self, sources, expected_output):
        in_iters = [iter(src) for src in sources]

        out = list(utils.merge(10, *in_iters))
        self.assertEqual(out, expected_output)

class TimeoutThreadTestCase(test.TestCase):
    def test_timeout_thread(self):
        """Create and kill thread by timeout.

        This single test covers 3 methods: terminate_thread, timeout_thread,
        and interruptable_sleep.

        This test is more like integrated then unit, but it is much better
        then unreadable 500 lines of mocking and checking.
        """
        queue = Queue.Queue()
        killer_thread = threading.Thread(
            target=utils.timeout_thread,
            args=(queue,),
        )
        test_thread = threading.Thread(
            target=utils.interruptable_sleep,
            args=(30, 0.01),
        )
        test_thread.start()
        start_time = time.time()
        queue.put((test_thread.ident, start_time + 1))
        killer_thread.start()
        test_thread.join()
        end_time = time.time()
        queue.put((None, None))
        killer_thread.join()
        time_elapsed = end_time - start_time
        # NOTE(sskripnick): Killing thread with PyThreadState_SetAsyncExc
        # works with sinificant delay. Make sure this delay is less
        # than 10 seconds.
        self.assertTrue(time_elapsed < 11,
                        "Thread killed too late (%s seconds)" % time_elapsed)


text:
require 'addressable'

module PictureTag
  # Represents a link to an image. We use the File library rather than the URI
  # library to build these because it doesn't like relative URIs.
  #
  # Just give it a filename, and pass source_image: true if it's not a generated
  # image. Call to_s on it to get the link.
  class ImgURI
    attr_reader :filename, :source_image

    def initialize(filename, source_image: false)
      @source_image = source_image
      @filename = filename
    end

    # https://example.com/my-base-path/assets/generated-images/image.jpg
    # |     domain       |  baseurl   |       directory       | filename
    def to_s
      Addressable::URI.escape(
        File.join(domain, PictureTag.baseurl, directory, @filename)
      )
    end

    private

    # https://example.com/my-base-path/assets/generated-images/image.jpg
    # ^^^^^^^^^^^^^^^^^^^^
    # |     domain       |  baseurl   |    j-p-t output dir   | filename
    def domain
      if PictureTag.cdn?
        PictureTag.cdn_url
      elsif PictureTag.relative_url
        ''
      else
        PictureTag.config['url'] || ''
      end
    end

    # https://example.com/my-base-path/assets/generated-images/image.jpg
    #                                  ^^^^^^^^^^^^^^^^^^^^^^^^
    # |     domain       |  baseurl   |       directory       | filename
    def directory
      PictureTag.pconfig[
        @source_image ? 'source' : 'output'
      ]
    end
  end
end


text:
/*!
 * \file
 * \brief The Khronos Extras Extension Node and Immediate Interfaces
 * \author Erik Rainey <erik.rainey@gmail.com>
 */

#include <VX/vx.h>
#include <VX/vx_lib_extras.h>
#include <VX/vx_helper.h>

//*****************************************************************************
// PUBLIC INTERFACE
//*****************************************************************************

vx_node vxNonMaxSuppressionNode(vx_graph graph, vx_image mag, vx_image phase, vx_image edge)
{
    vx_reference params[] = {
        (vx_reference)mag,
        (vx_reference)phase,
        (vx_reference)edge,
    };
    return vxCreateNodeByStructure(graph,
                                   VX_KERNEL_EXTRAS_NONMAXSUPPRESSION,
                                   params, dimof(params));
}

vx_status vxuNonMaxSuppression(vx_context context, vx_image mag, vx_image phase, vx_image edge)
{
    vx_status status = VX_SUCCESS;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxNonMaxSuppressionNode(graph, mag, phase, edge);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxLaplacian3x3Node(vx_graph graph, vx_image input, vx_image output)
{
    vx_reference params[] = {
        (vx_reference)input,
        (vx_reference)output,
    };
    return vxCreateNodeByStructure(graph,
                                   VX_KERNEL_EXTRAS_LAPLACIAN_3x3,
                                   params,
                                   dimof(params));
}

vx_status vxuLaplacian3x3(vx_context context, vx_image input, vx_image output)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxLaplacian3x3Node(graph, input, output);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxScharr3x3Node(vx_graph graph, vx_image input, vx_image output1, vx_image output2)
{
    vx_reference params[] = {
        (vx_reference)input,
        (vx_reference)output1,
        (vx_reference)output2
    };
    return vxCreateNodeByStructure(graph,
                                   VX_KERNEL_EXTRAS_SCHARR_3x3,
                                   params,
                                   dimof(params));
}

vx_status vxuScharr3x3(vx_context context, vx_image input, vx_image output1,vx_image output2)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxScharr3x3Node(graph, input, output1,output2);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxSobelMxNNode(vx_graph graph, vx_image input, vx_scalar ws, vx_image gx, vx_image gy)
{
    vx_reference params[] = {
        (vx_reference)input,
        (vx_reference)ws,
        (vx_reference)gx,
        (vx_reference)gy,
    };
    vx_node node = vxCreateNodeByStructure(graph,
                                   VX_KERNEL_EXTRAS_SOBEL_MxN,
                                   params,
                                   dimof(params));
    return node;
}

vx_status vxuSobelMxN(vx_context context, vx_image input, vx_scalar win, vx_image gx, vx_image gy)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxSobelMxNNode(graph, input, win, gx, gy);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxHarrisScoreNode(vx_graph graph,
                          vx_image gx,
                          vx_image gy,
                          vx_scalar sensitivity,
                          vx_scalar block_size,
                          vx_image score)
{
    vx_reference params[] = {
        (vx_reference)gx,
        (vx_reference)gy,
        (vx_reference)sensitivity,
        (vx_reference)block_size,
        (vx_reference)score,
    };
    vx_node node = vxCreateNodeByStructure(graph,
                                           VX_KERNEL_EXTRAS_HARRIS_SCORE,
                                           params,
                                           dimof(params));
    return node;
}

vx_status vxuHarrisScore(vx_context context, vx_image gx,
                         vx_image gy,
                         vx_scalar sensitivity,
                         vx_scalar block_size,
                         vx_image score)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxHarrisScoreNode(graph, gx, gy, sensitivity, block_size, score);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxEuclideanNonMaxNode(vx_graph graph,
                              vx_image input,
                              vx_scalar strength_thresh,
                              vx_scalar min_distance,
                              vx_image output)
{
    vx_reference params[] = {
        (vx_reference)input,
        (vx_reference)strength_thresh,
        (vx_reference)min_distance,
        (vx_reference)output,
    };
    vx_node node = vxCreateNodeByStructure(graph,
                                           VX_KERNEL_EXTRAS_EUCLIDEAN_NONMAXSUPPRESSION,
                                           params,
                                           dimof(params));
    return node;
}

vx_status vxuEuclideanNonMax(vx_context context, vx_image input,
                             vx_scalar strength_thresh,
                             vx_scalar min_distance,
                             vx_image output)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxEuclideanNonMaxNode(graph, input, strength_thresh, min_distance, output);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxImageListerNode(vx_graph graph, vx_image input, vx_array arr, vx_scalar num_points)
{
    vx_reference params[] = {
        (vx_reference)input,
        (vx_reference)arr,
        (vx_reference)num_points,
    };
    return vxCreateNodeByStructure(graph,
                                   VX_KERNEL_EXTRAS_IMAGE_LISTER,
                                   params,
                                   dimof(params));
}

vx_status vxuImageLister(vx_context context, vx_image input,
                         vx_array arr, vx_scalar num_points)
{
    vx_status status = VX_FAILURE;
    vx_graph graph = vxCreateGraph(context);
    if (graph)
    {
        vx_node node = vxImageListerNode(graph, input, arr, num_points);
        if (node)
        {
            status = vxVerifyGraph(graph);
            if (status == VX_SUCCESS)
            {
                status = vxProcessGraph(graph);
            }
            vxReleaseNode(&node);
        }
        vxClearLog((vx_reference)graph);
        vxReleaseGraph(&graph);
    }
    return status;
}

vx_node vxElementwiseNormNode(vx_graph graph,
                              vx_image input_x,
                              vx_image input_y,
                              vx_scalar norm_type,
                              vx_image output)
{
    vx_reference params[] = {
        (vx_reference)input_x,
        (vx_reference)input_y,
        (vx_reference)norm_type,
        (vx_reference)output,
    };
    vx_node node = vxCreateNodeByStructure(graph,
                                           VX_KERNEL_EXTRAS_ELEMENTWISE_NORM,
                                           params,
                                           dimof(params));
    return node;
}

vx_node vxEdgeTraceNode(vx_graph graph,
                        vx_image norm,
                        vx_threshold threshold,
                        vx_image output)
{
    vx_reference params[] = {
        (vx_reference)norm,
        (vx_reference)threshold,
        (vx_reference)output,
    };
    vx_node node = vxCreateNodeByStructure(graph,
                                           VX_KERNEL_EXTRAS_EDGE_TRACE,
                                           params,
                                           dimof(params));
    return node;
}