text:
title: Grails® Test Leakage
date: December 5, 2017
description: Learn how to avoid test leakage in Grails® integration and functional tests
author: Sergio Del Amo Caballero
image: 2017-12-05.jpg
CSS: [%url]/stylesheets/prism.css
JAVASCRIPT: [%url]/javascripts/prism.js
---

# [%title]

[%author]

[%date]

From Rob Fletcher book, [Spock: Up and Running](https://shop.oreilly.com/product/0636920038597.do)

> TEST LEAKAGE
>
> A very important feature of any unit test is that it should be idempotent. That is to say, the test should produce the same result regardless of whether it is run alone or with other tests in a suite and regardless of the order in which the tests in that suite are run. When side effects from a test affect subsequent tests in the suite, we can describe that test as leaking.
> Test leakage is caused by badly managed resources. Typical causes of leakage include data in a persistent store that is not removed, changes to a class' metaclass that are unexpectedly still in place later, mocks injected into objects reused between tests, and uncontrolled changes to global state such as the system clock.
>  Test leakage can be very difficult to track down. Simply identifying which test is leaking can be time consuming. For example, the leaking test might not affect the one running directly after it, or continuous integration servers might run test suites in a different order from that of the developer's computers, leading to protests of but, it works on my machine!"

In this blog post, we discuss how to avoid test leakage in Grails® integration and functional tests. In particular, _data in a persistent store that is not removed_.

Lets us create a simple Grails App:

    curl -O start.grails.org/myapp.zip -d version=3.3.2 -d profile=rest-api

with a Domain Class

_grails-app/domain/demo/Book.groovy_
```groovy
package demo

import grails.rest.Resource

@Resource
class Book {
    String title
}
```

and a GORM Data Service

_grails-app/services/demo/BookDataService.groovy_
```groovy
package demo

import grails.gorm.services.Service

@Service(Book)
interface BookDataService {
    Book saveBook(String title)
    void deleteBook(Serializable id)
    int count()
}
```

## Integration Test

If you create the next integration specification:

_src/integration-test/groovy/demo/BookDataServiceSpec.groovy_
```groovy
package demo

import grails.testing.mixin.integration.Integration
import spock.lang.Specification

@Integration
class BookDataServiceSpec extends Specification {

    BookDataService bookDataService

    void "test save book"() {
        when:
        Book book = bookDataService.saveBook('Practical Grails 3')

        then:
bookDataService.count() == old(bookDataService.count()) + 1
        book
    }
}
```

You will have a test leakage. After the specification is executed, the `book` database table will be:

id	title

1	Practical Grails 3

The previous test leaks one `book` row.

To solve it, you could add a cleanup block:

_src/integration-test/groovy/demo/BookDataServiceSpec.groovy_
```groovy
@Integration
class BookDataServiceSpec extends Specification {

    BookDataService bookDataService

    void "test save book"() {
        when:
        Book book = bookDataService.saveBook('Practical Grails 3')

        then:
        Book.count() == old(Book.count()) + 1

        cleanup:
        bookDataService.deleteBook(book.id)
    }
}
```

or use `@Rollback` annotation.

> The Rollback annotation ensures that each test method runs in a transaction that is rolled back. Generally this is desirable because you do not want your tests depending on order or application state.

_src/integration-test/groovy/demo/BookDataServiceSpec.groovy_
```groovy
package demo

import grails.gorm.transactions.Rollback
import grails.testing.mixin.integration.Integration
import spock.lang.Specification

@Rollback
@Integration
class BookDataServiceSpec extends Specification {

    BookDataService bookDataService

    void "test save book"() {
        when:
        Book book = bookDataService.saveBook('Practical Grails 3')

        then:
        bookDataService.count() == old(bookDataService.count()) + 1
        book
    }
}
```

## Functional Test

You may have noticed that we have annotated the Domain class with `@Resource` transformation.

> Simply by adding the Resource transformation and specifying a URI, your domain class will automatically be available as a REST resource in either XML or JSON formats. The transformation will automatically register the necessary RESTful URL mapping and create a controller called BookController.

We add a functional test to test the API exposed by the transformation:

_src/integration-test/groovy/demo/BookResourceSpec.groovy_
```groovy
package demo

import grails.plugins.rest.client.RestBuilder
import grails.plugins.rest.client.RestResponse
import grails.testing.mixin.integration.Integration
import groovy.json.JsonOutput
import spock.lang.Specification

@Integration
class BookResourceSpec extends Specification {

    BookDataService bookDataService

    void "test save book"() {
        given:
        RestBuilder restBuilder = new RestBuilder()

        when:
        RestResponse resp = restBuilder.post("http://localhost:${serverPort}/book") {
            accept('application/json')
            contentType('application/json')
            json(JsonOutput.toJson([title: 'Practical Grails 3']))
        }

        then:
        bookDataService.count() == old(bookDataService.count()) + 1
        resp.json.id
    }
}
```

The previous tests causes a test leakage. After the specification is executed, the `book` database table will be:

id	title

1	Practical Grails 3

You may be tempted to add a `@Rollback` annotation to the functional test. However, that will not solve
the test leakage. `@Rollback` only impacts changes within the test method. By using a REST
client you are sending requests to the server which run the changes in a completely
different thread, thus the same transaction management doesn't apply.

You can solve the functional test leakage by adding a `cleanup` block.

_src/integration-test/groovy/demo/BookResourceSpec.groovy_
```groovy
package demo

import grails.plugins.rest.client.RestBuilder
import grails.plugins.rest.client.RestResponse
import grails.testing.mixin.integration.Integration
import groovy.json.JsonOutput
import spock.lang.Specification

@Integration
class BookResourceSpec extends Specification {

    BookDataService bookDataService

    void "test save book"() {
        given:
        RestBuilder restBuilder = new RestBuilder()

        when:
        RestResponse resp = restBuilder.post("http://localhost:${serverPort}/book") {
            accept('application/json')
            contentType('application/json')
            json(JsonOutput.toJson([title: 'Practical Grails 3']))
        }

        then:
        bookDataService.count() == old(bookDataService.count()) + 1
        resp.json.id

        cleanup:
        bookDataService.deleteBook(resp.json.id as Serializable)
    }
}
```

To sump up, be careful when writing integration and functional tests to avoid test leakage.
While `@Rollback` annotation may help you in integration tests, you will need to
manually cleanup in functional tests.


text:
> Inspects, updates and manages submodules.
> Homepage: <https://git-scm.com/docs/git-submodule>.

- Install a repository's specified submodules:

`git submodule update --init --recursive`

- Add a git repository as a submodule:

`git submodule add {{repository_url}}`

- Add a git repository as a submodule at the specified directory:

`git submodule add {{repository_url}} {{path/to/directory}}`

- Update every submodule to its latest commit:

`git submodule foreach git pull`

redpajama_set_name: RedPajamaGithub


text:
package ru.fizteh.fivt.students.kamilTalipov.database.utils;

import ru.fizteh.fivt.storage.structured.Storeable;
import ru.fizteh.fivt.storage.structured.Table;

public class StoreableUtils {
    public static boolean isCorrectStoreable(Storeable value, Table table) {
        if (value == null) {
            throw new IllegalArgumentException("Storeable must be not null");
        }
        if (table == null) {
            throw new IllegalArgumentException("Table must be not null");
        }

        if (!isCorrectSize(value, table)) {
            return false;
        }

        for (int i = 0; i < table.getColumnsCount(); ++i) {
            if (value.getColumnAt(i) != null
                    && value.getColumnAt(i).getClass() != table.getColumnType(i)) {
                return false;
            }
        }

        return true;
    }

    private static boolean isCorrectSize(Storeable value, Table table) {
        try {
            value.getColumnAt(table.getColumnsCount() - 1);
        } catch (IndexOutOfBoundsException e) {
            return false;
        }
        try {
            value.getColumnAt(table.getColumnsCount());
        }  catch (IndexOutOfBoundsException e) {
            return true;
        }

        return false;
    }

    public static boolean isEqualStoreable(Storeable storeable1, Storeable storeable2) {
        if (storeable1 == null) {
            if (storeable2 == null) {
                return true;
            }
            return false;
        }
        if (storeable2 == null) {
            return false;
        }

        int size = 0;
        while (true) {
            boolean wasException1 = false;
            try {
                storeable1.getColumnAt(size);
            }  catch (IndexOutOfBoundsException e) {
                wasException1 = true;
            }

            boolean wasException2 = false;
            try {
                storeable2.getColumnAt(size);
            }  catch (IndexOutOfBoundsException e) {
                wasException2 = true;
            }

            if (wasException1 != wasException2) {
                return false;
            } else if (wasException1) {
                break;
            }

            ++size;
        }

        for (int i = 0; i < size; ++i) {
            Object object1 = storeable1.getColumnAt(i);
            Object object2 = storeable2.getColumnAt(i);
            if (object1 == null) {
                if (object2 != null) {
                    return false;
                }
                continue;
            }
            if (object2 == null) {
                return false;
            }

            if (object1.getClass() != object2.getClass()) {
                return false;
            }
            if (!object1.toString().equals(object2.toString())) {
                return false;
            }
        }

        return true;
    }
}


text:
'use strict';

const stampit = require('stampit');

const ObjectKey = require('./object-key');

module.exports = stampit()
  .methods({
    min,
    max
  })
  .compose(ObjectKey);

/**
 * Describe validation rule for minimum value
 *
 * @param {Integer} value Minimal value
 * @param {String} [msg] Optional. Error message. Defaults to empty string
 *
 * @return {Object} Validation schema (this)
 *
 * @public
 */
function min (value, msg = '') {
  if (!Number.isInteger(value)) {
    throw new TypeError('value must be an integer');
  }

  this.minValue = value;
  this.minValueMsg = String(msg);
  return this;
}

/**
 * Describe validation rule for maximum value
 *
 * @param {Integer} value Maximum value
 * @param {String} [msg] Optional. Error message. Defaults to the empty string
 *
 * @return {Object} Validation schema (this)
 *
 * @public
 */
function max (value, msg = '') {
  if (!Number.isInteger(value)) {
    throw new TypeError('value must be an integer');
  }

  this.maxValue = value;
  this.maxValueMsg = String(msg);
  return this;
}


text:
#ifndef __H_VHWD_SERIALIZATION__
#define __H_VHWD_SERIALIZATION__

#include "vhwd/serialization/serializer.h"
#include "vhwd/serialization/serializer_stream.h"
#include "vhwd/serialization/serializer_socket.h"
#include "vhwd/serialization/serializer_buffer.h"

#endif


text:
package org.apache.naming;

import javax.naming.Context;
import javax.naming.NamingException;

import org.junit.Assert;
import org.junit.Test;

import org.apache.catalina.deploy.ContextEnvironment;
import org.apache.catalina.deploy.ContextResourceLink;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.naming.factory.ResourceLinkFactory;

public class TestNamingContext extends TomcatBaseTest {

    private static final String COMP_ENV = "comp/env";
    private static final String GLOBAL_NAME = "global";
    private static final String LOCAL_NAME = "local";
    private static final String DATA = "Cabbage";

    @Test
    public void testGlobalNaming() throws Exception {
        Tomcat tomcat = getTomcatInstance();
        tomcat.enableNaming();

        org.apache.catalina.Context ctx = tomcat.addContext("", null);

        tomcat.start();

        Context webappInitial = ContextBindings.getContext(ctx);

        // Nothing added at the moment so should be null
        Object obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
        Assert.assertNull(obj);

        ContextEnvironment ce = new ContextEnvironment();
        ce.setName(GLOBAL_NAME);
        ce.setValue(DATA);
        ce.setType(DATA.getClass().getName());

        tomcat.getServer().getGlobalNamingResources().addEnvironment(ce);

        // No link so still should be null
        obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
        Assert.assertNull(obj);

        // Now add a resource link to the context
        ContextResourceLink crl = new ContextResourceLink();
        crl.setGlobal(GLOBAL_NAME);
        crl.setName(LOCAL_NAME);
        crl.setType(DATA.getClass().getName());
        ctx.getNamingResources().addResourceLink(crl);

        // Link exists so should be OK now
        obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
        Assert.assertEquals(DATA, obj);

        // Try shortcut
        ResourceLinkFactory factory = new ResourceLinkFactory();
        ResourceLinkRef rlr = new ResourceLinkRef(DATA.getClass().getName(), GLOBAL_NAME, null, null);
        obj = factory.getObjectInstance(rlr, null, null, null);
        Assert.assertEquals(DATA, obj);

        // Remove the link
        ctx.getNamingResources().removeResourceLink(LOCAL_NAME);

        // No link so should be null
        obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
        Assert.assertNull(obj);

        // Shortcut should fail too
        obj = factory.getObjectInstance(rlr, null, null, null);
        Assert.assertNull(obj);
    }

    private Object doLookup(Context context, String name) {
        Object result = null;
        try {
            result = context.lookup(name);
        } catch (NamingException nnfe) {
            // Ignore
        }
        return result;
    }
}


text:
RSpec.describe RuboCop::Cop::Naming::VariableNumber, :config do
  let(:cop_config) { { 'CheckMethodNames' => true, 'CheckSymbols' => true } }

  shared_examples 'offense' do |style, variable, style_to_allow_offenses|
    it "registers an offense for #{variable} in #{style}" do
      expect_offense(<<~RUBY, variable: variable)
        #{variable} = 1
        ^{variable} Use #{style} for variable numbers.
      RUBY

      expect(cop.config_to_allow_offenses).to eq(
        { 'EnforcedStyle' => style_to_allow_offenses.to_s }
      )
    end
  end

  shared_examples 'offense_array' do |style, variables|
    it "registers an offense for #{variables} in #{style}" do
      lines = variables.map { |v| "#{v} = 1" }
      lines.insert(1, "^{first_variable} Use #{style} for variable numbers.")

      expect_offense(lines.join("\n"), first_variable: variables.first)

      expect(cop.config_to_allow_offenses).to eq({ 'Enabled' => false })
    end
  end

  shared_examples 'accepts' do |style, variable|
    it "accepts #{variable} in #{style}" do
      expect_no_offenses("#{variable} = 1")
    end
  end

  shared_examples 'accepts integer symbols' do
    it 'accepts integer symbol' do
      expect_no_offenses(':"42"')
    end

    it 'accepts integer symbol array literal' do
      expect_no_offenses('%i[1 2 3]')
    end
  end

  context 'when configured for snake_case' do
    let(:cop_config) { { 'EnforcedStyle' => 'snake_case' } }

    it_behaves_like 'offense', 'snake_case', 'local1', :normalcase
    it_behaves_like 'offense', 'snake_case', '@local1', :normalcase
    it_behaves_like 'offense', 'snake_case', '@@local1', :normalcase
    it_behaves_like 'offense', 'snake_case', 'camelCase1', :normalcase
    it_behaves_like 'offense', 'snake_case', '@camelCase1', :normalcase
    it_behaves_like 'offense', 'snake_case', '_unused1', :normalcase
    it_behaves_like 'offense', 'snake_case', 'aB1', :normalcase
    it_behaves_like 'offense_array', 'snake_case', %w[a1 a_2]

    it_behaves_like 'accepts', 'snake_case', 'local_1'
    it_behaves_like 'accepts', 'snake_case', 'local_12'
    it_behaves_like 'accepts', 'snake_case', 'local_123'
    it_behaves_like 'accepts', 'snake_case', 'local_'
    it_behaves_like 'accepts', 'snake_case', 'aB_1'
    it_behaves_like 'accepts', 'snake_case', 'a_1_b'
    it_behaves_like 'accepts', 'snake_case', 'a_1_b_1'
    it_behaves_like 'accepts', 'snake_case', '_'
    it_behaves_like 'accepts', 'snake_case', '_foo'
    it_behaves_like 'accepts', 'snake_case', '@foo'
    it_behaves_like 'accepts', 'snake_case', '@__foo__'
    it_behaves_like 'accepts', 'snake_case', 'emparejó'
    it_behaves_like 'accepts', 'snake_case', '_1'

    it_behaves_like 'accepts integer symbols'

    it 'registers an offense for normal case numbering in symbol' do
      expect_offense(<<~RUBY)
        :sym1
        ^^^^^ Use snake_case for symbol numbers.
      RUBY
    end

    it 'does not register an offense for snake case numbering in symbol' do
      expect_no_offenses(<<~RUBY)
        :sym_1
      RUBY
    end

    it 'registers an offense for normal case numbering in method parameter' do
      expect_offense(<<~RUBY)
        def method(arg1); end
                   ^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in method camel case parameter' do
      expect_offense(<<~RUBY)
        def method(funnyArg1); end
                   ^^^^^^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in method name' do
      expect_offense(<<~RUBY)
        def method1; end
            ^^^^^^^ Use snake_case for method name numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in a global variable name' do
      expect_offense(<<~RUBY)
        $arg1 = :foo
        ^^^^^ Use snake_case for variable numbers.
      RUBY
    end
  end

  context 'when configured for normal' do
    let(:cop_config) { { 'EnforcedStyle' => 'normalcase' } }

    it_behaves_like 'offense', 'normalcase', 'local_1', :snake_case
    it_behaves_like 'offense', 'normalcase', 'sha_256', :snake_case
    it_behaves_like 'offense', 'normalcase', '@local_1', :snake_case
    it_behaves_like 'offense', 'normalcase', '@@local_1', :snake_case
    it_behaves_like 'offense', 'normalcase', 'myAttribute_1', :snake_case
    it_behaves_like 'offense', 'normalcase', '@myAttribute_1', :snake_case
    it_behaves_like 'offense', 'normalcase', '_myLocal_1', :snake_case
    it_behaves_like 'offense', 'normalcase', 'localFOO_1', :snake_case
    it_behaves_like 'offense', 'normalcase', 'local_FOO_1', :snake_case
    it_behaves_like 'offense_array', 'normalcase', %w[a_1 a2]

    it_behaves_like 'accepts', 'normalcase', 'local1'
    it_behaves_like 'accepts', 'normalcase', 'local_'
    it_behaves_like 'accepts', 'normalcase', 'user1_id'
    it_behaves_like 'accepts', 'normalcase', 'sha256'
    it_behaves_like 'accepts', 'normalcase', 'foo10_bar'
    it_behaves_like 'accepts', 'normalcase', 'target_u2f_device'
    it_behaves_like 'accepts', 'normalcase', 'localFOO1'
    it_behaves_like 'accepts', 'normalcase', 'snake_case'
    it_behaves_like 'accepts', 'normalcase', 'user_1_id'
    it_behaves_like 'accepts', 'normalcase', '_'
    it_behaves_like 'accepts', 'normalcase', '_foo'
    it_behaves_like 'accepts', 'normalcase', '@foo'
    it_behaves_like 'accepts', 'normalcase', '@__foo__'
    it_behaves_like 'accepts', 'normalcase', 'emparejó'
    it_behaves_like 'accepts', 'normalcase', '_1'

    it_behaves_like 'accepts integer symbols'

    it 'registers an offense for snake case numbering in symbol' do
      expect_offense(<<~RUBY)
        :sym_1
        ^^^^^^ Use normalcase for symbol numbers.
      RUBY
    end

    it 'does not register an offense for normal case numbering in symbol' do
      expect_no_offenses(':sym1')
    end

    it 'registers an offense for snake case numbering in method parameter' do
      expect_offense(<<~RUBY)
        def method(arg_1); end
                   ^^^^^ Use normalcase for variable numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in method camel case parameter' do
      expect_offense(<<~RUBY)
        def method(funnyArg_1); end
                   ^^^^^^^^^^ Use normalcase for variable numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in method name' do
      expect_offense(<<~RUBY)
        def method_1; end
            ^^^^^^^^ Use normalcase for method name numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in a global variable name' do
      expect_offense(<<~RUBY)
        $arg_1 = :foo
        ^^^^^^ Use normalcase for variable numbers.
      RUBY
    end
  end

  context 'when configured for non integer' do
    let(:cop_config) { { 'EnforcedStyle' => 'non_integer' } }

    it_behaves_like 'offense', 'non_integer', 'local_1', :snake_case
    it_behaves_like 'offense', 'non_integer', 'local1', :normalcase
    it_behaves_like 'offense', 'non_integer', '@local_1', :snake_case
    it_behaves_like 'offense', 'non_integer', '@local1', :normalcase
    it_behaves_like 'offense', 'non_integer', 'myAttribute_1', :snake_case
    it_behaves_like 'offense', 'non_integer', 'myAttribute1', :normalcase
    it_behaves_like 'offense', 'non_integer', '@myAttribute_1', :snake_case
    it_behaves_like 'offense', 'non_integer', '@myAttribute1', :normalcase
    it_behaves_like 'offense', 'non_integer', '_myLocal_1', :snake_case
    it_behaves_like 'offense', 'non_integer', '_myLocal1', :normalcase
    it_behaves_like 'offense_array', 'non_integer', %w[a_1 aone]

    it_behaves_like 'accepts', 'non_integer', 'localone'
    it_behaves_like 'accepts', 'non_integer', 'local_one'
    it_behaves_like 'accepts', 'non_integer', 'local_'
    it_behaves_like 'accepts', 'non_integer', '@foo'
    it_behaves_like 'accepts', 'non_integer', '@@foo'
    it_behaves_like 'accepts', 'non_integer', 'fooBar'
    it_behaves_like 'accepts', 'non_integer', '_'
    it_behaves_like 'accepts', 'non_integer', '_foo'
    it_behaves_like 'accepts', 'non_integer', '@__foo__'
    it_behaves_like 'accepts', 'non_integer', 'emparejó'
    it_behaves_like 'accepts', 'non_integer', '_1'

    it_behaves_like 'accepts integer symbols'

    it 'registers an offense for snake case numbering in symbol' do
      expect_offense(<<~RUBY)
        :sym_1
        ^^^^^^ Use non_integer for symbol numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in symbol' do
      expect_offense(<<~RUBY)
        :sym1
        ^^^^^ Use non_integer for symbol numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in method parameter' do
      expect_offense(<<~RUBY)
        def method(arg_1); end
                   ^^^^^ Use non_integer for variable numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in method parameter' do
      expect_offense(<<~RUBY)
        def method(arg1); end
                   ^^^^ Use non_integer for variable numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in method camel case parameter' do
      expect_offense(<<~RUBY)
        def method(myArg_1); end
                   ^^^^^^^ Use non_integer for variable numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in method camel case parameter' do
      expect_offense(<<~RUBY)
        def method(myArg1); end
                   ^^^^^^ Use non_integer for variable numbers.
      RUBY
    end

    it 'registers an offense for snake case numbering in method name' do
      expect_offense(<<~RUBY)
        def method_1; end
            ^^^^^^^^ Use non_integer for method name numbers.
      RUBY
    end

    it 'registers an offense for normal case numbering in method name' do
      expect_offense(<<~RUBY)
        def method1; end
            ^^^^^^^ Use non_integer for method name numbers.
      RUBY
    end
  end

  context 'when CheckMethodNames is false' do
    let(:cop_config) { { 'CheckMethodNames' => false, 'EnforcedStyle' => 'normalcase' } }

    it 'does not register an offense for snake case numbering in method name' do
      expect_no_offenses('def method_1; end')
    end
  end

  context 'when CheckSymbols is false' do
    let(:cop_config) { { 'CheckSymbols' => false, 'EnforcedStyle' => 'normalcase' } }

    it 'does not register an offense for snake case numbering in symbol' do
      expect_no_offenses(':sym_1')
    end
  end

  context 'when AllowedIdentifiers is set' do
    let(:cop_config) do
      {
        'AllowedIdentifiers' => %w[capture3],
        'CheckSymbols' => true,
        'CheckMethodNames' => true,
        'EnforcedStyle' => 'snake_case'
      }
    end

    it 'does not register an offense for a local variable name that is allowed' do
      expect_no_offenses(<<~RUBY)
        capture3 = :foo
      RUBY
    end

    it 'does not register an offense for a instance variable name that is allowed' do
      expect_no_offenses(<<~RUBY)
        @capture3 = :foo
      RUBY
    end

    it 'does not register an offense for a class variable name that is allowed' do
      expect_no_offenses(<<~RUBY)
        @@capture3 = :foo
      RUBY
    end

    it 'does not register an offense for a global variable name that is allowed' do
      expect_no_offenses(<<~RUBY)
        $capture3 = :foo
      RUBY
    end

    it 'does not register an offense for a method name that is allowed' do
      expect_no_offenses(<<~RUBY)
        def capture3
        end
      RUBY
    end

    it 'does not register an offense for a symbol that is allowed' do
      expect_no_offenses(':capture3')
    end
  end

  context 'when AllowedPatterns is set' do
    let(:cop_config) do
      {
        'AllowedIdentifiers' => [],
        'AllowedPatterns' => [
          '_v\d+\z',
          'allow_me'
        ],
        'CheckSymbols' => true,
        'CheckMethodNames' => true,
        'EnforcedStyle' => 'snake_case'
      }
    end

    it 'registers an offense for a local variable name that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        foo_a1 = :foo
        ^^^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'does not register an offense for a local variable name that matches an allowed pattern' do
      expect_no_offenses(<<~RUBY)
        foo_v1 = :foo
        foo_allow_me_a1 = :allowed
      RUBY
    end

    it 'registers an offense for a instance variable name that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        @foo_a1 = :foo
        ^^^^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'does not register an offense for a instance variable name that matches an allowed pattern' do
      expect_no_offenses(<<~RUBY)
        @foo_v1 = :foo
        @foo_allow_me_a1 = :allowed
      RUBY
    end

    it 'registers an offense for a class variable name that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        @@foo_a1 = :foo
        ^^^^^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'does not register an offense for a class variable name that matches an allowed pattern' do
      expect_no_offenses(<<~RUBY)
        @@foo_v1 = :foo
        @@foo_allow_me_a1 = :allowed
      RUBY
    end

    it 'registers an offense for a global variable name that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        $foo_a1 = :foo
        ^^^^^^^ Use snake_case for variable numbers.
      RUBY
    end

    it 'does not register an offense for a global variable name that matches an allowed pattern' do
      expect_no_offenses(<<~RUBY)
        $foo_v1 = :foo
        $foo_allow_me_a1 = :allowed
      RUBY
    end

    it 'registers an offense for a method name that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        def foo_a1
            ^^^^^^ Use snake_case for method name numbers.
        end
      RUBY
    end

    it 'does not register an offense for a method name that matches an allowed pattern' do
      expect_no_offenses(<<~RUBY)
        def foo_v1
        end

        def foo_allow_me_a1
        end
      RUBY
    end

    it 'registers an offense for a symbol that does not match an allowed pattern' do
      expect_offense(<<~RUBY)
        :foo_a1
        ^^^^^^^ Use snake_case for symbol numbers.
      RUBY
    end

    it 'does not register an offense for a symbol that matches an allowed pattern' do
      expect_no_offenses(':foo_v1')
      expect_no_offenses(':foo_allow_me_a1')
    end
  end
end


text:
using System;
using Azure.Core;

namespace Azure.ResourceManager.ContainerRegistry.Models
{
    /// <summary> The authorization properties for accessing the source code repository. </summary>
    public partial class SourceCodeRepoAuthInfo
    {
        /// <summary> Initializes a new instance of SourceCodeRepoAuthInfo. </summary>
        /// <param name="tokenType"> The type of Auth token. </param>
        /// <param name="token"> The access token used to access the source control provider. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="token"/> is null. </exception>
        public SourceCodeRepoAuthInfo(SourceCodeRepoAuthTokenType tokenType, string token)
        {
            Argument.AssertNotNull(token, nameof(token));

            TokenType = tokenType;
            Token = token;
        }

        /// <summary> Initializes a new instance of SourceCodeRepoAuthInfo. </summary>
        /// <param name="tokenType"> The type of Auth token. </param>
        /// <param name="token"> The access token used to access the source control provider. </param>
        /// <param name="refreshToken"> The refresh token used to refresh the access token. </param>
        /// <param name="scope"> The scope of the access token. </param>
        /// <param name="expireInSeconds"> Time in seconds that the token remains valid. </param>
        internal SourceCodeRepoAuthInfo(SourceCodeRepoAuthTokenType tokenType, string token, string refreshToken, string scope, int? expireInSeconds)
        {
            TokenType = tokenType;
            Token = token;
            RefreshToken = refreshToken;
            Scope = scope;
            ExpireInSeconds = expireInSeconds;
        }

        /// <summary> The type of Auth token. </summary>
        public SourceCodeRepoAuthTokenType TokenType { get; set; }
        /// <summary> The access token used to access the source control provider. </summary>
        public string Token { get; set; }
        /// <summary> The refresh token used to refresh the access token. </summary>
        public string RefreshToken { get; set; }
        /// <summary> The scope of the access token. </summary>
        public string Scope { get; set; }
        /// <summary> Time in seconds that the token remains valid. </summary>
        public int? ExpireInSeconds { get; set; }
    }
}


text:
@implementation SimpleActionSheetOptionCellInput

-(NSString*) cellType {
    return DTVCCellIdentifier_SimpleActionCell;
}

-(id) initSimpleActionSheetInputForObject:(id) managedObject forReturnKey:(NSString*)newReturnKey withOptions:(NSArray*) optionsArray withTitle:(NSString*) cellTitle  inSection:(NSString*) newSectionHeader{
    self = [super init];
    NSLog(@"action shee created with object %@" , [managedObject description]);
    if (self) {
        self = [self initType:DTVCCellIdentifier_SimpleActionCell forReturnKey:newReturnKey withTitle:cellTitle inSection:newSectionHeader];
        self.optionsArray=optionsArray;
        [self defineCellInputFormatType:[NSNumber numberWithInt:DTVCInputType_SimpleActionSheetCell_String]];
        [self createDefaultValueForObject:managedObject orValue:self.optionsArray[0]];

    }
    return self;
}
-(id) initSimpleActionSheetInputForObject:(id) managedObject forReturnKey:(NSString*)newReturnKey withDefault:(NSString*) defaultValue withOptions:(NSArray*) optionsArray withTitle:(NSString*) cellTitle  inSection:(NSString*) newSectionHeader{
    self = [super init];
    NSLog(@"action shee created with object %@" , [managedObject description]);
    if (self) {
        self = [self initType:DTVCCellIdentifier_SimpleActionCell forReturnKey:newReturnKey withTitle:cellTitle inSection:newSectionHeader];
        self.optionsArray=optionsArray;
        [self defineCellInputFormatType:[NSNumber numberWithInt:DTVCInputType_SimpleActionSheetCell_String]];
        [self createDefaultValueForObject:managedObject orValue:defaultValue];

    }
    return self;
}
-(id) initSimpleActionSheetInputForObject:(id) managedObject forReturnKey:(NSString*)newReturnKey withOptions:(NSArray*) optionsArray resultMap:(NSDictionary*) resultMap withTitle:(NSString*) cellTitle  inSection:(NSString*) newSectionHeader{
    self = [super init];
    NSLog(@"action shee created with object %@" , [managedObject description]);

    if (self) {
        self = [self initType:DTVCCellIdentifier_SimpleActionCell forReturnKey:newReturnKey withTitle:cellTitle inSection:newSectionHeader];
        self.optionsArray=optionsArray;
        self.resultsMap=resultMap;
        [self defineCellInputFormatType:[NSNumber numberWithInt:DTVCInputType_SimpleActionSheetCell_DictMap]];
    }
    return self;
}

#pragma mark - editable table cell delegate methods

-(void) cellSimpleActionSheetDidChange:(NSIndexPath *) cellIndexPath withIndex:(NSInteger)optionIndex{
    NSObject *newValue = [NSNumber numberWithInteger:optionIndex];
    [self updateValue:newValue];
    [self saveObjectContext];
}
-(void) cellSimpleActionSheetDidChange:(NSIndexPath *) cellIndexPath withString:(NSString*)optionString{
    NSLog(@"action sheet call to update value %@ %@",self.title,optionString);
    [self updateValue:optionString];
    [self updateContextWithValue:optionString];

    [self saveObjectContext];
}
-(void) cellSimpleActionSheetDidChange:(NSIndexPath *) cellIndexPath withObject:(NSObject*)optionObject{
    [self updateValue:optionObject];
    [self updateContextWithValue:optionObject];
    [self saveObjectContext];
}
@end


text:
import {Component} from '@angular/core';
import {Page, NavController, NavParams, Alert, Modal, ViewController, Events} from 'ionic-angular';
import {ChooseNoteGamePage} from '../choose-note-game/choose-note-game';
import {BasePage} from '../base/base-page';
import {PreferencesPage} from '../preferences/preferences';
import {NoteLevel} from '../../providers/note-service/note-service';

@Component({
  templateUrl: 'build/pages/training-choose/training-choose.html'
})
export class TrainingChoosePage extends BasePage {

  constructor(public nav: NavController,
              private navParams: NavParams,
              public viewCtrl: ViewController,
              public events: Events) {
     super(nav, events);
  }

  ionViewLoaded() {
    this.viewCtrl.showBackButton(false);
  }

  ionViewDidEnter() {
  }

  goToGameNote() {
    this.nav.push(ChooseNoteGamePage);
  }

  goToGameChord() {
    this.doAlert();
  }

  goToRecords() {
    this.doAlert();
  }

  doAlert() {
    let alert = Alert.create({
      title: 'Aviso!',
      subTitle: `Essa funcionalidade estará disponível em uma versão futura desse aplicativo.`,
      buttons: [
          {
              text: 'OK',
              handler: () => {

              }
          }
      ]
    });
    this.nav.present(alert);
  }

  presentFilter() {
    let modal = Modal.create(PreferencesPage);
    this.nav.present(modal);
  }

}


text:
package net.ontrack.extension.issue;

import java.util.Collection;

public interface IssueServiceConfigSubscription {

    boolean supportsService(String serviceId);

    Collection<? extends IssueServiceConfigSubscriber> getSubscribers(String serviceId, int configId);

    void unsubscribe(String serviceId, int configId);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta property="og:image" content="http://www.imagehover.io/imagehover-og.jpg">
    <meta property="og:site_name" content="Imagehover.css">
    <meta property="og:title" content="Imagehover.css - An Image Hover CSS Library">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Imagehover.css - An Image Hover CSS Library</title>
    <link href="css/demo-page.css" rel="stylesheet" media="all">
    <link href="css/imagehover.min.css" rel="stylesheet" media="all">
    <link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />

Fork me on GitHub

imagehover.css 2.0.0

A Scaleable & Light Image Hover CSS Library

Imagehover.css is a lovingly crafted CSS library allowing you to easily implement scaleable image hover effects. Choose from over 40 hover effect classes from a CSS library weighing in at a minified size of only 19KB.

Download

Version 2.0.0 - Github

The Mark-Up

Once you have included the imagehover.css. Place the following markup in to your HTML document. Edit the URL to your image and add your hover content. Then simply set the imagehover.css class of your choice to the containing figure element. In the example below this has been set to 'imghvr-fade'. A full list of hover effects and their classes can be found below.

<figure class="imghvr-fade">
    <img src="#">
    <figcaption>
        // Hover Content
    </figcaption>
    <a href="#"></a>
</figure>

Further information on usage can be found here - https://github.com/ciar4n/imagehover.css

The Classes

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fade</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-push-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-push-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-push-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-push-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-slide-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-slide-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-slide-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-slide-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-reveal-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-reveal-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-reveal-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-reveal-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-hinge-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-hinge-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-hinge-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-hinge-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-flip-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-flip-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-flip-diag-1</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-flip-diag-2</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-out-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-out-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-out-diag-1</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-out-diag-2</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-out-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-out-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-out-diag-1</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-shutter-in-out-diag-2</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fold-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fold-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fold-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fold-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-in</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-flip-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-zoom-out-flip-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-blur</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-switch-up</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-switch-down</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-switch-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-switch-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-in-top-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-in-top-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-in-bottom-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-in-bottom-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-out-top-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-out-top-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-out-bottom-left</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-pivot-out-bottom-right</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fall-away-horiz</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fall-away-vert</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fall-away-cc</textarea>

Hello World

Life is too important to be taken seriously!

          <textarea onclick="this.focus();this.select()" readonly="readonly">imghvr-fall-away-ccc</textarea>

License

Imagehover.css is open source, and made available under the MIT License. Distribute, use as-is, or modify to your liking in personal and commercial projects. Please retain the original readme and license files.

      Copyright ©©2019 ciar4n

Brought to you by
ciar4n


text:
package parameters

import (
	"encoding/json"
	"fmt"
	"regexp"
	"strings"
)

var keymapRegex = regexp.MustCompile(`^([^\[]+)\[(.+)\]\s*$`)

// ParseVariableJSON converts a JSON object into a map of keys and values
// Example:
// `{ "location" : "east", "group" : "demo" }' becomes map[location:east group:demo]
func ParseVariableJSON(params string) (map[string]interface{}, error) {
	var p map[string]interface{}
	err := json.Unmarshal([]byte(params), &p)
	if err != nil {
		return nil, fmt.Errorf("invalid parameters (%s)", params)
	}
	return p, nil
}

// ParseVariableAssignments converts a string array of variable assignments
// into a map of keys and values
// Example:
// [a=b c=abc1232=== d=banana d=pineapple] becomes map[a:b c:abc1232=== d:[banana pineapple]]
func ParseVariableAssignments(params []string) (map[string]interface{}, error) {
	variables := make(map[string]interface{})
	for _, p := range params {

		parts := strings.SplitN(p, "=", 2)
		if len(parts) < 2 {
			return nil, fmt.Errorf("invalid parameter (%s), must be in name=value format", p)
		}

		variable := strings.TrimSpace(parts[0])
		if variable == "" {
			return nil, fmt.Errorf("invalid parameter (%s), variable name is required", p)
		}
		value := strings.TrimSpace(parts[1])

		storedValue, ok := variables[variable]
		// Logic to add new value to map variables:
		// if variable DNE: add pair to variables as variable:value
		// if variable exists in form of variable:value, create array to hold old value&new value
		// if variable exists in form variable:[some values], append new value to existing array
		if !ok {
			variables[variable] = value // if there is no key, add key&value as string
		} else {
			switch storedValType := storedValue.(type) {
			case string:
				variables[variable] = []string{storedValType, value}
			case []string:
				variables[variable] = append(storedValType, value)
			}
		}
	}

	return variables, nil
}

// ParseKeyMaps converts a string array of key lookups
// into a map of the map name and key
// Example:
// [a[b] mysecret[foo.txt]] becomes map[a:b mysecret:foo.txt]
func ParseKeyMaps(params []string) (map[string]string, error) {
	keymap := map[string]string{}

	for _, p := range params {
		parts := keymapRegex.FindStringSubmatch(p)
		if len(parts) < 3 {
			return nil, fmt.Errorf("invalid parameter (%s), must be in MAP[KEY] format", p)
		}

		mapName := strings.TrimSpace(parts[1])
		if mapName == "" {
			return nil, fmt.Errorf("invalid parameter (%s), map is required", p)
		}

		key := strings.TrimSpace(parts[2])
		if key == "" {
			return nil, fmt.Errorf("invalid parameter (%s), key is required", p)
		}

		keymap[mapName] = key
	}

	return keymap, nil
}


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\TransitionTargetType.
 */

namespace jamesiarmes\PhpEws\Type;

/**
 * Specifies the target of the time zone transition.
 *
 * The target is either a time zone period or a group of time zone transitions.
 *
 * @package php-ews\Type
 */
class TransitionTargetType extends StringType
{
    /**
     * Indicates whether the time zone transition target is a time zone period
     * or of a group of time zone transitions.
     *
     * @since Exchange 2010
     *
     * @var \jamesiarmes\PhpEws\Enumeration\TransitionTargetKindType
     */
    public $Kind;
}


text:
#include "TCPSocket.h"
#include "TempFailure.h"

#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>

using namespace NET;

TCPSocket::TCPSocket()
: InternetSocket( STREAM, IPPROTO_TCP)
{}

TCPSocket::TCPSocket( Handle handle)
: InternetSocket( handle.release() )
{}

int TCPSocket::sendAll( const void* buffer, size_t len)
{
	size_t sent = 0;
	while( sent != len)
	{
		const char* buf = static_cast<const char*>(buffer) + sent;
		int ret = send( buf, len - sent);
		if( ret < 0) return ret;
		sent += static_cast<unsigned>(ret);
	}
	return sent;
}

void TCPSocket::listen( int backlog /* = 5 */)
{
	int ret = ::listen( m_socket, backlog);
	if( ret < 0)
		throw SocketException("listen failed, most likely another socket is already listening on the same port");
}

TCPSocket::Handle TCPSocket::accept() const
{
	int ret = ::accept( m_socket, nullptr, nullptr);
	if( ret < 0)
		throw SocketException("TCPSocket::accept failed");
	return Handle(ret);
}

TCPSocket::Handle TCPSocket::timedAccept( int timeout) const
{
	struct pollfd poll;
	poll.fd = m_socket;
	poll.events = POLLIN;

	int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout));

	if( ret == 0) return Handle();
	if( ret < 0) throw SocketException("Poll failed (receive)");

	ret = ::accept( m_socket, nullptr, nullptr);
	if( ret < 0)
		throw SocketException("TCPSocket::timedAccept failed");
	return Handle(ret);
}


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

