text:
# grunt-replace [![Build Status](https://secure.travis-ci.org/outaTiME/grunt-replace.png?branch=master)](http://travis-ci.org/outaTiME/grunt-replace)

> Replace text patterns with [applause](https://github.com/outaTiME/applause).

## Install

From NPM:

```shell
npm install grunt-replace --save-dev
```

## Replace Task

Assuming installation via NPM, you can use `grunt-replace` in your gruntfile like this:

```javascript
module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-replace');
  grunt.initConfig({
    replace: {
      dist: {
        options: {
          patterns: [
            {
              match: 'foo',
              replacement: 'bar'
            }
          ]
        },
        files: [
          {expand: true, flatten: true, src: ['src/index.html'], dest: 'build/'}
        ]
      }
    }
  });
  grunt.registerTask('default', 'replace');
};
```

### Options

@@options

#### excludeBuiltins
Type: `Boolean`
Default: `false`

If set to `true`, we exclude built-in matching rules.

#### force
Type: `Boolean`
Default: `true`

Force the copy of files even when those files don't have any match found for replacement.

#### noProcess
Type: `String`

This option is an advanced way to control which file contents are processed.

> `processContentExclude` has been renamed to `noProcess` and the option name will be removed in the future.

#### encoding
Type: `String`
Default: `grunt.file.defaultEncoding`

The file encoding to copy files with.

#### mode
Type: `Boolean` or `Number`
Default: `false`

Whether to copy or set the existing file permissions. Set to `true` to copy the existing file permissions. Or set to the mode, i.e.: `0644`, that copied files will be set to.

#### silent
Type: `Boolean`
Default: `false`

If set to `true`, removes the output from stdout.

#### pedantic
Type: `Boolean`
Default: `false`

If set to `true`, the task will fail with a `grunt.fail.warn` when no matches are present.

### Built-in Replacements

Few matching rules are provided by default and can be used anytime (these will be affected by the `options` given):

 *  `__SOURCE_FILE__`:

    Replace match with the source file.

 *  `__SOURCE_PATH__`:

    Replace match with the path of source file.

 *  `__SOURCE_FILENAME__`:

    Replace match with the filename of source file.

 *  `__TARGET_FILE__`:

    Replace match with the target file.

 *  `__TARGET_PATH__`:

    Replace match with the path of target file.

 *  `__TARGET_FILENAME__`:

    Replace match with the filename of target file.

> If you are looking how to use an `built-in` replacements, check out the [How to insert filename in target](#how-to-insert-filename-in-target) usage.

### Usage Examples

#### Basic

File `src/manifest.appcache`:

```
CACHE MANIFEST
# @@timestamp

CACHE:

favicon.ico
index.html

NETWORK:
*
```

Gruntfile, define pattern (for timestamp) and the source files for lookup:

```js
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'timestamp',
          replacement: '<%= grunt.template.today() %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['src/manifest.appcache'], dest: 'build/'}
    ]
  }
}
```

#### Multiple matching

File `src/manifest.appcache`:

```
CACHE MANIFEST
# @@timestamp

CACHE:

favicon.ico
index.html

NETWORK:
*
```

File `src/humans.txt`:

```
              __     _
   _    _/__  /./|,//_`
  /_//_// /_|///  //_, outaTiME v.@@version

/* TEAM */
  Web Developer / Graphic Designer: Ariel Oscar Falduto
  Site: http://www.outa.im
  Twitter: @outa7iME
  Contact: afalduto at gmail dot com
  From: Buenos Aires, Argentina

/* SITE */
  Last update: @@timestamp
  Standards: HTML5, CSS3, robotstxt.org, humanstxt.org
  Components: H5BP, Modernizr, jQuery, Twitter Bootstrap, LESS, Jade, Grunt
  Software: Sublime Text 2, Photoshop, LiveReload

```

Gruntfile:

```js
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'version',
          replacement: '<%= pkg.version %>'
        },
        {
          match: 'timestamp',
          replacement: '<%= grunt.template.today() %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['src/manifest.appcache', 'src/humans.txt'], dest: 'build/'}
    ]
  }
}
```

#### Cache busting

File `src/assets/index.html`:

```html
<head>
  <link rel="stylesheet" href="/css/style.css?rel=@@timestamp">
  <script src="/js/app.js?rel=@@timestamp"></script>
</head>
```

Gruntfile:

```js
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'timestamp',
          replacement: '<%= new Date().getTime() %>'
        }
      ]
    },
    files: [
      {src: ['src/assets/index.html'], dest: 'build/index.html'}
    ]
  }
}
```

#### Include file

File `src/index.html`:

```html
<body>
  @@include
</body>
```

Gruntfile:

```js
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'include',
          replacement: '<%= grunt.file.read("includes/content.html") %>'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['src/index.html'], dest: 'build/'}
    ]
  }
}
```

#### Regular expression

File `src/username.txt`:

```
John Smith
```

Gruntfile:

```js
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: /(\w+)\s(\w+)/,
          replacement: '$2, $1' // replaces "John Smith" to "Smith, John"
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['src/username.txt'], dest: 'build/'}
    ]
  }
}
```

#### Lookup for `foo` instead of `@@foo`

Gruntfile:

```js
// option 1 (explicitly using an regexp)
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: /foo/g,
          replacement: 'bar'
        }
      ]
    },
    files: [
      {expand: true, flatten: true, src: ['src/foo.txt'], dest: 'build/'}
    ]
  }
}

// option 2 (easy way)
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'foo',
          replacement: 'bar'
        }
      ],
      usePrefix: false
    },
    files: [
      {expand: true, flatten: true, src: ['src/foo.txt'], dest: 'build/'}
    ]
  }
}

// option 3 (old way)
replace: {
  dist: {
    options: {
      patterns: [
        {
          match: 'foo',
          replacement: 'bar'
        }
      ],
      prefix: '' // remove prefix
    },
    files: [
      {expand: true, flatten: true, src: ['src/foo.txt'], dest: 'build/'}
    ]
  }
}
```

#### How to insert filename in target

File `src/app.js`:

```js
// filename: @@__SOURCE_FILENAME__

var App = App || (function () {

  return {

    // app contents

  };

}());