<TITLE>
Notation (Axis API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.axis.types.Notation class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.axis.types

Class Notation

java.lang.Object
  org.apache.axis.types.Notation

All Implemented Interfaces:
java.io.Serializable

public class Notation
extends java.lang.Object
implements java.io.Serializable

Custom class for supporting XSD data type NOTATION.

Author:

Davanum Srinivas <dims@yahoo.com>

See Also:
XML Schema Part 1: 3.12 Notation Declarations,
Serialized Form

Constructor Summary

Notation()

Notation(NCName name,
         URI publicURI,
         URI systemURI)

Method Summary

 boolean
equals(java.lang.Object obj)

 NCName
getName()

 URI
getPublic()

 URI
getSystem()

static TypeDesc
getTypeDesc()

 int
hashCode()

          Returns the sum of the hashcodes of {name,publicURI,systemURI}
 for whichever properties in that set is non null.

 void
setName(NCName name)

 void
setPublic(URI publicURI)

 void
setSystem(URI systemURI)

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Notation

public Notation()

Notation

public Notation(NCName name,
                URI publicURI,
                URI systemURI)

Method Detail

getName

public NCName getName()

setName

public void setName(NCName name)

getPublic

public URI getPublic()

setPublic

public void setPublic(URI publicURI)

getSystem

public URI getSystem()

setSystem

public void setSystem(URI systemURI)

equals

public boolean equals(java.lang.Object obj)

hashCode

public int hashCode()

Returns the sum of the hashcodes of {name,publicURI,systemURI}
 for whichever properties in that set is non null.  This is
 consistent with the implementation of equals, as required by
 Object.hashCode.

Returns:
an int value

getTypeDesc

public static TypeDesc getTypeDesc()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2005 Apache Web Services Project. All Rights Reserved.


text:
using AspNetCoreComponentLibrary.Abstractions;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace AspNetCoreComponentLibrary
{
    public abstract class Repository<K, T> : IGetOptions, IRepository<K, T> /*where K : struct/*, IComparable<K>*/ where T : BaseDM<K>
    {
        protected DbSet<T> DbSet { get; set; }

        protected IStorageContext StorageContext;
        protected IStorage Storage { get; set; }
        protected ILoggerFactory LoggerFactory;
        protected ILogger Logger;
        protected ILogger LoggerMEF;
        protected ILocalizer2Garin Localizer2Garin;

        public void SetStorageContext(IStorageContext storageContext, IStorage storage, ILoggerFactory loggerFactory, ILocalizer2Garin localizer2Garin)
        {
            try
            {
                StorageContext = storageContext;
                Storage = storage;
                LoggerFactory = loggerFactory;
                Logger = LoggerFactory.CreateLogger(this.GetType().FullName);
                // для красоты в логах EntityFrameworkCore
                LoggerMEF = LoggerFactory.CreateLogger(Utils.MEFNameSpace);
                //if (StorageContext == null) Logger.LogCritical("AAAAAAAAAAAAAAAAAAA!!!!!!!!!");
                DbSet = (StorageContext as DbContext).Set<T>();
                Localizer2Garin = localizer2Garin;
            }
            catch (Exception e)
            {
                Logger.LogCritical(e.ToString());
            }
        }

        #region Translates

        protected virtual string TranslatesTable => "Translates";

        /// <summary>
        /// В теории переписав эту функцию в потомках можно отменить перевод.
        /// </summary>
        /// <param name="lang"></param>
        /// <param name="siteLanguages"></param>
        /// <returns></returns>
        protected virtual bool NeedTranslate(Languages lang, List<Languages> siteLanguages)
        {
            if (lang == null || lang.IsDefault) return false;
            if (siteLanguages == null || !siteLanguages.Any()) return false;
            return true;
        }

        public void TranslateItem(long siteid, Languages lang, List<Languages> siteLanguages, T item) //ref T item
        {
            if (!NeedTranslate(lang, siteLanguages)) return;
        }

        public void TranslateList(long siteid, Languages lang, List<Languages> siteLanguages, List<T> items) //ref T item
        {
            if (!NeedTranslate(lang, siteLanguages)) return;
        }
        public void TranslateOptionsVM(long siteid, Languages lang, List<Languages> siteLanguages, List<OptionVM> items, string SelectTitleName) //ref T item
        {
            if (!NeedTranslate(lang, siteLanguages)) return;
        }
        #endregion

        private void MakeTree(List<OptionVM> res, List<OptionVM> source, string parent, string SelectTreePrefix, string prefix = "", int deep = 0)
        {
            //if (res == null) return; // на всякий пожарный
            if (deep > 10) throw new Exception("Recursion");

            foreach (var val in source.Where(i => i.Parent == parent))
            {
                if (val.Value == "null") throw new Exception("Wrong data. Value cann't be null.");
                var title_str = val.Title;
                val.OriginalTitle = val.Title;
                val.Title = prefix + val.Title;
                res.Add(val);
                MakeTree(res, source, val.Value, SelectTreePrefix, prefix + string.Format(SelectTreePrefix, title_str), deep + 1);
            }
        }

        public List<OptionVM> GetOptions(long siteid, Languages lang, List<Languages> siteLanguages, string SelectValueName, string SelectTitleName, string SelectParentName, string SelectTreePrefix, bool SelectOnlyUnblocked)
        {
            if (string.IsNullOrWhiteSpace(SelectTitleName)) throw new ArgumentNullException(SelectTitleName);
            var propValue = typeof(T).GetProperty(SelectValueName ?? "Id");
            var propTitle = typeof(T).GetProperty(SelectTitleName);
            if (propValue == null) throw new Exception("Cannot find entitiy properties " + SelectValueName ?? "Id");
            if (propTitle == null) throw new Exception("Cannot find entitiy properties " + SelectTitleName);

            var query = SelectOnlyUnblocked ? GetUnblocked(siteid) : StartQuery(siteid);
            // установим сортировку по умолчанию на загрузку в кеш!
            //query = query.SetDefaultOrder();

            var res = new List<OptionVM>();
            var propParent = string.IsNullOrWhiteSpace(SelectParentName) ? null : typeof(T).GetProperty(SelectParentName);

            foreach (var val in query.Select(ExpressionHelper.SelectOptionVM<T>(propValue, propTitle, propParent)))
            {
                val.Title = string.IsNullOrWhiteSpace(val.Title) ? "-" : val.Title;
                res.Add(val);
            }

            TranslateOptionsVM(siteid, lang, siteLanguages, res, SelectTitleName);

            if (propParent != null)
            {
                var tree = new List<OptionVM>();
                MakeTree(tree, res, "null", SelectTreePrefix);
                return tree;
            }
            return res;
        }

        /*protected HtmlString LocalizeHtml(string key, params object[] args)
        {
            return Localizer2Garin.LocalizeHtml(key, args);
        }
        protected string Localize(string key, params object[] args)
        {
            return Localizer2Garin.Localize(key, args);
        }*/

        public virtual IQueryable<T> StartQuery(long siteid)
        {
            if (typeof(T).IsImplementsInterface(typeof(IWithSiteId)) && siteid > 0)
            {
                return DbSet
                    .AsNoTracking()
                    .Where(i => ((IWithSiteId)i).SiteId == siteid);
            }
            return DbSet.AsNoTracking();
        }

        public IQueryable<T> GetFiltered(long siteid, Form form)
        {
            //Logger.LogTrace("Repository GetFiltered for {0}. IWithSiteId = {1}", GetType().FullName, typeof(IWithSiteId).GetTypeInfo().IsAssignableFrom(typeof(T)));
            var query = StartQuery(siteid);

            if (form != null)
            {
                foreach (var field in form.Fields)
                {
                    var nameLC = field.PropertyName;

                    Logger.LogTrace("..... Filter {name} type: {type} ", nameLC, field.Type.Name);

                    var property = typeof(T).GetProperty(field.PropertyName);
                    if (property == null || property.PropertyType != field.Type) continue;

                    var values = field.GetValueAsObject();
                    if (values == null || !values.Any()) continue;

                    query = query.Where(ExpressionHelper.ComparePropertyWithConstArray<T>(nameLC, field.Type, values, field.Compare.GetCompareExpression()));
                }
            }
            return query;
        }

        public IQueryable<T> GetUnblocked(long siteid)
        {
            Logger.LogTrace("Repository GetUnblocked for {0}.", GetType().FullName);
            var query = StartQuery(siteid);

            if (typeof(T).IsImplementsInterface(typeof(IBlockable)))
                query = query.Where(i => !((IBlockable)i).IsBlocked);

            return query;
        }

        public virtual T Save(T item)
        {
            if (item == null) throw new ArgumentNullException();

            if (!BeforeSave(item)) return item;

            var isnew = Utils.CheckDefault(item.Id);

            if (!isnew)
            {
                DbSet.Update(item);
            }
            else
            {
                DbSet.Add(item);
            }
            (StorageContext as DbContext).SaveChanges();
            AfterSave(item, isnew);
            return item;
        }

        public virtual bool BeforeSave(T item)
        {
            Logger.LogTrace("Repository BeforeSave for {0}", item.Id);
            return true;
        }

        public virtual void AfterSave(T item, bool isnew)
        {
            Logger.LogTrace("Repository AfterSave for {0}", item.Id);
        }/**/

        public virtual void Remove(T item)
        {
            DbSet.Remove(item);
            (StorageContext as DbContext).SaveChanges();
        }

        protected virtual void SetBlock(K id, bool value)
        {
            //if (typeof(T) is IBlockable)
            if (typeof(T).IsImplementsInterface(typeof(IBlockable)))
            {
                T item = (T)Activator.CreateInstance(typeof(T));
                item.Id = id;
                ((IBlockable)item).IsBlocked = value;
                //DbSet.Update(item);
                Save(item);
            }
        }

        public void Block(K id) { SetBlock(id, true); }
        public void UnBlock(K id) { SetBlock(id, false); }

        public virtual void AddToCache(K id) { }
        public virtual void RemoveFromCache(K id) { }

        public virtual T this[K index]
        {
            get
            {
                return GetSingleFromDB(index);
            }
        }

        public virtual T GetSingleFromDB(K index)
        {
            using (new BLog(LoggerMEF, "GetSingleFromDB", GetType().FullName))
            {
                return DbSet
                    // очень важно!
                    .AsNoTracking()
                    .FirstOrDefault(i => i.Id.Equals(index));
            }
        }

        public virtual void ClearCache(long? siteid)
        {
            Logger.LogTrace("Repository ClearCache {0} for siteid={1}", this.GetType().FullName, siteid);
        }
    }
}


text:
package de.tudarmstadt.ukp.clarin.webanno.brat.display.model;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import org.junit.Test;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

import de.tudarmstadt.ukp.clarin.webanno.support.JSONUtil;

public class EntityTest
{
    @Test
    public void toJsonTest()
        throws IOException
    {
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();

        String json = JSONUtil.toJsonString(jsonConverter, new Entity(new VID(1, 2), "type",
                new Offsets(1, 2), "label", "color"));

        assertEquals("[\"1.2\",\"type\",[[1,2]],\"label\",\"color\"]", json);
    }
}


text:
require "spec_helper"

describe "Relevance::Tarantula::Link" do
  include ActionView::Helpers::UrlHelper

  it "does not raise an error when initializing without href attribtue" do
    link = make_link(Hpricot('foo').at('a'))
    link.href.should == nil
    link.meth.should == :get
  end

  it "parses anchor tags" do
    link = make_link(Hpricot('foo').at('a'))
    link.href.should == '/foo'
    link.meth.should == :get
  end

  it "parses anchor tags with POST 'method'" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :post
  end

  it "parses anchor tags with POST data-method" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :post
  end

  it "parses anchor tags with PUT 'method'" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :put
  end

  it "parses anchor tags with PUT data-method" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :put
  end

  it "parses anchor tags with PATCH data-method" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :patch
  end

  it "parses anchor tags with DELETE 'method'" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :delete
  end

  it "parses anchor tags with DELETE data-method" do
    link = make_link(Hpricot(%Q{foo}).at('a'))
    link.href.should == '/foo'
    link.meth.should == :delete
  end

  it "parses link tags with text" do
    link = make_link(Hpricot('<link href="/bar">bar').at('link'))
    link.href.should == '/bar'
    link.meth.should == :get
  end

  it "parses link tags without text" do
    link = make_link(Hpricot('<link href="/bar" />').at('link'))
    link.href.should == '/bar'
    link.meth.should == :get
  end

  it 'remembers link referrer if there is one' do
    link = make_link('/url', stub_everything, '/some-referrer')
    link.referrer.should == '/some-referrer'
  end

  it "does two things when crawled: follow, log, and handle" do
    crawler = Relevance::Tarantula::Crawler.new
    link = make_link('/foo', crawler)

    response = stub(:code => "200")
    crawler.expects(:follow).returns(response)
    link.expects(:log)
    crawler.expects(:handle_link_results)

    link.crawl
  end

  # method_javascript_function needs this method
  def protect_against_forgery?
    false
  end

end

describe "possible conflict when user has an AR model named Link" do
  it "does not taint Object with Relevance::Tarantula" do
    Object.ancestors.should_not include(Relevance::Tarantula)
  end

  it "doesnt break with a Link model" do
    lambda {
      class Link < ActiveRecord::Base
      end
    }.should_not raise_error
  end

end


text:
package org.apache.pulsar.functions.instance;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.apache.pulsar.functions.api.Record;
import org.apache.pulsar.functions.source.PulsarRecord;
import org.mockito.Mockito;
import org.testng.annotations.Test;

public class SinkRecordTest {

    @Test
    public void testCustomAck() {

        PulsarRecord pulsarRecord = Mockito.mock(PulsarRecord.class);
        SinkRecord sinkRecord = new SinkRecord<>(pulsarRecord, new Object());

        sinkRecord.cumulativeAck();
        Mockito.verify(pulsarRecord, Mockito.times(1)).cumulativeAck();

        sinkRecord = new SinkRecord(Mockito.mock(Record.class), new Object());
        try {
            sinkRecord.individualAck();
            fail("Should throw runtime exception");
        } catch (Exception e) {
            assertTrue(e instanceof RuntimeException);
            assertEquals(e.getMessage(), "SourceRecord class type must be PulsarRecord");
        }
    }
}


text:
All notable changes of the PHP_CodeCoverage 3.3 release series are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [3.3.3] - 2016-05-27

### Fixed

* Fixed [#438](https://github.com/sebastianbergmann/php-code-coverage/issues/438): Wrong base directory for Clover reports

## [3.3.2] - 2016-05-25

### Changed

* The constructor of `PHP_CodeCoverage_Report_Text` now has default values for its parameters

## [3.3.1] - 2016-04-08

### Fixed

* Fixed handling of lines that contain `declare` statements

## [3.3.0] - 2016-03-03

### Added

* Added support for whitelisting classes for the unintentionally covered code unit check

[3.3.3]: https://github.com/sebastianbergmann/php-code-coverage/compare/3.3.2...3.3.3
[3.3.2]: https://github.com/sebastianbergmann/php-code-coverage/compare/3.3.1...3.3.2
[3.3.1]: https://github.com/sebastianbergmann/php-code-coverage/compare/3.3.0...3.3.1
[3.3.0]: https://github.com/sebastianbergmann/php-code-coverage/compare/3.2...3.3.0


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>VacayPay</title>
    <link rel="stylesheet" type="text/css" href="styles/styles.css" />

VacayPay

          Overview
          New Event


text:
"""
Tools to handle reads sequenced with unique molecular identifiers (UMIs).
"""
from __future__ import print_function

import editdist
import gzip
import os
import re
import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from collections import Counter, defaultdict
from itertools import islice, izip
from pysam import index, Samfile

try:
    from itertools import izip as zip
except ImportError:
    pass

from ._version import __version__

IUPAC = {
    "A": "A",
    "T": "T",
    "C": "C",
    "G": "G",
    "R": "GA",
    "Y": "TC",
    "M": "AC",
    "K": "GT",
    "S": "GC",
    "W": "AT",
    "H": "ACT",
    "B": "GTC",
    "V": "GCA",
    "D": "GAT",
    "N": "GATC"
}
UMI_REGEX = re.compile(r'UMI_([\w]*)')
gzopen = lambda f: gzip.open(f) if f.endswith(".gz") else open(f)

class UMINotFound(Exception):
    pass

class Fastq(object):
    """FASTQ record. Holds record of name, sequence, and quality scores.

    >>> fq = Fastq(["@illumina_naming_scheme", "ACTGACTG", "+", "KKKKKKKK"])
    >>> fq.name, fq.seq, fq.qual
    ('illumina_naming_scheme', 'ACTGACTG', 'KKKKKKKK')
    >>> fq
    Fastq(illumina_naming_scheme)
    >>> print(fq)
    @illumina_naming_scheme
    ACTGACTG
    +
    KKKKKKKK
    >>> fq = Fastq(["@fail", "ACTGACTG", "+", "KKK"]) # doctest: +ELLIPSIS
    Traceback (most recent call last):
     ...
    AssertionError: Seq and Qual vary in length
    """
    def __init__(self, args):
        self.name = args[0][1:]
        self.seq = args[1]
        self.qual = args[3]
        assert len(self.seq) == len(self.qual), "Seq and Qual vary in length"

    def __repr__(self):
        return "Fastq(%s)" % self.name

    def __str__(self):
        return "@%s\n%s\n+\n%s" % (self.name, self.seq, self.qual)

def is_indexed(bam):
    if not os.path.exists("%s.bai" % bam):
        # this returns nothing even when it fails
        index(bam)
        if not os.path.exists("%s.bai" % bam):
            print("index not found for %s and indexing failed" % bam)
            sys.exit(1)
    return True

def umi_from_name(name):
    """Extracts the UMI sequence from the read name.

    Args:
        name (str): Name of the sequence

    Returns:
        str: UMI sequence

    >>> umi_from_name("cluster_1017333:UMI_GCCGCA")
    'GCCGCA'
    >>> umi_from_name("TEST") # doctest: +ELLIPSIS
    Traceback (most recent call last):
     ...
    UMINotFound: TEST
    """
    try:
        umi = UMI_REGEX.findall(name)[0].strip()
    except IndexError:
        raise UMINotFound(name)
    return umi

def is_similar(query, targets, n):
    """Tests target set of sequences to the query.

    Args:
        query (str): query sequence
        targets (set): unique sequences
        n (int): allowable mismatches when comparing a query to a given sequence of the targets

    Returns:
        bool

    >>> import editdist
    >>> s = "ACTGA"
    >>> ts_1 = {"ACTGG"}
    >>> ts_2 = {"ACTCC", "ACTGG"}
    >>> ts_3 = {"ACTCC", "ACTTT"}
    >>> n = 1
    >>> is_similar(s, ts_1, n)
    True
    >>> is_similar(s, ts_2, n)
    True
    >>> is_similar(s, ts_3, n)
    False
    """
    if targets:
        for target in targets:
            if editdist.distance(target, query) <= n:
                return True
    return False

def process_bam(abam, bbam, mismatches=0):
    """Removes duplicate reads characterized by their UMI at any given start location.

    Args:
        abam (str): Input bam with potential duplicate UMIs
        bbam (str): Output bam after removing duplicate UMIs
        mismatches (Optional[int]): Allowable edit distance between UMIs
    """
    is_indexed(abam)
    with Samfile(abam, 'rb') as in_bam, Samfile(bbam, 'wb', template=in_bam) as out_bam:

        for chrom in in_bam.references:
            print("processing chromosome", chrom, file=sys.stderr)

            umi_idx = defaultdict(set)
            read_counts = Counter()

            for read in in_bam.fetch(chrom):
                if read.is_unmapped:
                    continue

                # get the iupac umi sequence
                try:
                    umi = umi_from_name(read.qname)
                except UMINotFound:
                    print("You may be processing alignments that haven't been annotated with UMIs!", file=sys.stderr)
                    raise

                # get actual read start
                # read.pos accounts for 5' soft clipping
                if read.is_reverse:
                    # read.alen alignment length accounting for 3' soft clipping
                    # UMIs are then compared to reads with the same start
                    read_start = read.pos + read.alen
                else:
                    read_start = read.pos

                # add count for this start; counts all reads
                read_counts[read_start] += 1

                # check if UMI seen
                if umi in umi_idx[read_start]:
                    continue

                # check if UMI is similar enough to another that has been seen
                if mismatches > 0 and is_similar(umi, umi_idx[read_start], mismatches):
                    # do not count; group similar UMIs into one
                    continue

                # keep track of unique UMIs - set eliminates duplicates
                umi_idx[read_start].add(umi)

                out_bam.write(read)

            # process before and after counts over chrom
            for start, before_count in sorted(read_counts.items()):
                print(chrom, start, start + 1, before_count, len(umi_idx[start]), sep="\t")

def readfq(filehandle):
    """Fastq iterator.

    Args:
        filehandle (file): open file handle

    Yields:
        Fastq
    """
    fqclean = (x.strip("\r\n") for x in filehandle if x.strip())
    while True:
        rd = [x for x in islice(fqclean, 4)]
        if not rd:
            raise StopIteration
        assert all(rd) and len(rd) == 4
        yield Fastq(rd)

def valid_umi(iupac, umi):
    """Parse UMI sequence to validate against IUPAC sequence.

    Args:
        iupac (str): IUPAC sequence
        umi (str): observed sequence

    Returns:
        bool

    >>> valid_umi("NNNV", "ACGT")
    False
    >>> valid_umi("NNNV", "ACGG")
    True
    """
    for code, base in zip(iupac, umi):
        try:
            if base not in IUPAC[code]:
                return False
        except KeyError:
            return False
    return True

def clip_umi(record, n, end):
    """Removes UMI sequence from read, trims respective length from qual, then appends UMI onto read name.

    Args:
        record (Fastq): `Fastq` record
        n (int): Length of the UMI
        end (int): The end of the read on which the UMI resides

    Returns:
        Fastq else str: The record or the failed UMI sequence

    >>> fq = Fastq(["@cluster_455 2","GGGGGAGCCACGAGGTGTGTTTTATTTTCATTATTC","+","C===>=B=@:<;4A;8=9?6EEC0?DDA72B@3EB4"])
    >>> r, umi = clip_umi(fq, 6, 5)
    >>> r
    Fastq(cluster_455:UMI_GGGGGA 2)
    >>> r.seq
    'GCCACGAGGTGTGTTTTATTTTCATTATTC'
    >>> fq = Fastq(["@cluster_455 2","GGXXGAGCCACGAGGTGTGTTTTATTTTCATTATTC","+","C===>=B=@:<;4A;8=9?6EEC0?DDA72B@3EB4"])
    >>> r, umi = clip_umi(fq, 6, 5)
    >>> umi
    'GGXXGA'
    >>> fq = Fastq(["@cluster_455 2","GGXXGAGCCACGAGGTGTGTTTTATTTTCATTATTC","+","C===>=B=@:<;4A;8=9?6EEC0?DDA72B@3EB4"])
    >>> r, umi = clip_umi(fq, 5, 3)
    >>> r.seq
    'GGXXGAGCCACGAGGTGTGTTTTATTTTCAT'
    >>> r.qual
    'C===>=B=@:<;4A;8=9?6EEC0?DDA72B'
    """
    if end == 5:
        umi = record.seq[:n]
        record.seq = record.seq[n:]
        record.qual = record.qual[n:]
    else:
        umi = record.seq[-n:]
        record.seq = record.seq[:-n]
        record.qual = record.qual[:-n]
    try:
        name, pair = record.name.split(" ", 1)
        record.name = "{name}:UMI_{umi} {pair}".format(name=name, umi=umi, pair=pair)
    except ValueError:
        record.name = "{name}:UMI_{umi}".format(name=record.name, umi=umi)
    return record, umi

def process_fastq(fastq, umi, end=5, invalid=None, verbose=False, top=10):
    """For every valid umi, trim while incorporating UMI into read name.

    Args:
        fastq (str): file path to unprocessed FASTQ file
        umi (str): IUPAC sequence of UMI
        end (Optional[int]): 5 or 3, which ever end you're UMI is located on
        invalid (Optional[str]): file path to save invalid, non-passing reads
        verbose (Optional[bool]): True prints basic stats on observed UMIs
        top (Optional[int]): Number of the the top invalid UMIs to print out
    """
    umi_stats = Counter()
    umi = umi.upper()
    u_leng = len(umi)
    if invalid:
        with gzopen(fastq) as fq, open(invalid, 'w') as ofh:
            for read in readfq(fq):
                read, observed_umi = clip_umi(read, u_leng, end)
                if not valid_umi(umi, observed_umi):
                    umi_stats.update([observed_umi])
                    print(read, file=ofh)
                else:
                    print(read)
    else:
        with gzopen(fastq) as fq:
            for read in readfq(fq):
                read, observed_umi = clip_umi(read, u_leng, end)
                if not valid_umi(umi, observed_umi):
                    umi_stats.update([observed_umi])
                else:
                    print(read)
    if verbose:
        print("Invalid UMI Total:", sum(umi_stats.values()), file=sys.stderr)
        print("Unique UMIs Removed:", len(list(umi_stats)), file=sys.stderr)
        print("Top", top, "Invalid UMIs:", file=sys.stderr)
        for umi, val in umi_stats.most_common(top):
            print(umi, val, sep="\t", file=sys.stderr)

def main():

    def _file_exists(parser, arg):
        if not os.path.exists(arg):
            parser.error("The file %s does not exist" % arg)
        if not os.path.isfile(arg):
            parser.error("Expected file, not folder (%s)" % arg)
        return arg

    p = ArgumentParser(description=__doc__)
    p.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__))
    subp = p.add_subparsers(help='commands', dest='command')

    # fastq processing
    fastq = subp.add_parser('trim', description=("Trims the UMI sequence from the read, incorporating the unique "
                                                 "sequence in the read name facilitating filtering of the alignments."),
                            formatter_class=ArgumentDefaultsHelpFormatter,
                            help="trim UMI and incorporate sequence into read name")
    fastq.add_argument('fastq', metavar='FASTQ', type=lambda x: _file_exists(p, x),
                       help='reads with untrimmed UMI')
    fastq.add_argument('umi', metavar='UMI',
                       help='IUPAC UMI sequence, e.g. NNNNNV')
    fastq.add_argument('--end', choices=[5, 3], default=5, type=int,
                       help="UMI location on the read")
    fastq.add_argument('--invalid', metavar='STR',
                       help='save invalid, non-passing reads to this file')
    fastq.add_argument('--verbose', action='store_true',
                       help="print UMI stats to stderr")
    fastq.add_argument('--top', metavar='INT', type=int, default=10,
                       help="when verbose, print this many of the top filtered UMI sequences")

    # bam processing
    bam = subp.add_parser('rmdup', description=("Removes duplicate reads, that were previously characterized by "
                                                "their UMI, at any given start location. Coverage differences before "
                                                "and after are written to STDOUT as BED3+."),
                          formatter_class=ArgumentDefaultsHelpFormatter,
                          help="remove duplicate UMI entries from all start positions")
    bam.add_argument('abam', metavar='INPUT_BAM', type=lambda x: _file_exists(p, x),
                     help='bam with UMI in read name')
    bam.add_argument('bbam', metavar='OUTPUT_BAM',
                     help='non-duplicate UMIs at any given start position')
    bam.add_argument('-m', '--mismatches', metavar='INT', default=0, type=int,
                     help="allowable mismatches when comparing UMIs at any given start location")

    args = p.parse_args()
    if args.command == 'trim':
        process_fastq(args.fastq, args.umi, end=args.end, invalid=args.invalid,
                      verbose=args.verbose, top=args.top)
    elif args.command == 'rmdup':
        process_bam(args.abam, args.bbam, mismatches=args.mismatches)

if __name__ == "__main__":
    main()


text:
/**
@module ember
*/

import { deprecate } from '@ember/debug';
import { DeprecationOptions } from '@ember/debug/lib/deprecate';
import { get } from './property_get';
import { set } from './property_set';

/**
  Used internally to allow changing properties in a backwards compatible way, and print a helpful
  deprecation warning.

  @method deprecateProperty
  @param {Object} object The object to add the deprecated property to.
  @param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing).
  @param {String} newKey The property that will be aliased.
  @private
  @since 1.7.0
*/

export function deprecateProperty(
  object: object,
  deprecatedKey: string,
  newKey: string,
  options?: DeprecationOptions
): void {
  function _deprecate(): void {
    deprecate(
      `Usage of \`${deprecatedKey}\` is deprecated, use \`${newKey}\` instead.`,
      false,
      options
    );
  }

  Object.defineProperty(object, deprecatedKey, {
    configurable: true,
    enumerable: false,
    set(value): any {
      _deprecate();
      set(this, newKey, value);
    },
    get(): any {
      _deprecate();
      return get(this, newKey);
    },
  });
}


text:
#if NUnit
using TestFixtureAttribute = NUnit.Framework.TestFixtureAttribute;
using TestAttribute = NUnit.Framework.TestAttribute;
#elif MsTest
using TestFixtureAttribute = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#elif Xunit
using TestAttribute = Xunit.FactAttribute;
#endif
using program1.MyLibrary;
using System.Collections.Generic;
using UntestableLibrary;
using UntestableLibrary.Prig;
using Urasandesu.Prig.Framework;
using Test.program1.TestUtilities;