window.App = App;
```

Gruntfile:

```js
replace: {
  dist: {
    options: {
      // pass, we use built-in replacements
    },
    files: [
      {expand: true, flatten: true, src: ['src/**/*.js'], dest: 'build/'}
    ]
  }
}
```

## Release History

 * 2015-08-06   v0.9.3   New pedantic option (thanks [@donkeybanana](https://github.com/donkeybanana)). Fix issue with special characters attributes ($$, $&, $`, $', $n or $nn) on JSON, YAML and CSON.
 * 2015-05-07   v0.9.2   Fix regression issue with empty string in replacement.
 * 2015-05-01   v0.9.1   Better output.
 * 2015-05-01   v0.9.0   Output available via --verbose flag. The mode option now also applies to directories. Fix path issue on Windows. Display warning message when no matches and overall of replacements. Update to [applause](https://github.com/outaTiME/applause) v0.4.0.
 * 2014-10-10   v0.8.0   Escape regexp when matching type is `String`.
 * 2014-08-26   v0.7.9   Fixes backwards incompatible changes introduced in NPM.
 * 2014-06-10   v0.7.8   Remove node v.8.0 support and third party dependencies updated. Force flag now are true by default.
 * 2014-04-20   v0.7.7   JSON / YAML / CSON as function supported. Readme updated (thanks [@milanlandaverde](https://github.com/milanlandaverde)).
 * 2014-03-23   v0.7.6   Readme updated.
 * 2014-03-22   v0.7.5   Modular core renamed to [applause](https://github.com/outaTiME/applause). Performance improvements. Expression flag removed. New pattern matching for CSON object. More test cases, readme updated and code cleanup.
 * 2014-03-21   v0.7.4   Test cases in Mocha, readme updated and code cleanup.
 * 2014-03-17   v0.7.3   Update script files for readme file generation.
 * 2014-03-12   v0.7.2   Typo error, replace task name again.
 * 2014-03-11   v0.7.1   Task name update.
 * 2014-03-11   v0.7.0   New [pattern-replace](https://github.com/outaTiME/pattern-replace) modular core for replacements.
 * 2014-02-13   v0.6.2   Attach process data for function replacements (source / target). Add delimiter option for object as replacement. Dependencies updated.
 * 2014-02-06   v0.6.1   Rename excludePrefix to preservePrefix (more readable) and adds usePrefix flag. Support the noProcess option like [grunt-contrib-copy](https://github.com/gruntjs/grunt-contrib-copy).
 * 2014-02-05   v0.6.0   Object replacement allowed. New excludePrefix flag (thanks [@shinnn](https://github.com/shinnn)). Encoding / Mode options added.
 * 2013-09-18   v0.5.1   New pattern matching for JSON object.
 * 2013-09-17   v0.5.0   Regular expression matching now supported and notation has been updated but is backward compatible.
 * 2013-05-03   v0.4.4   Fix escape $ before performing regexp replace (thanks [@warpech](https://github.com/warpech)).
 * 2013-04-14   v0.4.3   Detect path destinations correctly on Windows.
 * 2013-04-02   v0.4.2   Add peerDependencies and update description.
 * 2013-04-02   v0.4.1   Add trace when force flag.
 * 2013-02-28   v0.4.0   First official release for Grunt 0.4.0.
 * 2012-11-20   v0.3.2   New examples added.
 * 2012-09-25   v0.3.1   Rename grunt-contrib-lib dep to grunt-lib-contrib, add force flag.
 * 2012-09-25   v0.3.0   General cleanup and consolidation. Global options depreciated.

---

Task submitted by [Ariel Falduto](http://outa.im/)


text:
require "spec_helper"
if ChefUtils.windows?
  require "chef/win32/api/file"
  require "chef/win32/file"
  require "chef/win32/version"
end

describe Chef::ReservedNames::Win32::File, :windows_only do
  context "#symlink" do
    let(:with_privilege) { Chef::ReservedNames::Win32::API::File::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE }
    let(:without_privilege) { 0x0 }

    context "an invalid parameter is passed" do
      it "will throw an exception if an invalid parameter is passed" do
        allow(File).to receive(:directory?).and_return(false)
        allow(Chef::ReservedNames::Win32::File).to receive(:encode_path) { |a| a }
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:windows_10?).and_return(true)
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:build_number).and_return(1)
        allow(Chef::ReservedNames::Win32::File).to receive(:CreateSymbolicLinkW).and_return(nil)

        expect { Chef::ReservedNames::Win32::File.symlink("a", "b") }.to raise_error Chef::Exceptions::Win32APIError
      end
    end

    context "a valid parameter is passed" do
      before(:each) do
        allow(File).to receive(:directory?).and_return(false)
        allow(Chef::ReservedNames::Win32::File).to receive(:encode_path) { |a| a }
        allow(Chef::ReservedNames::Win32::File).to receive(:CreateSymbolicLinkW).with(any_args) { "don't //actually// do this" }
      end

      it "will not pass the unprivileged symlink flag if the node is not Windows 10" do
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:windows_10?).and_return(false)

        expect(Chef::ReservedNames::Win32::File).to receive(:CreateSymbolicLinkW).with("b", "a", without_privilege)
        described_class.symlink("a", "b")
      end

      it "will not pass the unprivileged symlink flag if the node is not at least Windows 10 Creators Update" do
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:windows_10?).and_return(true)
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:build_number).and_return(1)

        expect(Chef::ReservedNames::Win32::File).to receive(:CreateSymbolicLinkW).with("b", "a", without_privilege)
        described_class.symlink("a", "b")
      end

      it "will pass the unprivileged symlink flag if the node is Windows 10 Creators Update or higher" do
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:windows_10?).and_return(true)
        allow_any_instance_of(Chef::ReservedNames::Win32::Version).to receive(:build_number).and_return(15063)

        expect(Chef::ReservedNames::Win32::File).to receive(:CreateSymbolicLinkW).with("b", "a", with_privilege)
        described_class.symlink("a", "b")
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.jgroups.protocols.dns;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class MockDirContext implements DirContext {

   private static class DNSKey {
      final String query;
      final DNSResolver.DNSRecordType recordType;

      private DNSKey(String query, DNSResolver.DNSRecordType recordType) {
         this.query = query;
         this.recordType = recordType;
      }

      @Override
      public boolean equals(Object o) {
         if (this == o) return true;
         if (o == null || getClass() != o.getClass()) return false;

         DNSKey dnsKey = (DNSKey) o;

         if (query != null ? !query.equals(dnsKey.query) : dnsKey.query != null) return false;
         return recordType == dnsKey.recordType;
      }

      @Override
      public int hashCode() {
         int result = query != null ? query.hashCode() : 0;
         result = 31 * result + (recordType != null ? recordType.hashCode() : 0);
         return result;
      }
   }

   private Map<DNSKey, Attributes> responseMap = new HashMap<>();

   private MockDirContext() {

   }

   public static MockDirContext newDefault() {
      return new MockDirContext();
   }

   public MockDirContext addEntry(String dnsQuery, String dnsResponse, DNSResolver.DNSRecordType recordType) {
      Attributes attributes = responseMap.computeIfAbsent(new DNSKey(dnsQuery, recordType), v -> new BasicAttributes());
      Attribute attribute = attributes.get(recordType.toString());
      if(attribute == null) {
         attributes.put(new BasicAttribute(recordType.toString(), dnsResponse));
      } else {
         attribute.add(dnsResponse);
      }
      return this;
   }

   @Override
   public Attributes getAttributes(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Attributes getAttributes(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Attributes getAttributes(Name name, String[] attrIds) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Attributes getAttributes(String name, String[] attrIds) throws NamingException {
      DNSResolver.DNSRecordType recordType = DNSResolver.DNSRecordType.valueOf(attrIds[0]);
      return responseMap.get(new DNSKey(name, recordType));
   }

   @Override
   public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void bind(Name name, Object obj, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void bind(String name, Object obj, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rebind(Name name, Object obj, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rebind(String name, Object obj, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext createSubcontext(String name, Attributes attrs) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext getSchema(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext getSchema(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext getSchemaClassDefinition(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public DirContext getSchemaClassDefinition(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object lookup(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object lookup(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void bind(Name name, Object obj) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void bind(String name, Object obj) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rebind(Name name, Object obj) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rebind(String name, Object obj) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void unbind(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void unbind(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rename(Name oldName, Name newName) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void rename(String oldName, String newName) throws NamingException {
      // TODO: Customise this generated block
   }

   @Override
   public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void destroySubcontext(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void destroySubcontext(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Context createSubcontext(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Context createSubcontext(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object lookupLink(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object lookupLink(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NameParser getNameParser(Name name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public NameParser getNameParser(String name) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Name composeName(Name name, Name prefix) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public String composeName(String name, String prefix) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object addToEnvironment(String propName, Object propVal) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Object removeFromEnvironment(String propName) throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public Hashtable<?, ?> getEnvironment() throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public void close() throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }

   @Override
   public String getNameInNamespace() throws NamingException {
      throw new UnsupportedOperationException("Not implemented");
   }
}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR"

sudo docker build -t atheris-builder ./
sudo docker run -it --env ATHERIS_VERSION="$ATHERIS_VERSION" --mount type=bind,source=$PWD/../,target=/atheris atheris-builder

# chown the resulting dirs so that they can be read by the deployment script.
for d in .eggs atheris.egg-info build dist tmp; do
    sudo chown -R $USER ../$d
done


text:
package com.springproject;

import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.springproject.web.i18n.I18nService;

@RunWith(SpringRunner.class)
@SpringBootTest

public class SpringProjectApplicationTests {

	@Autowired
	private I18nService i18NService;

	@Test
	public void testMessageByLocaleService() throws Exception {
		String expectedResult = "Bootstrap starter template";
		String messageId = "index.main.callout";
		String actual = i18NService.getMessage(messageId);
		Assert.assertEquals("The actual message and expected String dont match", expectedResult, actual);

	}

}


text:
from datetime import datetime
from ....utils.logging import logger

def transpose_running_oauth(x):
    return {
        'code': x['code'],
        'endDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
        'startDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
        'name': x['name']
    }

def running_contests(self):
    path = 'contests'
    url = self._make_url(self.api_url, path)
    r = self._request_api(url)

    data = r['result']['data']['content']
    contest_list = map(transpose_running_oauth, data['contestList'])
    current_time = datetime.fromtimestamp(data['currentTime'])

    def check_current(contest):
        contest_time = contest['endDate']
        return contest_time >= current_time

    running = list(filter(check_current, contest_list))
    logger.debug("got running")

    return running


text:
package models.services

import java.util.UUID
import models.AuthToken
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps

/**
 * Handles actions to auth tokens.
 */
trait AuthTokenService {

  /**
   * Creates a new auth token and saves it in the backing store.
   *
   * @param userID The user ID for which the token should be created.
   * @param expiry The duration a token expires.
   * @return The saved auth token id.
   */
  def create(userID: UUID, expiry: FiniteDuration = 60 minutes): Future[UUID]

  /**
   * Validates a token ID.
   *
   * @param id The token ID to validate.
   * @return The token if it's valid, None otherwise.
   */
  def validate(id: UUID): Future[Option[AuthToken]]

  /**
   * Cleans expired tokens.
   *
   * @return The list of deleted tokens.
   */
  def clean: Future[Unit]

  /**
   * Remove token associated with given token id.
   *
   * @param id the id of the token to remove.
   * @return A future to wait for the process to be completed.
   */
  def remove(id: UUID): Future[Unit]
}


text:
package com.amazonaws.services.greengrass.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.greengrass.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * BulkDeploymentResultMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BulkDeploymentResultMarshaller {

    private static final MarshallingInfo<String> CREATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("CreatedAt").build();
    private static final MarshallingInfo<String> DEPLOYMENTARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeploymentArn").build();
    private static final MarshallingInfo<String> DEPLOYMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeploymentId").build();
    private static final MarshallingInfo<String> DEPLOYMENTSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeploymentStatus").build();
    private static final MarshallingInfo<String> DEPLOYMENTTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeploymentType").build();
    private static final MarshallingInfo<List> ERRORDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ErrorDetails").build();
    private static final MarshallingInfo<String> ERRORMESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ErrorMessage").build();
    private static final MarshallingInfo<String> GROUPARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("GroupArn").build();

    private static final BulkDeploymentResultMarshaller instance = new BulkDeploymentResultMarshaller();

    public static BulkDeploymentResultMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(BulkDeploymentResult bulkDeploymentResult, ProtocolMarshaller protocolMarshaller) {

        if (bulkDeploymentResult == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(bulkDeploymentResult.getCreatedAt(), CREATEDAT_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getDeploymentArn(), DEPLOYMENTARN_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getDeploymentId(), DEPLOYMENTID_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getDeploymentStatus(), DEPLOYMENTSTATUS_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getDeploymentType(), DEPLOYMENTTYPE_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getErrorDetails(), ERRORDETAILS_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getErrorMessage(), ERRORMESSAGE_BINDING);
            protocolMarshaller.marshall(bulkDeploymentResult.getGroupArn(), GROUPARN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package tadsuite.mvc.core;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import tadsuite.mvc.auth.AuthUserState;
import tadsuite.mvc.jdbc.Jdbc;

/**
 * 传递给该类(包括子类)各方法的参数,均认为是从客户端提供且未经验证的,必须验证其有效且SQL安全*/
public abstract class MvcServiceBase extends MvcBase {
	protected Jdbc jdbc;
	protected String message;
	protected AuthUserState auth;
	protected LinkedHashMap<String, Object> mapResult=new LinkedHashMap<String, Object>();
	protected ArrayList<LinkedHashMap<String, Object>> listResult=new ArrayList<LinkedHashMap<String, Object>>();
	protected MvcControllerBase controller;
	protected MvcRequest request;

	public MvcServiceBase(MvcControllerBase controller) {
		this.controller=controller;
		this.jdbc = controller.jdbc;
		this.request=controller.request;
	}

	public MvcServiceBase(MvcControllerBase controller, AuthUserState auth) {
		this.controller=controller;
		this.jdbc = controller.jdbc;
		this.request=controller.request;
		this.auth=auth;
	}

	public String getMessage() {
		return message;
	}

	public LinkedHashMap<String, Object> getMapResult() {
		return mapResult;
	}

	public ArrayList<LinkedHashMap<String, Object>> getListResult() {
		return listResult;
	}
}


text:
This is an api generated from a OpenAPI 3.0 spec with [SwagGen](https://github.com/yonaskolb/SwagGen)

## Operation

Each operation lives under the `TFL` namespace and within an optional tag: `TFL(.tagName).operationId`. If an operation doesn't have an operationId one will be generated from the path and method.

Each operation has a nested `Request` and a `Response`, as well as a static `service` property

#### Service

This is the struct that contains the static information about an operation including it's id, tag, method, pre-modified path, and authorization requirements. It has a generic `ResponseType` type which maps to the `Response` type.
You shouldn't really need to interact with this service type.

#### Request

Each request is a subclass of `APIRequest` and has an `init` with a body param if it has a body, and a `options` struct for other url and path parameters. There is also a convenience init for passing parameters directly.
The `options` and `body` structs are both mutable so they can be modified before actually sending the request.

#### Response

The response is an enum of all the possible responses the request can return. it also contains getters for the `statusCode`, whether it was `successful`, and the actual decoded optional `success` response. If the operation only has one type of failure type there is also an optional `failure` type.

## Model
Models that are sent and returned from the API are mutable classes. Each model is `Equatable` and `Codable`.

`Required` properties are non optional and non-required are optional

All properties can be passed into the initializer, with `required` properties being mandatory.

If a model has `additionalProperties` it will have a subscript to access these by string

## APIClient
The `APIClient` is used to encode, authorize, send, monitor, and decode the requests. There is a `APIClient.default` that uses the default `baseURL` otherwise a custom one can be initialized:

```swift
public init(baseURL: String, sessionManager: SessionManager = .default, defaultHeaders: [String: String] = [:], behaviours: [RequestBehaviour] = [])
```

#### APIClient properties

- `baseURL`: The base url that every request `path` will be appended to
- `behaviours`: A list of [Request Behaviours](#requestbehaviour) to add to every request
- `sessionManager`: An `Alamofire.SessionManager` that can be customized
- `defaultHeaders`: Headers that will be applied to every request
- `decodingQueue`: The `DispatchQueue` to decode responses on

#### Making a request
To make a request first initialize a [Request](#request) and then pass it to `makeRequest`. The `complete` closure will be called with an `APIResponse`

```swift
func makeRequest<T>(_ request: APIRequest<T>, behaviours: [RequestBehaviour] = [], queue: DispatchQueue = DispatchQueue.main, complete: @escaping (APIResponse<T>) -> Void) -> Request? {
```

Example request (that is not neccessarily in this api):

```swift

let getUserRequest = TFL.User.GetUser.Request(id: 123)
let apiClient = APIClient.default

apiClient.makeRequest(getUserRequest) { apiResponse in
    switch apiResponse {
        case .result(let apiResponseValue):
        	if let user = apiResponseValue.success {
        		print("GetUser returned user \(user)")
        	} else {
        		print("GetUser returned \(apiResponseValue)")
        	}
        case .error(let apiError):
        	print("GetUser failed with \(apiError)")
    }
}
```

Each [Request](#request) also has a `makeRequest` convenience function that uses `TFL.shared`.

#### APIResponse
The `APIResponse` that gets passed to the completion closure contains the following properties:

- `request`: The original request
- `result`: A `Result` type either containing an `APIClientError` or the [Response](#response) of the request
- `urlRequest`: The `URLRequest` used to send the request
- `urlResponse`: The `HTTPURLResponse` that was returned by the request
- `data`: The `Data` returned by the request.
- `timeline`: The `Alamofire.Timeline` of the request which contains timing information.

#### Encoding and Decoding
Only JSON requests and responses are supported. These are encoded and decoded by `JSONEncoder` and `JSONDecoder` respectively, using Swift's `Codable` apis.
There are some options to control how invalid JSON is handled when decoding and these are available as static properties on `TFL`:

- `safeOptionalDecoding`: Whether to discard any errors when decoding optional properties. Defaults to `true`.
- `safeArrayDecoding`: Whether to remove invalid elements instead of throwing when decoding arrays. Defaults to `true`.

Dates are encoded and decoded differently according to the swagger date format. They use different `DateFormatter`'s that you can set.
- `date-time`
    - `DateTime.dateEncodingFormatter`: defaults to `yyyy-MM-dd'T'HH:mm:ss.Z`
    - `DateTime.dateDecodingFormatters`: an array of date formatters. The first one to decode successfully will be used
- `date`
    - `DateDay.dateFormatter`: defaults to `yyyy-MM-dd`

#### APIClientError
This is error enum that `APIResponse.result` may contain:

```swift
public enum APIClientError: Error {
    case unexpectedStatusCode(statusCode: Int, data: Data)
    case decodingError(DecodingError)
    case requestEncodingError(String)
    case validationError(String)
    case networkError(Error)
    case unknownError(Error)
}
```

#### RequestBehaviour
Request behaviours are used to modify, authorize, monitor or respond to requests. They can be added to the `APIClient.behaviours` for all requests, or they can passed into `makeRequest` for just that single request.

`RequestBehaviour` is a protocol you can conform to with each function being optional. As the behaviours must work across multiple different request types, they only have access to a typed erased `AnyRequest`.

```swift
public protocol RequestBehaviour {

    /// runs first and allows the requests to be modified. If modifying asynchronously use validate
    func modifyRequest(request: AnyRequest, urlRequest: URLRequest) -> URLRequest

    /// validates and modifies the request. complete must be called with either .success or .fail
    func validate(request: AnyRequest, urlRequest: URLRequest, complete: @escaping (RequestValidationResult) -> Void)

    /// called before request is sent
    func beforeSend(request: AnyRequest)

    /// called when request successfuly returns a 200 range response
    func onSuccess(request: AnyRequest, result: Any)

    /// called when request fails with an error. This will not be called if the request returns a known response even if the a status code is out of the 200 range
    func onFailure(request: AnyRequest, error: APIClientError)

    /// called if the request recieves a network response. This is not called if request fails validation or encoding
    func onResponse(request: AnyRequest, response: AnyResponse)
}
```

### Authorization
Each request has an optional `securityRequirement`. You can create a `RequestBehaviour` that checks this requirement and adds some form of authorization (usually via headers) in `validate` or `modifyRequest`. An alternative way is to set the `APIClient.defaultHeaders` which applies to all requests.

#### Reactive and Promises
To add support for a specific asynchronous library, just add an extension on `APIClient` and add a function that wraps the `makeRequest` function and converts from a closure based syntax to returning the object of choice (stream, future...ect)

## Models

- **AccidentDetail**
- **AccidentStatsOrderedSummary**
- **ActiveServiceType**
- **AdditionalProperties**
- **ApiVersionInfo**
- **Bay**
- **CarParkOccupancy**
- **Casualty**
- **Coordinate**
- **Crowding**
- **CycleSuperhighway**
- **DateRange**
- **DateRangeNullable**
- **DbGeography**
- **DbGeographyWellKnownValue**
- **Disambiguation**
- **DisambiguationOption**
- **DisruptedPoint**
- **Disruption**
- **EmissionsSurchargeVehicle**
- **Fare**
- **FareBounds**
- **FareDetails**
- **FaresMode**
- **FaresPeriod**
- **FaresSection**
- **GeoCodeSearchMatch**
- **GeoPoint**
- **GeoPointBBox**
- **Identifier**
- **Instruction**
- **InstructionStep**
- **Interval**
- **ItineraryResult**
- **Journey**
- **JourneyPlannerCycleHireDockingStationData**
- **JourneyVector**
- **JpElevation**
- **KnownJourney**
- **Leg**
- **Line**
- **LineGroup**
- **LineModeGroup**
- **LineRouteSection**
- **LineServiceType**
- **LineServiceTypeInfo**
- **LineSpecificServiceType**
- **LineStatus**
- **MatchedRoute**
- **MatchedRouteSections**
- **MatchedStop**
- **Message**
- **Mode**
- **Object**
- **Obstacle**
- **OrderedRoute**
- **PassengerFlow**
- **PassengerType**
- **Path**
- **PathAttribute**
- **Period**
- **Place**
- **PlaceCategory**
- **PlacePolygon**
- **PlannedWork**
- **Point**
- **PostcodeInput**
- **Prediction**
- **PredictionTiming**
- **Recommendation**
- **RecommendationResponse**
- **Redirect**
- **RoadCorridor**
- **RoadDisruption**
- **RoadDisruptionImpactArea**
- **RoadDisruptionLine**
- **RoadDisruptionSchedule**
- **RoadProject**
- **RouteOption**
- **RouteSearchMatch**
- **RouteSearchResponse**
- **RouteSection**
- **RouteSectionNaptanEntrySequence**
- **RouteSequence**
- **Schedule**
- **SearchCriteria**
- **SearchMatch**
- **SearchResponse**
- **ServiceFrequency**
- **StationInterval**
- **StatusSeverity**
- **StopPoint**
- **StopPointCategory**
- **StopPointRouteSection**
- **StopPointSequence**
- **StopPointsResponse**
- **Street**
- **StreetSegment**
- **Ticket**
- **TicketTime**
- **TicketType**
- **TimeAdjustment**
- **TimeAdjustments**
- **Timetable**
- **TimetableResponse**
- **TimetableRoute**
- **TrainLoading**
- **TwentyFourHourClockTime**
- **ValidityPeriod**
- **Vehicle**

## Requests

- **TFL.AccidentStats**
	- **AccidentStatsGet**: GET `/accidentstats/{year}`
- **TFL.AirQuality**
	- **AirQualityGet**: GET `/airquality`
- **TFL.BikePoint**
	- **BikePointGet**: GET `/bikepoint/{id}`
	- **BikePointGetAll**: GET `/bikepoint`
	- **BikePointSearch**: GET `/bikepoint/search`
- **TFL.Cabwise**
	- **CabwiseGet**: GET `/cabwise/search`
- **TFL.Journey**
	- **JourneyJourneyResults**: GET `/journey/journeyresults/{from}/to/{to}`
	- **JourneyMeta**: GET `/journey/meta/modes`
- **TFL.Line**
	- **GetLineStatus**: GET `/line/{ids}/status/{startdate}/to/{enddate}`
	- **LineDisruption**: GET `/line/{ids}/disruption`
	- **LineDisruptionByMode**: GET `/line/mode/{modes}/disruption`
	- **LineGet**: GET `/line/{ids}`
	- **LineGetByMode**: GET `/line/mode/{modes}`
	- **LineLineRoutesByIds**: GET `/line/{ids}/route`
	- **LineMetaDisruptionCategories**: GET `/line/meta/disruptioncategories`
	- **LineMetaModes**: GET `/line/meta/modes`
	- **LineMetaServiceTypes**: GET `/line/meta/servicetypes`
	- **LineMetaSeverity**: GET `/line/meta/severity`
	- **LineRoute**: GET `/line/route`
	- **LineRouteByMode**: GET `/line/mode/{modes}/route`
	- **LineRouteSequence**: GET `/line/{id}/route/sequence/{direction}`
	- **LineSearch**: GET `/line/search/{query}`
	- **LineStatusByIds**: GET `/line/{ids}/status`
	- **LineStatusByMode**: GET `/line/mode/{modes}/status`
	- **LineStatusBySeverity**: GET `/line/status/{severity}`
	- **LineStopPoints**: GET `/line/{id}/stoppoints`
	- **LineTimetable**: GET `/line/{id}/timetable/{fromstoppointid}`
	- **LineTimetableTo**: GET `/line/{id}/timetable/{fromstoppointid}/to/{tostoppointid}`
	- **GetLineArrivals**: GET `/line/{ids}/arrivals`
	- **GetLineArrivalsByPath**: GET `/line/{ids}/arrivals/{stoppointid}`
- **TFL.Mode**
	- **ModeArrivals**: GET `/mode/{mode}/arrivals`
	- **ModeGetActiveServiceTypes**: GET `/mode/activeservicetypes`
- **TFL.Occupancy**
	- **GetOccupant**: GET `/occupancy/carpark/{id}`
	- **GetOccupants**: GET `/occupancy/carpark`
- **TFL.Place**
	- **PlaceGet**: GET `/place/{id}`
	- **PlaceGetAt**: GET `/place/{type}/at/{lat}/{lon}`
	- **PlaceGetByGeoBox**: GET `/place`
	- **PlaceGetByType**: GET `/place/type/{types}`
	- **PlaceGetOverlay**: GET `/place/{type}/overlay/{z}/{lat}/{lon}/{width}/{height}`
	- **PlaceGetStreetsByPostCode**: GET `/place/address/streets/{postcode}`
	- **PlaceMetaCategories**: GET `/place/meta/categories`
	- **PlaceMetaPlaceTypes**: GET `/place/meta/placetypes`
	- **PlaceSearch**: GET `/place/search`
- **TFL.Road**
	- **GetRoadDisruption**: GET `/road/{ids}/disruption`
	- **RoadDisruptedStreets**: GET `/road/all/street/disruption`
	- **RoadDisruptionById**: GET `/road/all/disruption/{disruptionids}`
	- **RoadMetaCategories**: GET `/road/meta/categories`
	- **RoadMetaSeverities**: GET `/road/meta/severities`
	- **RoadStatus**: GET `/road/{ids}/status`
	- **GetRoad**: GET `/road/{ids}`
	- **GetRoads**: GET `/road`
- **TFL.Search**
	- **SearchBusSchedules**: GET `/search/busschedules`
	- **SearchGet**: GET `/search`
	- **SearchMetaCategories**: GET `/search/meta/categories`
	- **SearchMetaSearchProviders**: GET `/search/meta/searchproviders`
	- **SearchMetaSorts**: GET `/search/meta/sorts`
- **TFL.StopPoint**
	- **StopPointArrivals**: GET `/stoppoint/{id}/arrivals`
	- **StopPointCrowding**: GET `/stoppoint/{id}/crowding/{line}`
	- **StopPointDirection**: GET `/stoppoint/{id}/directionto/{tostoppointid}`
	- **StopPointDisruption**: GET `/stoppoint/{ids}/disruption`
	- **StopPointDisruptionByMode**: GET `/stoppoint/mode/{modes}/disruption`
	- **StopPointGet**: GET `/stoppoint/{ids}`
	- **StopPointGetByGeoPoint**: GET `/stoppoint`
	- **StopPointGetByMode**: GET `/stoppoint/mode/{modes}`
	- **StopPointGetBySms**: GET `/stoppoint/sms/{id}`
	- **StopPointGetByType**: GET `/stoppoint/type/{types}`
	- **StopPointGetCarParksById**: GET `/stoppoint/{stoppointid}/carparks`
	- **StopPointGetServiceTypes**: GET `/stoppoint/servicetypes`
	- **StopPointGetTaxiRanksByIds**: GET `/stoppoint/{stoppointid}/taxiranks`
	- **StopPointMetaCategories**: GET `/stoppoint/meta/categories`
	- **StopPointMetaModes**: GET `/stoppoint/meta/modes`
	- **StopPointMetaStopTypes**: GET `/stoppoint/meta/stoptypes`
	- **StopPointReachableFrom**: GET `/stoppoint/{id}/canreachonline/{lineid}`
	- **StopPointRoute**: GET `/stoppoint/{id}/route`
	- **SearchStopPoints**: GET `/stoppoint/search`
	- **SearchStopPointsByPath**: GET `/stoppoint/search/{query}`
- **TFL.TravelTime**
	- **TravelTimeGetCompareOverlay**: GET `/traveltimes/compareoverlay/{z}/mapcenter/{mapcenterlat}/{mapcenterlon}/pinlocation/{pinlat}/{pinlon}/dimensions/{width}/{height}`
	- **TravelTimeGetOverlay**: GET `/traveltimes/overlay/{z}/mapcenter/{mapcenterlat}/{mapcenterlon}/pinlocation/{pinlat}/{pinlon}/dimensions/{width}/{height}`
- **TFL.Vehicle**
	- **VehicleGet**: GET `/vehicle/{ids}/arrivals`
	- **VehicleGetVehicle**: GET `/vehicle/emissionsurcharge`


text:
package edacc.parameterspace.domain;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class CategoricalDomain extends Domain {
	protected Set<String> categories;
	public static final String name = "Categorical";

	private CategoricalDomain() {

	}

	public CategoricalDomain(String[] categories) {
		this.categories = new HashSet<String>();
		for (String s: categories) {
			this.categories.add(new String(s));
		}
	}

	public CategoricalDomain(Set<String> categories) {
		this.categories = categories;
	}

	@Override
	public boolean contains(Object value) {
		return categories.contains(value);
	}

	@Override
	public Object randomValue(Random rng) {
		if (categories.size() == 0) return null;
		return categories.toArray()[rng.nextInt(categories.size())];
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for (String c: categories) {
			sb.append(c);
			sb.append(", ");
		}
		sb.append("}");
		return sb.toString();
	}

	public Set<String> getCategories() {
		return categories;
	}

	public void setCategories(Set<String> categories) {
		this.categories = categories;
	}

	@Override
	public Object mutatedValue(Random rng, Object value) {
		if (!contains(value)) return value;
		return randomValue(rng);
	}

	@Override
	public List<Object> getDiscreteValues() {
		List<Object> values = new LinkedList<Object>();
		values.addAll(categories);
		return values;
	}

    @Override
    public String getName() {
        return name;
    }
}


text:
package org.opensingular.internal.lib.commons.xml;

import com.sun.org.apache.xpath.internal.XPathAPI;
import org.opensingular.lib.commons.base.SingularException;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.NodeIterator;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.transform.TransformerException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static org.opensingular.internal.lib.commons.xml.XmlUtil.isNodeTypeElement;

/**
 * Métodos utilitários para trabalhar com XPath. Para um bom tutorial em
 * XPath veja
 *
 * http://www.w3schools.com/xpath/default.asp ou para exemplos
 *
 * passo-a-passo. Dado o XML de exemplo:

 * <xmp>
 * <pedido>
 * <cd cod="1">
 * <grupo>Pato Fu</grupo>
 * <nome>Acustico</nome>
 * <ano>2002</ano>
 * <faixa>Minha Musica</faixa>
 * <faixa>Sua Musica</faixa>
 * <faixa>Nossa Musica</faixa>
 * </cd>
 * <cd cod="4">
 * <grupo>Paralamas</grupo>
 * <nome>9 Luas</nome>
 * <ano>1999</ano>
 * <faixa>9 Luas</faixa>
 * <faixa>8 Luas</faixa>
 * <faixa>7 Luas</faixa>
 * </cd>
 * <cd cod="6">
 * <grupo>U2</grupo>
 * <nome>Zooropa</nome>
 * <ano>1997</ano>
 * <faixa>Babyface</faixa>
 * <faixa>Numb</faixa>
 * <faixa>Lemon</faixa>
 * </cd>
 * </pedido>
 * </xmp>
 *

 * Os resultados para chamadas utilizando
 * XPathToolkit.selectNode(raiz, xPath) são:
 * <xmp>
 * /pedido/cd[2]/nome                 --> <nome>9 Luas</nome>
 * /pedido[1]/cd[2]/nome              --> <nome>9 Luas</nome>
 * /pedido/cd[2]/faixa[2]             --> <faixa>8 Luas</faixa>
 * /pedido/cd[@cod=6]/nome            --> <nome>Zooropa</nome>
 * /pedido/cd[ano=1997]/faixa[last()] --> <faixa>Lemon</faixa>
 * /pedido/cd[@cod=6]/nome/../ano"    --> <ano>1997</ano>
 * </xmp>
 *

 * A implementação do XPath utilizada é o
 *  Xalan
 *
 * @author Daniel C. Bordin
 */
public final class XPathToolkit {

    private static final Map<Short, String> NODE_LABEL_MAP;

    static {
        NODE_LABEL_MAP = new HashMap<>();
        NODE_LABEL_MAP.put(Node.ELEMENT_NODE, "Element Node");
        NODE_LABEL_MAP.put(Node.TEXT_NODE, "Text Node");
        NODE_LABEL_MAP.put(Node.ATTRIBUTE_NODE, "Attribute Node");
        NODE_LABEL_MAP.put(Node.CDATA_SECTION_NODE, "CData Section Node");
        NODE_LABEL_MAP.put(Node.COMMENT_NODE, "Comment Node");
        NODE_LABEL_MAP.put(Node.DOCUMENT_NODE, "Document Node");
        NODE_LABEL_MAP.put(Node.DOCUMENT_FRAGMENT_NODE, "Document Fragment Node");
        NODE_LABEL_MAP.put(Node.DOCUMENT_TYPE_NODE, "Document Type Node");
        NODE_LABEL_MAP.put(Node.ENTITY_REFERENCE_NODE, "Entity Reference Node");
        NODE_LABEL_MAP.put(Node.ENTITY_NODE, "Entity Node");
        NODE_LABEL_MAP.put(Node.NOTATION_NODE, "Notation Node");
        NODE_LABEL_MAP.put(Node.PROCESSING_INSTRUCTION_NODE, "Processing Instruction Node");
    }

    /**
     * Esconde o construtor pro ser uma classe utiliária.
     */
    private XPathToolkit() {
    }

    /**
     * Retorna o path completo do elemento.
     *
     * @see #getFullPath(Node, Node)
     */
    @Nonnull
    public static String getFullPath(@Nonnull Node no) {
        return getFullPath(no, null);
    }

    /**
     * Retorna o path completo do elemento. O resutlado
     * deve ser semelehante a pedido/item[3]/codigo, que
     * representa o elemento codigo no terceiro elemento item do no pedido.
     *
     * @param no Nó a ter o nome completo adicionado no buffer
     * @param topo Nó até onde será montado o path.
     * Pode ser null para indicar até o topo.
     * @return path completo
     */
    @Nonnull
    public static String getFullPath(@Nonnull Node no, @Nullable Node topo) {
        StringBuilder buffer = new StringBuilder();
        getFullPath(buffer, no, topo);
        return buffer.toString();
    }

    /**
     * Adiciona no buffer o path completo do elemento. A sintaxe não é
     * padrão. O resutlado deve ser semelehante a
     * pedido/item[3]/codigo, que dizer o elemento codigo no
     * terceiro elemento item do no pedido.
     *
     * @param buffer destino do nome a ser montado
     * @param no Nó a ter o nome completo adicionado no buffer
     * @param topo Nó até onde será montado o path. O path incluirá esse nó.
     * Pode ser null para indicar até o topo.
     */
    private static void getFullPath(@Nonnull StringBuilder buffer, @Nonnull Node no, @Nullable Node topo) {

        Node parent = no.getParentNode();
        if (parent == null) {
            if (no.getNodeType() == Node.ATTRIBUTE_NODE) {
                parent = ((Attr) no).getOwnerElement();
            }
        } else {
            if (parent.getNodeType() == Node.DOCUMENT_NODE) {
                parent = null;
            }
        }

        if (parent == null) {
            buffer.append('/');
        } else {
            /* XXX: O método "isSameNode" não deveria ser usado aqui? */
            if (parent != topo) {
                getFullPath(buffer, parent, topo);
                buffer.append('/');
            }
        }

        /* XXX: O método "isSameNode" não deveria ser usado aqui? */
        if (no != topo) {
            switch (no.getNodeType()) {
                case Node.ELEMENT_NODE:
                    buffer.append(no.getNodeName());
                    addElementIndex(buffer, no);
                    break;
                case Node.ATTRIBUTE_NODE:
                    buffer.append('@');
                    buffer.append(no.getNodeName());
                    break;
                default:
            }
        }

    }

    /**
     * Adiciona ao buffer a posição do nó no em relação ao seus nós
     * irmãos com mesmo nome no formato "[9]".Se for o único com o
     * nome no mesmo nível, não faz nada.
     *
     * @param buffer Destino do texto
     * @param e Node a ser pesquisado o nível
     */
    private static void addElementIndex(StringBuilder buffer, Node e) {
        int pos = -1;
        // Verifica se possui no com mesmo nome antes
        Node cursor = e.getPreviousSibling();
        while (cursor != null) {
            if ((cursor.getNodeType() == e.getNodeType())
                    && (e.getNodeName().equals(cursor.getNodeName()))) {
                if (pos == -1) {
                    pos = 2;
                } else {
                    pos++;
                }
            }
            cursor = cursor.getPreviousSibling();
        }
        if (pos != -1) {
            buffer.append('[').append(pos).append(']');
            return;
        } // Verifica se possui no com mesmo nome depois
        cursor = e.getNextSibling();
        while (cursor != null) {
            if ((cursor.getNodeType() == e.getNodeType())
                    && (e.getNodeName().equals(cursor.getNodeName()))) {
                buffer.append("[1]");
                return;
            }
            cursor = cursor.getNextSibling();
        }

    }

    /**
     * Retorna o nome completo do tipo do Node.
     *
     * @param n No alvo
     * @return String Retorna o nome por extenso ou null se N for null.
     */
    public static String getNodeTypeName(Node n) {
        if (n == null) {
            return null;
        }

        String nodeLabel = NODE_LABEL_MAP.get(n.getNodeType());
        return nodeLabel != null ? nodeLabel : "Desconhecido (" + n.getClass().getName() + ") Node";
    }

    /**
     * Verifica se a consulta xPath é complexa ou é simples. No caso de ser
     * simples, pode ser utilizado o algorítmo implementado aqui na classe.
     *
     * @param xPath consulta a ser verificada a complexidadde
     * @return false Para indica necessidade da API XPath
     */
    static boolean isSimples(String xPath) {

        Pattern pattern = Pattern.compile("[*\\[\\].]|::");

        return !xPath.startsWith("//") && !xPath.startsWith(":") && !pattern.matcher(xPath).find();
    }

    /**
     * Verifica se a consulta xPath para retornar lista de Element é simples
     * (ou seja, pode utilizar algoritmo próprio em vez do xPath real).
     *
     * @param xPath consulta a ser verificada a complexidadde
     * @return false Para indica necessidade da API XPath
     */
    static boolean isSelectSimples(String xPath) {
        if (xPath == null) {
            return true;
        }
        for (int i = xPath.length() - 1; i != -1; i--) {
            switch (xPath.charAt(i)) {
                case '/':
                case ':':
                case '*':
                case '[':
                case ']':
                case '.':
                    return false;
                default:
            }
        }
        return true;
    }

    /**
     * Use an XPath string to select a single node.
     * XPath namespace prefixes are resolved from the context node.

     * Esse método é um atalho de conveniência.
     *
     * @param contextNode The node to start searching from.
     * @param xPath A valid XPath string.
     * @return Node The first node found that matches the XPath, or null.
     */
    public static Node selectNode(Node contextNode, String xPath) {
        if (isSimples(xPath)) {
            return findSimples(EWrapper.getOriginal(contextNode), xPath);
        }
        try {
            return XPathAPI.selectSingleNode(EWrapper.getOriginal(contextNode), xPath);
        } catch (TransformerException e) {
            throw SingularException.rethrow(e);
        }
    }

    /**
     * Use an XPath string to select a single node.
     * XPath namespace prefixes are resolved from the context node.

     * Esse método é um atalho de conveniência.
     *
     * @param contextNode The node to start searching from.
     * @param xPath A valid XPath string.
     * @return Node The first node found that matches the XPath, or null.
     */
    public static Element selectElement(Node contextNode, String xPath) {
        Node result = selectNode(contextNode, xPath);
        if (result == null) {
            return null;
        }
        if (!isNodeTypeElement(result)) {
            throw new SingularException(
                    "O elemento resultante (" + getFullPath(result) + ") não é um Element, mas um " +
                            getNodeTypeName(result));
        }
        return (Element) result;
    }

    /**
     * Use an XPath string to select a single node.
     * XPath namespace prefixes are resolved from the context node.

     * Esse método é um atalho de conveniência.
     *
     * @param contextNode The node to start searching from.
     * @param xPath A valid XPath string.
     */
    @Nonnull
    public static MElementResult selectElements(Node contextNode, String xPath) {
        if (contextNode instanceof Element) {
            if (xPath == null) {
                return new MElementResult((Element) contextNode);
            } else if (isSelectSimples(xPath)) {
                return new MElementResult((Element) contextNode, xPath);
            }
        }
        return new MElementResult(selectNodeList(contextNode, xPath));
    }

    /**
     * Retorna o valor do texto de todos os nos resutlantes da consulta.
     *
     * @param contextNode Ponto de partida da pesquisa
     * @param xPath Consulta para seleção dos nodes
     * @return Sempre not null. Se não encontrar nada retorna vazio.
     */
    public static List<String> getValues(Node contextNode, String xPath) {
        List<String> resultList = null;
        if (isSelectSimples(xPath)) {
            MElementResult rs = new MElementResult((Element) contextNode, xPath);
            while (rs.next()) {
                resultList = addToList(resultList, rs.getValue());
            }
        } else {
            NodeList nodesList = selectNodeList(contextNode, xPath);
            int tam = nodesList.getLength();
            for (int i = 0; i < tam; i++) {
                resultList = addToList(resultList, XmlUtil.getValueText(nodesList.item(i)));
            }
        }
        return resultList == null ? Collections.emptyList() : resultList;
    }
    private static List<String> addToList(List<String> list, String value) {
        List<String> newList = list;
        if (value != null) {
            if (list == null) {
                newList = new ArrayList<>();
            }
            newList.add(value);
        }
        return newList;
    }

    /**
     * Use an XPath string to select a nodelist. XPath namespace prefixes
     * are resolved from the contextNode. Esse método é um atalho de
     * conveniência.
     *
     * @param contextNode The node to start searching from.
     * @param xPath A valid XPath string.
     * @return NodeList A NodeIterator, should never be null.
     */
    public static NodeList selectNodeList(Node contextNode, String xPath) {
        try {
            // O XPath não funciona a partir o MElement
            return XPathAPI.selectNodeList(EWrapper.getOriginal(contextNode), xPath);
        } catch (TransformerException e) {
            throw SingularException.rethrow(e.getMessage(), e);
        }
    }

    /**
     * Use an XPath string to select a nodelist. XPath namespace prefixes
     * are resolved from the contextNode.
     *
     * @param context The node to start searching from.
     * @param xPath A valid XPath string.
     * @return NodeIterator A NodeIterator, should never be null.
     */
    public static NodeIterator selectNodeIterator(Node context, String xPath) {
        try {
            return XPathAPI.selectNodeIterator(EWrapper.getOriginal(context), xPath);
        } catch (TransformerException e) {
            throw SingularException.rethrow(e.getMessage(), e);
        }
    }

    /**
     * Para caminho simples, faz a pesquisa manual em vez de usar a
     * biblioteca XPath. A diferença de tempo pode ser da ordem de 1000 vezes.
     *
     * @param parent Elemento onde será pesquisado
     * @param nodePath Caminho a ser pesquisa deve conter apenas nomes e /
     * @return O elemento se for encontrado.
     */
    private static Node findSimples(final Node parent, final String nodePath) {

        Node resp = parent;
        String path = nodePath;
        if (path.charAt(0) == '/') {
            resp = XmlUtil.getRootParent(resp);
            if (path.length() == 1) {
                return resp;
            }
            path = path.substring(1);
        }

        String elementName;
        while ((resp != null) && (path != null)) {
            int pos = path.indexOf('/');
            if (pos == -1) {
                elementName = path;
                path = null;
            } else {
                elementName = path.substring(0, pos);
                path = path.substring(pos + 1);
            }

            if (elementName.charAt(0) == '@') {
                if ((path != null) || !isNodeTypeElement(resp)) {
                    throw SingularException.rethrow("O xPath '" + path + "' é inválido");
                }
                return ((Element) resp).getAttributeNode(elementName.substring(1));
            }

            resp = XmlUtil.nextSiblingOfTypeElement(resp.getFirstChild(), elementName);
        }
        return resp;
    }

}


text:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace EdityMcEditface.Mvc.Services
{
    public class PathBaseInjector : IPathBaseInjector
    {
        private IHttpContextAccessor httpContextAccessor;

        public PathBaseInjector(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public String PathBase
        {
            get
            {
                return this.httpContextAccessor.HttpContext.Request.PathBase;
            }
        }
    }
}


text:
<?php

namespace cd;

set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__).'/../core/');

require_once('TwitterClient.php');

$t = new TwitterClient();
//if (!$t->test()) echo 'FAIL 1';

$x = $t->getTimeline('phonecafedrift');

print_r($x);

//XXX FUNKAR EJ NU PGA SAKNAD OAUTH SUPPORT:
//print_r( $t->getSearchResult('kex') );
//$x = $t->getFriendsTimeline();
//print_r($x);

?>


text:
package br.com.objectos.jabuticava.bvmf.rf.cri;

import br.com.objectos.comuns.base.Construtor;

/**
 * @author anderson.silva@objectos.com.br (Anderson Silva)
 */
public interface Cri {

  interface Contrutor extends Construtor<Cri> {

    CriEmissor getEmissor();

    CriEmissao getEmissao();

    CriSerie getSerie();

    CriRemuneracao getRemuneracao();

    CriInformacoes getInformacoes();

  }

  CriEmissor getEmissor();

  CriEmissao getEmissao();

  CriSerie getSerie();

  CriRemuneracao getRemuneracao();

  CriInformacoes getInformacoes();

}


text:
Adafruit_SSD1306_rfMOD
======================

clumsy modification of the wonderful Adafruit_SSD1306 library to work with RFDuino


text:
<?php

namespace Es\View\Exception;

use Es\Exception\NotFoundExceptionInterface;
use Exception;

class TemplateNotFoundException extends Exception implements NotFoundExceptionInterface
{
}


text:
/*
 * Qa full api
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: all
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using NUnit.Framework;

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using HostMe.Sdk.Api;
using HostMe.Sdk.Model;
using HostMe.Sdk.Client;
using System.Reflection;

namespace HostMe.Sdk.Test
{
    /// <summary>
    ///  Class for testing CustomerProfile
    /// </summary>
    /// <remarks>
    /// This file is automatically generated by Swagger Codegen.
    /// Please update the test case below to test the model.
    /// </remarks>
    [TestFixture]
    public class CustomerProfileTests
    {
        // TODO uncomment below to declare an instance variable for CustomerProfile
        //private CustomerProfile instance;

        /// <summary>
        /// Setup before each test
        /// </summary>
        [SetUp]
        public void Init()
        {
            // TODO uncomment below to create an instance of CustomerProfile
            //instance = new CustomerProfile();
        }

        /// <summary>
        /// Clean up after each test
        /// </summary>
        [TearDown]
        public void Cleanup()
        {

        }

        /// <summary>
        /// Test an instance of CustomerProfile
        /// </summary>
        [Test]
        public void CustomerProfileInstanceTest()
        {
            // TODO uncomment below to test "IsInstanceOfType" CustomerProfile
            //Assert.IsInstanceOfType<CustomerProfile> (instance, "variable 'instance' is a CustomerProfile");
        }

        /// <summary>
        /// Test the property 'LastVisitDate'
        /// </summary>
        [Test]
        public void LastVisitDateTest()
        {
            // TODO unit test for the property 'LastVisitDate'
        }
        /// <summary>
        /// Test the property 'Phone'
        /// </summary>
        [Test]
        public void PhoneTest()
        {
            // TODO unit test for the property 'Phone'
        }
        /// <summary>
        /// Test the property 'VisitsCount'
        /// </summary>
        [Test]
        public void VisitsCountTest()
        {
            // TODO unit test for the property 'VisitsCount'
        }
        /// <summary>
        /// Test the property 'CustomerName'
        /// </summary>
        [Test]
        public void CustomerNameTest()
        {
            // TODO unit test for the property 'CustomerName'
        }
        /// <summary>
        /// Test the property 'Status'
        /// </summary>
        [Test]
        public void StatusTest()
        {
            // TODO unit test for the property 'Status'
        }
        /// <summary>
        /// Test the property 'MembershipLevel'
        /// </summary>
        [Test]
        public void MembershipLevelTest()
        {
            // TODO unit test for the property 'MembershipLevel'
        }
        /// <summary>
        /// Test the property 'Points'
        /// </summary>
        [Test]
        public void PointsTest()
        {
            // TODO unit test for the property 'Points'
        }
        /// <summary>
        /// Test the property '_CustomerProfile'
        /// </summary>
        [Test]
        public void _CustomerProfileTest()
        {
            // TODO unit test for the property '_CustomerProfile'
        }

    }

}


text:
var CrudModule = angular.module('crudMod', ['ng-admin']);

CrudModule.config(require('./list/ListActions'));

module.exports = CrudModule;


text:
{{name}}

{{email}}


text:
define([
    'MultiSet'
], function(MultiSet) {
    const CMultiSet = MultiSet.constructor;

    describe("MultiSet", function() {

        describe("basic usage", function() {

            it("should demonstrate the basic functions of cell-multiset", function() {
                var obj = {iam: 'object'};

                var ms1 = MultiSet.create([7, 67, 7, 7, 'text', obj, 'text', obj]); // use an iterable for initialization.
                var ms2 = Object.create(MultiSet).init([7, 67, 7, 'text', obj, 'text2', obj, 99]);
                var ms3 = new CMultiSet([7, 67, 7, 7, 'text', obj, 'text', obj]); // Use the CMultiSet export for classical inheritance.
                expect(ms1.size).to.eql(8); // cardinality (@alias) of the multiset.
                expect(ms1.toString()).to.eql('{7 => 3, 67 => 1, text => 2, [object Object] => 2}');
                expect(ms1.has(7)).to.be.true;
                expect(ms1.multiplicity(obj)).to.eql(2);
                expect(ms1.multiplicity(undefined)).to.eql(0); // non existent elements have multiplicity 0.
                expect(ms1.equals(ms3)).to.be.true; // checks equality between 2 multisets.

                ms1.union(ms2);

                expect(ms1.toString()).to.eql('{7 => 3, 67 => 1, text => 2, [object Object] => 2, text2 => 1, 99 => 1}');
                expect(ms1.size).to.eql(10);

                var ms4 = ms3.Union(ms2); // use Pascal case Union to output a new MultiSet and leave ms3 unchanged.

                expect(ms3.toString(1)).to.eql('[7, 7, 7, 67, text, text, [object Object], [object Object]]'); // use mode=1 to output single dimension array-like string.
                expect(ms4.toString()).to.eql('{7 => 3, 67 => 1, text => 2, [object Object] => 2, text2 => 1, 99 => 1}');
            });
        });

        describe("constructor", function() {

            it("should be able to construct a multi-set based on an iterable object", function() {

                var ms = new MultiSet.constructor([7, 7, 67, 23]);

                expect(ms.has(7)).to.be.true;
                expect(ms.has(67)).to.be.true;
                expect(ms.has(23)).to.be.true;

                expect(ms.size).to.eql(4);
            });

            it("should be able to construct an empty multi-set using new", function() {

                var ms = new MultiSet.constructor();

                expect(ms.size).to.eql(0);
            });
        });

        describe("$create/spawn", function() {

            it("should create a new multiset", function() {

                var ms = MultiSet.create([7, 67, 23]);

                expect(ms.has(7)).to.be.true;
                expect(ms.has(67)).to.be.true;
                expect(ms.has(23)).to.be.true;
            });

            it("should be able to construct an empty multi-set using its alias spawn", function() {

                var ms = MultiSet.create();

                expect(ms.size).to.eql(0);
            });

            it("should be able to call the static form of create/spawn from the constructor function", function() {

                var ms1 = MultiSet.constructor.create();
                var ms2 = MultiSet.constructor.spawn();

                expect(ms1.size).to.eql(0);
                expect(ms2.size).to.eql(0);
            });
        });

        describe("add", function() {

            it("should be possible to add multiple elements", function() {

                var ms = MultiSet.create().add(7, 67, 23);

                expect(ms.has(7)).to.be.true;
                expect(ms.has(67)).to.be.true;
                expect(ms.has(23)).to.be.true;
            });
        });

        describe("cardinality/size", function() {

            it("should return the cardinality of the set", function() {

                var ms = MultiSet.create();

                expect(ms.size).to.eql(0);
                expect(ms.cardinality).to.eql(0);

                ms.add(7, 7, 67, 23);

                expect(ms.size).to.eql(4);
            });

            it("should return a warning in case of a set", function() {

                var ms = MultiSet.create();

                ms.size = 6;

                expect(console.warn.calledWith(".cardinality/.size property is readonly.")).to.be.true;
            });
        });

        describe("clear", function() {

            it("should clear the set.", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                ms.clear();

                expect(ms.size).to.eql(0);
                expect(ms.elements.size).to.eql(0);
            });
        });

        describe("clone", function() {

            it("should create a clone of a multiset", function() {

                var ms    = MultiSet.create().add(7, 67, 23);
                var clone = ms.clone();

                expect(ms.toString()).to.eql(clone.toString());
            });
        });

        describe("contains", function() {

            it("should check containment", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 1, 2]);

                expect(ms1.contains(ms2)).to.be.false;
                expect(ms2.contains(ms1)).to.be.true;
            });
        });

        describe("difference", function() {

            it("should calculate the difference between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                ms1.difference(ms2);

                expect(ms1.toString(1)).to.eql('[1]');
            });
        });

        describe("Difference", function() {

            it("should calculate the Difference between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                var diff = ms1.Difference(ms2);

                expect(diff.toString(1)).to.eql('[1]');
                expect(ms1.toString(1)).to.eql('[1, 1]');
            });
        });

        describe("each/forEach", function() {

            it("should iterate over the alphabet of the set", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var sum = 0;

                ms.each((val, multiplicity) => {sum += multiplicity});

                expect(sum).to.eql(4);
            });

            it("should be able to call the alias forEach", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var sum = 0;

                ms.forEach((val, multiplicity) => {sum += multiplicity});

                expect(sum).to.eql(4);
            });

            it("should be able to change the context of the callback function or break prematurely", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);
                var ctx = {max: 8};
                var sum = 0;

                // Don't use shorthand functions in this case, or the context is immutably this.
                ms.each(function(val, multiplicity) {if(val > this.max) {return false} sum += multiplicity}, ctx);

                expect(sum).to.eql(2);
            });
        });

        describe("each$/forEach$/eachAll/forEachAll", function() {

            it("should iterate over all elements including repetitions", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var sum                 = 0;
                var multiplicityOfSeven = 0;

                ms.each$(elm => {sum++; if(elm === 7) {multiplicityOfSeven++}});

                expect(sum).to.eql(4);
                expect(multiplicityOfSeven).to.eql(2);
            });

            it("should be possible to use its aliases forEach$/eachAll/forEachAll", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var sum                 = 0;
                var multiplicityOfSeven = 0;

                ms.forEach$(  elm => {sum++; if(elm === 7) {multiplicityOfSeven++}});
                ms.eachAll(   elm => {sum++; if(elm === 7) {multiplicityOfSeven++}});
                ms.forEachAll(elm => {sum++; if(elm === 7) {multiplicityOfSeven++}});

                expect(sum).to.eql(12);
                expect(multiplicityOfSeven).to.eql(6);
            });

            it("should be able to change the context of the callback function or break prematurely", function() {

                var ms = MultiSet.create([56, 7, 7, 7, 7, 67, 23]);

                var ctx = {max: 4};
                var sum = 0;
                var multiplicityOfSeven = 0;

                // Don't use shorthand functions in this case, or the context is immutably this.
                ms.each$(function(elm, count) {
                    sum++;
                    if(elm === 7) {multiplicityOfSeven++}
                    return count < (this.max-1)
                }, ctx);

                expect(sum).to.eql(4);
                expect(multiplicityOfSeven).to.eql(3);
            });
        });

        describe("equals", function() {

            it("should check equality between 2 multisets", function() {

                var ms1 = MultiSet.create([7, 7, 67, 23]);
                var ms2 = MultiSet.create([7, 7, 67, 23]);
                var ms3 = MultiSet.create([7, 7, 7, 67, 23]);

                expect(ms1 == ms2).to.be.false;
                expect(ms1 === ms2).to.be.false;
                expect(ms1.equals(ms2)).to.be.true;
                expect(ms1.equals(ms3)).to.be.false;
            });
        });

        describe("entries", function() {

            it("should output an iterable object containing value & multiplicity", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var setIter = ms.entries();

                expect(setIter.next().value).to.eql([ 7, 2]);
                expect(setIter.next().value).to.eql([67, 1]);
                expect(setIter.next().value).to.eql([23, 1]);
            });
        });

        describe("info (static/non-static)", function() {

            it("should be possible to read the info object from the constructor as well as from the prototype", function() {
                expect(MultiSet.constructor.info.name).to.eql('cell-multiset');
                expect(MultiSet.info.name).to.eql('cell-multiset');
            });
        });

        describe("intersection/and", function() {

            it("should calculate the intersection between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1, 1, 3]);
                var ms2 = MultiSet.create([1, 1]);

                ms1.intersection(ms2);

                expect(ms1.toString(1)).to.eql('[1, 1]');
            });

            it("should be able to use the alias and", function() {

                var ms1 = MultiSet.create([1, 1, 1, 3]);
                var ms2 = MultiSet.create([1, 1]);

                ms1.and(ms2);

                expect(ms1.toString(1)).to.eql('[1, 1]');
            });
        });

        describe("Intersection/And", function() {

            it("should calculate the Intersection between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1, 1, 3]);
                var ms2 = MultiSet.create([1, 1]);

                var intersection = ms1.Intersection(ms2);

                expect(intersection.toString(1)).to.eql('[1, 1]');
                expect(ms1.toString(1)).to.eql('[1, 1, 1, 3]');
            });

            it("should be able to use the alias And", function() {

                var ms1 = MultiSet.create([1, 1, 1, 3]);
                var ms2 = MultiSet.create([1, 1]);

                var intersection = ms1.And(ms2);

                expect(intersection.toString(1)).to.eql('[1, 1]');
                expect(ms1.toString(1)).to.eql('[1, 1, 1, 3]');
            });
        });

        describe("isSubsetOf/isContainedIn", function() {

            it("should check if it is a subset of another", function() {

                var ms1 = MultiSet.create([1, 1, 2]);
                var ms2 = MultiSet.create([1, 1, 2, 2, 3]);

                expect(ms1.isSubsetOf(ms2)).to.be.true;
                expect(ms2.isSubsetOf(ms1)).to.be.false;
                expect(ms1.isContainedIn(ms2)).to.be.true;
                expect(ms2.isContainedIn(ms1)).to.be.false;
            });
        });

        describe("keys/underlyingElements", function() {

            it("should return all unique elements", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var setIter = ms.keys();

                expect(setIter.next().value).to.eql(7);
                expect(setIter.next().value).to.eql(67);
                expect(setIter.next().value).to.eql(23);
            });

            it("should be possible to use the alias 'underlyingElements'", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var setIter = ms.underlyingElements();

                expect(setIter.next().value).to.eql(7);
                expect(setIter.next().value).to.eql(67);
                expect(setIter.next().value).to.eql(23);
            });
        });

        describe("multiplicity", function() {

            it("should return the multiplicity of an element", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                expect(ms.multiplicity(7)).to.eql(2);
                expect(ms.multiplicity(67)).to.eql(1);
                expect(ms.multiplicity('ndef')).to.eql(0);
            });
        });

        describe("remove/delete", function() {

            it("should be possible to remove multiple elements", function() {

                var ms = MultiSet.create().add(7, 67, 23).remove(8, 23).delete(7);

                expect(ms.has(7)).to.be.false;
                expect(ms.has(67)).to.be.true;
                expect(ms.has(23)).to.be.false;
            });
        });

        describe("symmetricDifference/exclusion", function() {

            it("should calculate the symmetricDifference between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1, 3, 3]);
                var ms2 = MultiSet.create([1, 2, 3, 3]);

                ms1.symmetricDifference(ms2);

                expect(ms1.toString(1)).to.eql('[1, 2]');
            });

            it("should be able to use the alias exclusion", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                ms1.exclusion(ms2);

                expect(ms1.toString(1)).to.eql('[1, 2]');
            });
        });

        describe("SymmetricDifference/Exclusion", function() {

            it("should calculate the SymmetricDifference between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1, 3, 3]);
                var ms2 = MultiSet.create([1, 2, 3, 3]);

                var sd = ms1.SymmetricDifference(ms2);

                expect(sd.toString(1)).to.eql('[1, 2]');
                expect(ms1.toString(1)).to.eql('[1, 1, 3, 3]');
            });

            it("should be possible to use the alias Exclusion", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                var sd = ms1.Exclusion(ms2);

                expect(sd.toString(1)).to.eql('[1, 2]');
                expect(ms1.toString(1)).to.eql('[1, 1]');
            });
        });

        describe("toString/stringify", function() {

            it("should, by default, output all elements in {value => multiplicity, ...} pairs (like a map).", function() {

                var ms = MultiSet.create().add(7, 7, 7, 67, 23, 8).remove(23);

                expect(ms.toString()).to.eql('{7 => 3, 67 => 1, 8 => 1}');
            });

            it("should output all elements, including repetitions, as a string if mode is 1 (array like).", function() {

                var ms = MultiSet.create().add(7, 7, 7, 67, 23, 8).remove(23);

                expect(ms.toString(1)).to.eql('[7, 7, 7, 67, 8]');
            });

            it("should output a formal representation in case mode is -1.", function() {

                var ms = MultiSet.create().add(7, 7, 7, 67, 23, 8).remove(23);

                expect(ms.toString(-1)).to.eql('({7, 67, 8}, {(7, 3), (67, 1), (8, 1)})');
            });
        });

        describe("union/or", function() {

            it("should calculate the union between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                ms1.union(ms2);

                expect(ms1.toString(1)).to.eql('[1, 1, 2]');
            });

            it("should be able to use the alias or", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                ms1.or(ms2);

                expect(ms1.toString(1)).to.eql('[1, 1, 2]');
            });
        });

        describe("Union/Or", function() {

            it("should calculate the Union between 2 multisets", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                var union = ms1.Union(ms2);

                expect(union.toString(1)).to.eql('[1, 1, 2]');
                expect(ms1.toString(1)).to.eql('[1, 1]');
            });

            it("should be able to use the alias Or", function() {

                var ms1 = MultiSet.create([1, 1]);
                var ms2 = MultiSet.create([1, 2]);

                var union = ms1.Or(ms2);

                expect(union.toString(1)).to.eql('[1, 1, 2]');
                expect(ms1.toString(1)).to.eql('[1, 1]');
            });
        });

        describe("values", function() {

            it("should return all, including repeating, elements", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var setIter = ms.values();

                expect(setIter.next().value).to.eql(7);
                expect(setIter.next().value).to.eql(7);
                expect(setIter.next().value).to.eql(67);
            });
        });

        describe("[@@iterator]", function() {

            it("should return all, including repeating, elements", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                var keySum          = 0;
                var multiplicitySum = 0;

                for(let [value, multiplicity] of ms)
                {
                    keySum          += value;
                    multiplicitySum += multiplicity;
                }

                expect(keySum).to.eql(97);
                expect(multiplicitySum).to.eql(4);
            });
        });

        describe("[@@species]", function() {

            it("should return the MultiSet constructor if the species is requested (static/non-static)", function() {

                var ms = MultiSet.create([7, 7, 67, 23]);

                expect(ms[Symbol.species]).to.eql(MultiSet.constructor);
                expect(ms.constructor[Symbol.species]).to.eql(MultiSet.constructor);
            });
        });

        if(window.chrome)
        {
            // disabled because this does not work in firefox yet
            describe("[@@toStringTag]", function() {

                it("should return the custom type [object MultiSet] in case Object.prototype.toString.call(ms) is used", function() {

                    var ms = MultiSet.create([7, 7, 67, 23]);

                    expect(Object.prototype.toString.call(ms)).to.eql('[object MultiSet]');
                });
            });
        }
    });
});


text:
<?php

/**
 * System Import SimplifiedPHP File
 */
type::$system->import = function ($context) {
  return cmd('@import', $context, array('string' => function ($command, $string) use ($context) {
    if ($string == '') {
      throw new Exception("Cannot import empty string");
    }

    /**
     * Future imports are relative to the file the @import is defined in
     * regardless of the current file being executed
     */
    try {
      $dir = get($context, '#directory');
      if ($string[0] !== '/') {
        $string = $dir . $string;
      }
    }
    catch(Exception $e) {}
    try {
      $code = parse(file_get_contents($string), $context);
      $code->{'#directory'} = dirname(realpath($string)) . '/';
      return run($code);
    }
    catch(Exception $e) {
      if ($e instanceof InternalException) {
        throw $e;
      }
      $f = realpath($string);
      $m = $e->getMessage();
      $from = $e->getFile() . ':' . $e->getLine();
      throw new Exception("$m in $f (from $from)", 0, $e);
    }
  }));
};

/**
 * System Redirect
 */
type::$system->redirect = function ($context) {
  return cmd('@redirect', $context, array('string' => function ($command, $url) use ($context) {
    if (headers_sent()) {
      echo '<meta http-equiv="refresh" content="0; url=' . $url . '">';
    } else {
      header("Location: $url", true, 302);
    }
    echo 'Redirecting to ' . $url . '';
    exit;
  }));
};

/**
 * System File
 */
type::$system->file = function ($context) {
  return cmd('@file', $context, array('string' => function ($command, $string) use ($context) {
    return ofile($string);
  }));
};

/**
 * System Dir
 */
type::$system->dir = function ($context) {
  return cmd('@dir', $context, array('string' => function ($command, $string) use ($context) {
    return odir($string);
  }));
};

/**
 * System Plugin
 */
type::$system->plugin = function ($context) {
  $plugins = new stdClass;
  $plugins->{'#get'} = function ($plugins, $name) {
    require_once(__DIR__ . "/../../plugins/sphp-$name/$name.php");
    return sys::$plugin->$name;
  };
  return $plugins;
};

/**
 * System Exit
 */
type::$system->exit = function ($context) {
  exit;
};

/**
 * System Trace
 */
type::$system->trace = function ($context) {
  echo get($context, 'to_json');
  die;
};

/**
 * System Parent
 */
type::$system->parent = function ($context) {
  return is_object($context) && isset($context->{'#parent'}) ? $context->{'#parent'} : null;
};

/**
 * System Self
 */
type::$system->self = function ($context) {
  return $context;
};

/**
 * System Test
 */
type::$system->test = function ($context) {
  return cmd('@test', $context, array(
    'object' => function ($cmd, $object) {
      $e = null;
      try {
        $status = run($object) === true ? 'pass' : 'fail';
      }
      catch(Exception $e) {
        $status = 'error';
      }
      $data = array();
      if (!is_null($e)) {
        $data['message'] = exc($e);
      }
      $data['status'] = $status;
      $data['code'] = get($object, 'to_source');
      sys::$tests['tests'][] = $data;
    }
  ));
};

/**
 * System Request
 */
type::$system->request = function ($context) {
  static $request;
  if (!is_object($request)) {
    $request = obj('object');
    $request->method = $_SERVER['REQUEST_METHOD'];

    $request->args = (object) $_GET;
    $request->form = (object) $_POST;
    $request->files = (object) $_FILES;
    $request->cookie = (object) $_COOKIE;

    $request->json = json_decode(file_get_contents('php://input'));

    $request->host = $_SERVER['HTTP_HOST'];
    $request->path = $_SERVER['REQUEST_URI'];
    $request->query = $_SERVER['QUERY_STRING'];
    $name = explode('?', $request->path);
    $name = array_shift($name);
    $name = explode('/', $name);
    $request->basename = array_pop($name);

    $request->remote_addr = $_SERVER['REMOTE_ADDR'];
    $request->remote_port = $_SERVER['REMOTE_PORT'];

    $request->protocol = $_SERVER['SERVER_PROTOCOL'];
    $request->time = $_SERVER['REQUEST_TIME_FLOAT'];

    $request->file = obj('file');
    $request->file->path = $_SERVER['SCRIPT_FILENAME'];
  }
  return $request;
};

/**
 * System Timer
 */
type::$system->timer = function () {
  return number_format(1000 * microtime(true) - 1000 * sys::$timer, 1);
};

/**
 * Finally
 */
type::$system->finally = function($context) {
  return cmd('@finally', $context, array('object' => function ($command, $object) {
    array_unshift(sys::$finally, $object);
  }));
};

/**
 * Null
 */
type::$system->null = function($context) {
  return null;
};

/**
 * Continue
 */
type::$system->continue = function($context) {
  throw new ContinueCommand("@continue");
};

/**
 * Continue Exception
 */
class ContinueCommand extends InternalException {}

/**
 * Break
 */
type::$system->break = function($context) {
  throw new BreakCommand("@break");
};

/**
 * Break Exception
 */
class BreakCommand extends InternalException {}

/**
 * Stop
 */
type::$system->stop = function($context) {
  throw new StopCommand("@stop");
};

/**
 * Stop Exception
 */
class StopCommand extends InternalException {}

/**
 * System Class
 */
class sys {
  public static $tests = array('tests' => array());
  public static $finally = array();
  public static $plugin = null;
  public static $timer = null;
}

/**
 * Plugins
 */
sys::$plugin = new stdClass;

/**
 * Start timer
 */
sys::$timer = microtime(true);

/**
 * Process Finally
 */
register_shutdown_function(function () {
  if (count(sys::$tests['tests'])) {
    sys::$tests['total'] = count(sys::$tests['tests']);
    foreach(sys::$tests['tests'] as $test) {
      $status = $test['status'];
      if (!isset(sys::$tests[$status])) {
        sys::$tests[$status] = 0;
      }
      sys::$tests[$status]++;
    }
    echo json_encode(sys::$tests);
    exit;
  }
  foreach(sys::$finally as $object) {
    run($object);
  }
});


text:
/* tables */
table.tablesorter thead tr .header {
	background-image: url(bg.gif);
	background-repeat: no-repeat;
	background-position: center right;
	cursor: pointer;
  padding-right: 22px;
}
table.tablesorter thead tr .headerSortUp {
	background-image: url(asc.gif);
}
table.tablesorter thead tr .headerSortDown {
	background-image: url(desc.gif);
}


text:
The MonoGame Framework dependency used here is a Portable Class Library created using this guide:
https://github.com/craftworkgames/MonoGame.Extended/blob/master/Documentation/MonoGamePCL.md


text:
<?php
declare(strict_types=1);

namespace Cake\ORM\Locator;

use Cake\ORM\TableRegistry;

/**
 * Contains method for setting and accessing LocatorInterface instance
 */
trait LocatorAwareTrait
{
    /**
     * Table locator instance
     *
     * @var \Cake\ORM\Locator\LocatorInterface|null
     */
    protected $_tableLocator;

    /**
     * Sets the table locator.
     *
     * @param \Cake\ORM\Locator\LocatorInterface $tableLocator LocatorInterface instance.
     * @return $this
     */
    public function setTableLocator(LocatorInterface $tableLocator)
    {
        $this->_tableLocator = $tableLocator;

        return $this;
    }

    /**
     * Gets the table locator.
     *
     * @return \Cake\ORM\Locator\LocatorInterface
     */
    public function getTableLocator(): LocatorInterface
    {
        if ($this->_tableLocator === null) {
            $this->_tableLocator = TableRegistry::getTableLocator();
        }

        return $this->_tableLocator;
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p137;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test2749 {
    Production2749 objectUnderTest = new Production2749();

    @Test
    public void testProperty0() {
        Production2740 value = new Production2740();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production2744 value = new Production2744();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production2748 value = new Production2748();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}