namespace Test.program1.MyLibrary
{
    [TestFixture]
    public class ChatRoomTest
    {
        delegate bool ReplyInformationFunc(ULChatBot @this, ULTypeOfFeedback input, out string reply, ref ULActions action, out ULTypeOfFeedback recommendation);

        [Test]
        public void Start_on_execute_should_return_expected()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                var actualInputs = new List<ULTypeOfFeedback>();

                var proxy1 = new Proxy<OfPProxyULChatBot>();
                proxy1.Setup<ReplyInformationFunc>(_ => _.ReplyInformationULTypeOfFeedbackStringRefULActionsRefULTypeOfFeedbackRef()).Body =
                    (ULChatBot @this, ULTypeOfFeedback input, out string reply, ref ULActions action, out ULTypeOfFeedback recommendation) =>
                    {
                        actualInputs.Add(input);
                        reply = "1";
                        recommendation = ULTypeOfFeedback.Suggestion;
                        return true;
                    };

                var proxy2 = new Proxy<OfPProxyULChatBot>();
                proxy2.Setup<ReplyInformationFunc>(_ => _.ReplyInformationULTypeOfFeedbackStringRefULActionsRefULTypeOfFeedbackRef()).Body =
                    (ULChatBot @this, ULTypeOfFeedback input, out string reply, ref ULActions action, out ULTypeOfFeedback recommendation) =>
                    {
                        actualInputs.Add(input);
                        reply = "2";
                        recommendation = ULTypeOfFeedback.Incomprehensible;
                        return true;
                    };

                // Act
                new ChatRoom().Start(ULTypeOfFeedback.Praise, (ULChatBot)proxy1.Target, (ULChatBot)proxy2.Target);

                // Assert
                var expectedInputs = new[] { ULTypeOfFeedback.Praise, ULTypeOfFeedback.Suggestion };
                CollectionAssert.AreEqual(expectedInputs, actualInputs);
            }
        }
    }
}


text:
package com.google.cloud.solutions.cloudadventure.world;

import com.google.api.services.cloudadventure.model.Player;
import com.google.api.services.cloudadventure.model.Tile;

import android.util.Log;

import java.util.List;

/**
 * Utility class to aid with map navigation in the game.
 */
public class MapUtils {
  /**
   * This class enumerates the types of cardinal directions available. Note for developers: be very
   * careful when changing the order of declaration in this enum, since values() is called elsewhere
   * in this application.
   * <p>
   * NOTE: Updates to this enum need to be reflected in the corresponding enum class in the backend
   */
  public enum Cardinal {
    NORTH, EAST, SOUTH, WEST
  }

  /**
   * This class maps the ever-changing relationships between the cardinal directions and the
   * relative directions of a {@link Player}. One of these mappers is instantiated for each
   * {@link Player} in the game, and is updated each time the player moves and changes direction.
   */
  public static class DirectionMapper {
    private Cardinal[] cardinalDirections = Cardinal.values();

    private Cardinal forward = Cardinal.NORTH;
    private Cardinal right = Cardinal.EAST;
    private Cardinal back = Cardinal.SOUTH;
    private Cardinal left = Cardinal.WEST;

    public DirectionMapper(final Cardinal initialFacing) {
      switch (initialFacing) {
        case NORTH:
          break;
        case EAST:
          turnRight();
          break;
        case SOUTH:
          turnAround();
          break;
        case WEST:
          turnLeft();
          break;
      }
    }

    public Cardinal getFrontCardinal() {
      return forward;
    }

    public Cardinal getRightCardinal() {
      return right;
    }

    public Cardinal getBehindCardinal() {
      return back;
    }

    public Cardinal getLeftCardinal() {
      return left;
    }

    public void turnRight() {
      forward = cardinalDirections[(forward.ordinal() + 1 + 4) % 4];
      right = cardinalDirections[(right.ordinal() + 1 + 4) % 4];
      back = cardinalDirections[(back.ordinal() + 1 + 4) % 4];
      left = cardinalDirections[(left.ordinal() + 1 + 4) % 4];
    }

    public void turnAround() {
      forward = cardinalDirections[(forward.ordinal() + 2 + 4) % 4];
      right = cardinalDirections[(right.ordinal() + 2 + 4) % 4];
      back = cardinalDirections[(back.ordinal() + 2 + 4) % 4];
      left = cardinalDirections[(left.ordinal() + 2 + 4) % 4];
    }

    public void turnLeft() {
      forward = cardinalDirections[(forward.ordinal() - 1 + 4) % 4];
      right = cardinalDirections[(right.ordinal() - 1 + 4) % 4];
      back = cardinalDirections[(back.ordinal() - 1 + 4) % 4];
      left = cardinalDirections[(left.ordinal() - 1 + 4) % 4];
    }
  }

  /**
   * Given a {@link Player} and cardinal direction, finds the next {@link Tile} in that direction.
   *
   * @param player a {@link Player} with a current {@link Tile} location
   * @param direction the direction in which to find the next tile
   * @return {@link Tile}
   */
  public static Tile getNextTile(Player player, Cardinal direction) {
    Tile currentTile = player.getCurrentTile();
    List<List<Tile>> grid = player.getMaze().getGrid();
    try {
      switch (direction) {
        case NORTH:
          return grid.get(currentTile.getCoord().getX()).get(currentTile.getCoord().getY() + 1);
        case EAST:
          return grid.get(currentTile.getCoord().getX() + 1).get(currentTile.getCoord().getY());
        case SOUTH:
          return grid.get(currentTile.getCoord().getX()).get(currentTile.getCoord().getY() - 1);
        case WEST:
          return grid.get(currentTile.getCoord().getX() - 1).get(currentTile.getCoord().getY());
      }
    } catch (IndexOutOfBoundsException e) {
      Log.wtf("MapUtils", "Should not have been able to call this method with direction "
          + direction + ", because the UI should not have presented the player with the option.");
    }
    Log.wtf("MapUtils", "Why does an available direction exist such as " + direction + " here?");
    return currentTile;
  }
}