text:
package org.assertj.core.api;

import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.and;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.api.BDDAssertions.thenExceptionOfType;
import static org.assertj.core.api.BDDAssertions.thenIOException;
import static org.assertj.core.api.BDDAssertions.thenIllegalArgumentException;
import static org.assertj.core.api.BDDAssertions.thenIllegalStateException;
import static org.assertj.core.api.BDDAssertions.thenNoException;
import static org.assertj.core.api.BDDAssertions.thenNullPointerException;
import static org.assertj.core.api.BDDAssertions.thenObject;
import static org.assertj.core.api.BDDAssertions.thenThrownBy;
import static org.assertj.core.api.BDDAssertions.thenWith;
import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import static org.assertj.core.util.Lists.list;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Spliterator;
import java.util.function.DoublePredicate;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link BDDAssertions#then(String)}</code>.
 *
 * @author Mariusz Smykula
 */
class BDDAssertions_then_Test {

  private AssertFactory<String, StringAssert> stringAssertFactory = StringAssert::new;

  private AssertFactory<Integer, IntegerAssert> integerAssertFactory = IntegerAssert::new;

  @Test
  void then_char() {
    then('z').isGreaterThan('a');
  }

  @Test
  void then_Character() {
    then(Character.valueOf('A')).isEqualTo(Character.valueOf('A'));
  }

  @Test
  void then_char_array() {
    then(new char[] { 'a', 'b', 'c' }).contains('b');
  }

  @Test
  void then_CharSequence() {
    then("abc".subSequence(0, 1)).contains("a");
  }

  @Test
  void then_Class() {
    then("Foo".getClass()).isEqualTo(String.class);
  }

  @Test
  void should_delegate_to_assert_comparable() {

    class IntBox implements Comparable<IntBox> {

      private final Integer number;

      IntBox(Integer number) {
        this.number = number;
      }

      @Override
      public int compareTo(IntBox o) {
        return number.compareTo(o.number);
      }
    }

    then(new IntBox(1)).isLessThan(new IntBox(2));
  }

  @Test
  void then_Iterable() {
    Iterable<String> iterable = Arrays.asList("1");
    then(iterable).contains("1");
    then(iterable, StringAssert.class).first().startsWith("1");
    then(iterable, stringAssertFactory).first().startsWith("1");
    then(iterable).first(as(STRING)).startsWith("1");
    then(iterable).singleElement(as(STRING)).startsWith("1");
  }

  @Test
  void then_Iterator() {
    Iterator<String> iterator = singletonList("1").iterator();
    then(iterator).hasNext();
  }

  @Test
  void then_double() {
    then(1d).isNotZero();
  }

  @Test
  void then_Double() {
    then(Double.valueOf(1d)).isNotZero();
  }

  @Test
  void then_double_array() {
    then(new double[] { 1d, 2d }).contains(2d);
  }

  @Test
  void then_float() {
    then(1f).isEqualTo(1f);
  }

  @Test
  void then_Float() {
    then(Float.valueOf(1f)).isEqualTo(1f);
  }

  @Test
  void then_float_array() {
    then(new float[] { 1f, 2f }).contains(2f);
  }

  @Test
  void then_long() {
    then(1L).isEqualTo(1L);
  }

  @Test
  void then_Long() {
    then(Long.valueOf(1L)).isEqualTo(1L);
  }

  @Test
  void then_long_array() {
    then(new long[] { 1L, 2L }).contains(2L);
  }

  @Test
  void then_Object() {
    then(new Object()).isNotNull();
  }

  @Test
  void then_Object_array() {
    then(new Object[] { new Object(), new Object() }).hasSize(2);
  }

  @Test
  void then_short() {
    then((short) 1).isEqualTo((short) 1);
  }

  @Test
  void then_Short() {
    then(Short.valueOf("1")).isEqualTo((short) 1);
  }

  @Test
  void then_short_array() {
    then(new short[] { (short) 1, (short) 2 }).contains((short) 2);
  }

  @Test
  void then_Throwable() {
    then(new IllegalArgumentException("Foo")).hasMessage("Foo");
  }

  @Test
  void then_BigDecimal() {
    then(BigDecimal.ONE).isEqualTo(BigDecimal.valueOf(1));
  }

  @Test
  void then_boolean() {
    then(true).isEqualTo(Boolean.TRUE);
  }

  @Test
  void then_Boolean() {
    then(Boolean.TRUE).isEqualTo(true);
  }

  @Test
  void then_boolean_array() {
    then(new boolean[] { true, false }).isEqualTo(new boolean[] { true, false });
  }

  @Test
  void then_byte() {
    then((byte) 7).isEqualTo((byte) 0x07);
  }

  @Test
  void then_Byte() {
    then(Byte.valueOf((byte) 8)).isEqualTo((byte) 0x08);
  }

  @Test
  void then_byte_array() {
    then(new byte[] { 10, 11 }).contains((byte) 11);
  }

  @Test
  void then_int() {
    then(1).isEqualTo(1);
  }

  @Test
  void then_Integer() {
    then(Integer.valueOf(4)).isEqualTo(4);
  }

  @Test
  void then_BigInteger() {
    then(BigInteger.valueOf(4)).isEqualTo(4);
  }

  @Test
  void then_int_array() {
    then(new int[] { 2, 3 }).isEqualTo(new int[] { 2, 3 });
  }

  @Test
  void then_List() {
    List<Integer> list = list(5, 6);
    then(list).hasSize(2);
    then(list, IntegerAssert.class).first().isLessThan(10);
    then(list, integerAssertFactory).first().isLessThan(10);
    then(list).first(as(INTEGER)).isEqualTo(5);
    then(list(5)).singleElement(as(INTEGER)).isEqualTo(5);
  }

  @Test
  void then_String() {
    then("Foo").isEqualTo("Foo").isGreaterThan("Bar");
  }

  @Test
  void then_Date() {
    then(new Date()).isNotNull();
  }

  @Test
  void then_Map() {
    then(new HashMap<>()).isEmpty();
  }

  @Test
  void should_build_ThrowableAssert_with_throwable_thrown() {
    thenThrownBy(() -> {
      throw new Throwable("something was wrong");
    }).isInstanceOf(Throwable.class)
      .hasMessage("something was wrong");
  }

  @Test
  void should_build_ThrowableAssert_with_throwable_thrown_with_format_string() {
    thenThrownBy(() -> {
      throw new Throwable("something was wrong");
    }).isInstanceOf(Throwable.class)
      .hasMessage("something was %s", "wrong");
  }

  @Test
  void then_explicit_Object() {
    thenObject(new LinkedList<>()).matches(l -> l.peek() == null);
  }

  @Test
  void then_with() {
    thenWith("foo", string -> assertThat(string).startsWith("f"));
  }

  @Test
  void then_with_multiple_requirements() {
    thenWith("foo",
             string -> assertThat(string).startsWith("f"),
             string -> assertThat(string).endsWith("o"));
  }

  @Test
  void then_URI() {
    then(URI.create("http://assertj.org")).hasNoPort();
  }

  @Test
  void then_Optional() {
    then(Optional.of("foo")).hasValue("foo");
  }

  @Test
  void then_OptionalInt() {
    then(OptionalInt.of(1)).hasValue(1);
  }

  @Test
  void then_OptionalDouble() {
    then(OptionalDouble.of(1)).hasValue(1);
  }

  @Test
  void then_Predicate() {
    Predicate<String> actual = String::isEmpty;
    then(actual).accepts("");
  }

  @Test
  void then_IntPredicate() {
    IntPredicate predicate = val -> val <= 2;
    then(predicate).accepts(1);
  }

  @Test
  void then_LongPredicate() {
    LongPredicate predicate = val -> val <= 2;
    then(predicate).accepts(1);
  }

  @Test
  void then_DoublePredicate() {
    DoublePredicate predicate = val -> val <= 2;
    then(predicate).accepts(1);
  }

  @Test
  void then_OptionalLong() {
    then(OptionalLong.of(1)).hasValue(1);
  }

  @Test
  void then_Spliterator() {
    Spliterator<Integer> spliterator = Stream.of(1, 2).spliterator();
    then(spliterator).hasCharacteristics(Spliterator.SIZED);
  }

  @Test
  void then_Duration() {
    then(Duration.ofHours(1)).isNotNull().isPositive();
  }

  @SuppressWarnings("static-access")
  @Test
  void and_then() {
    and.then(true).isNotEqualTo(false);
    and.then(1L).isEqualTo(1L);
  }

  @Test
  void should_build_ThrowableTypeAssert_with_throwable_thrown() {
    thenExceptionOfType(Throwable.class).isThrownBy(() -> methodThrowing(new Throwable("boom")))
                                        .withMessage("boom");
  }

  @Test
  void should_build_NotThrownAssert_with_throwable_not_thrown() {
    thenNoException().isThrownBy(() -> methodNotThrowing());
  }

  @Test
  void should_build_ThrowableTypeAssert_with_NullPointerException_thrown() {
    thenNullPointerException().isThrownBy(() -> methodThrowing(new NullPointerException("something was wrong")))
                              .withMessage("something was wrong");
  }

  @Test
  void should_build_ThrowableTypeAssert_with_IllegalArgumentException_thrown() {
    thenIllegalArgumentException().isThrownBy(() -> methodThrowing(new IllegalArgumentException("something was wrong")))
                                  .withMessage("something was wrong");
  }

  @Test
  void should_build_ThrowableTypeAssert_with_IllegalStateException_thrown() {
    thenIllegalStateException().isThrownBy(() -> methodThrowing(new IllegalStateException("something was wrong")))
                               .withMessage("something was wrong");
  }

  @Test
  void should_build_ThrowableTypeAssert_with_IOException_thrown() {
    thenIOException().isThrownBy(() -> methodThrowing(new IOException("something was wrong")))
                     .withMessage("something was wrong");
  }

  private static void methodThrowing(Throwable throwable) throws Throwable {
    throw throwable;
  }

  private static void methodNotThrowing() {}

}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class HostNtpConfig extends DynamicData {
  public String[] server;

  public String[] getServer() {
    return this.server;
  }

  public void setServer(String[] server) {
    this.server=server;
  }
}

redpajama_set_name: RedPajamaGithub


text:
module Docushin
  class ApplicationController < ActionController::Base
    layout "docushin"

    private
    def authorize!
      render :text => "Unauthorized" unless Rails.env.development?
      return false
    end

    def load_route_set
      @route_set = Docushin::RouteSet.new
    end

    def set_default_base_path
      File.join(Rails.root, 'doc', 'docushin')
    end
  end
end


text:
import re

from flask.ext.script import Manager

from forms import create_app, app

forms_app = create_app()
manager = Manager(forms_app)

@manager.command
def run(port=5000):
    app.run(port=int(port))

@manager.command
def show_list():
    print 'Listing all referer / email pairs and counts...'

    values = []

    for key in app.REDIS.keys('*counter*'):
        count = int(app.REDIS.get(key))
        keyhash = key.split('_')[-1]
        email, host = app._get_values_for_hash(keyhash)
        values.append((count, email, host))

    values.sort(key=lambda x: x[0], reverse=True)

    total = {}
    total['Pairs'] = len(values)
    total['Sent'] = sum([x[0] for x in values])
    total['Unique'] = len(set([x[1] for x in values]))

    def format_dict(d):
        return ', '.join([k+': '+str(d[k]) for k in d])

    print '\n---\n'

    print 'Totals - ', format_dict(total)

    print '\n---\n'

    for v in values: print v

    print '\n---\n'

    print 'Totals - ', format_dict(total)

    print 'Done'

def _matchhosts(name):
    r = app.REDIS
    keys = r.keys('forms_hash_host_*')
    hosts = filter(lambda x: re.match(r".*%s"%name, r.get(x)), keys)
    return map(lambda x: x.split("_")[-1], hosts)

def _print(hostid):
    r = app.REDIS
    keys = r.keys("*%s*" % hostid)
    results = dict((k,r.get(k)) for k in keys)
    print results

def _del(hostid):
    r = app.REDIS
    keys = r.keys("*%s*" % hostid)
    for k in keys:
        r.delete(k)

@manager.command
def print_hosts(name):
    count = 0
    for host in _matchhosts(name):
        _print(host)
        count +=1
    print "found %d items" % count

@manager.command
def delete_hosts(name):
    count = 0
    for host in _matchhosts(name):
        _del(host)
        count +=1
    print "deleted %d items" % count

if __name__ == "__main__":
    manager.run()


text:
/* definitions for obf routines */

#ifdef  __cplusplus
extern "C" {
#endif

#define HASH_TYPE_MD5     1
#define HASH_TYPE_SHA1    2
#define HASH_TYPE_DEFAULT 3
#define SHA1_FLAG_STRING ":::sha1"

void obfDecodeByKey(char *in, char *key, char *out);
int obfRmPw(int opt);
int obfGetPw(char *pw);
int obfSavePw(int promptOpt, int fileOpt, int printOpt, char *pwArg);
int obfTempOps(int tmpOpt);
int obfiGetEnvKey();
int obfiGetTv(char *fileName);
int obfiDecode(char *in, char *out, int extra);
int obfiGetPw(char *fileName, char *pw);
int obfiOpenOutFile(char *fileName, int fileOpt);
int obfiWritePw(int fd, char *pw);
void obfiEncode(char *in, char *out, int extra);
void obfEncodeByKey(char *in, char *key, char *out);
void obfEncodeByKeyV2(char *in, char *key, char *key2, char *out);
void obfDecodeByKeyV2(char *in, char *key, char *key2, char *out);
void obfMakeOneWayHash(int hashType, unsigned char *inBuf,
                        int inBufSize, unsigned char *outHash);
void obfSetDefaultHashType(int type);
int obfGetDefaultHashType();
char *obfGetMD5Hash(char *stringToHash);
#ifdef  __cplusplus
}
#endif


text:
**Elm**, **SASS**, **Gulp** (ES6), **Javscript** synchronized to Elm bootstrap.

## What's in the Quickstart
This project contains the *elm*, *npm* and *Gulp* configuration to start developing
 Elm SPA from scratch.

It comes with the following packages available and configured:

* [Bootstrap](http://getbootstrap.com/) is automatically installed via *npm* and
 copied to the `public/dist/css` folder, then it is imported in the `index.html`.
* [SASS](http://sass-lang.com/) preprocessor is used to compile the assets found in
 `src/styles` and minify them to `public/dist/css`, then included in the `index.html`.
* [Elm](http://elm-lang.org/) language is supported, compiling all the files found in
 `src/elm`, minifying them to `public/dist/js`, and included in the `index.html`.

Furthermore, it offers the hook to execute your external Javascript code detecting
 Elm's bootstrap, using the
  [MutationObserver API](https://developer.mozilla.org/en/docs/Web/API/MutationObserver).
You can find the code in `public/index.html`, the function is this one:

```javascript
    var mo = new MutationObserver(function(mutationRecords, instance) {
        // check modifications
        for (var i = 0; i < mutationRecords.length; i += 1) {
            // if new DOM nodes
            if (mutationRecords[i].addedNodes.length > 0) {
                // elm just started!
                console.debug('Hello from the JS, Elm just started rendering!');
                mo.disconnect();
            }
        }
    });
```

## Why the need to synchronize Javascript to Elm?
When we where building [MaltaJS registration page](https://github.com/roedit/maltajs-elm)
 using Elm, we needed a quick  way to run the [GoogleMap](https://developers.google.com/maps/)
 plugin without messing up with Elm code, being sure that the Elm app had
 already rendered its HTML.

Since the external plugin doesn't need to exchange data with Elm, a Port looked
 too complex as a solution.

If you need to run a plugin like *GoogleMap* or a *jQuery plugin*, you can use this
 method to have the modules running on your page completely independent each other,
 while guaranteeing that Elm will be bootstrapped first.

## Instructions

Ensure you have installed:
* Node >= 5
* Npm >= 3
* Gulp

```sh
$ git clone git@github.com:pietro909/elm-quickstart.git
$ npm install
$ gulp build
$ npm start
```

Open `localhost:8000` with your browser.

## Where is the code
Elm sources are to be placed under `src/elm`.

SASS sources are located in `src/styles`.

The Gulp's configuration files are into `gulp/` folder.

## Credits
I strongly thank my colleague [Andrei Toma](http://andreitoma.com/) for helping me
 with Gulp configuration, and the whole Elm community on Slack: they always welcome
 newbies and are happy to help!


text:
  # Window class
  class Window

    attr_reader :num
    attr_reader :win_id
    attr_reader :activity
    attr_reader :wvx, :wvy, :wvw, :wvh
    attr_reader :px, :py
    attr_reader :visibility

    # initialize
    #
    # @param num [Fixnum] Ordering number in Window Manager
    # @param win_id [String] the window ID
    # @param activity [String] the activity (or sometimes other component) owning the window
    # @param wvx [Fixnum] window's virtual X
    # @param wvy [Fixnum] window's virtual Y
    # @param wvw [Fixnum] window's virtual Width
    # @param wvh [Fixnum] window's virtual Height
    # @param px [Fixnum] parent's X
    # @param py [Fixnum] parent's Y
    # @param visibility [Fixnum] visibility of the window
    def initialize(num, win_id, activity, wvx, wvy, wvw, wvh, px, py, visibility)
      @num, @win_id, @activity = num, win_id, activity
      @wvx, @wvy, @wvw, @wvh = wvx, wvy, wvw, wvh
      @px, @py = px, py
      @visibility = visibility
    end

    def to_s
      "Window(#{@num}, wid=#{@win_id}, a=#{@activity}, x=#{@wvx}, y=#{@wvy}, w=#{@wvw}, h=#{@wvh}, px=#{@px}, py=#{@py}, v=#{@visibility})"
    end
  end


text:
package au.gov.dva.sopapi;

public enum Environment {
    prod,
    devtest,
    dev,
    devtestlocal;

}


text:
package org.apache.xmpbox;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.schema.XMPSchema;
import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpParsingException;
import org.apache.xmpbox.xml.XmpSerializationException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;

/**
 * Test XMP MetaData Transformer
 *
 * @author a183132
 *
 */
public class XMPMetaDataTest
{

    protected XMPMetadata metadata;
    protected Document parent;
    protected XMPSchema tmp, tmp2;

    @Before
    public void init() throws Exception
    {
        metadata = XMPMetadata.createXMPMetadata();
        String tmpNsURI = "http://www.test.org/schem/";
        tmp = new XMPSchema(metadata, tmpNsURI, "test");
        tmp.addQualifiedBagValue("BagContainer", "Value1");
        tmp.addQualifiedBagValue("BagContainer", "Value2");
        tmp.addQualifiedBagValue("BagContainer", "Value3");

        tmp.addUnqualifiedSequenceValue("SeqContainer", "Value1");
        tmp.addUnqualifiedSequenceValue("SeqContainer", "Value2");
        tmp.addUnqualifiedSequenceValue("SeqContainer", "Value3");

        tmp.addProperty(metadata.getTypeMapping().createText(null, "test", "simpleProperty", "YEP"));

        tmp2 = new XMPSchema(metadata, "http://www.space.org/schem/", "space", "space");
        tmp2.addUnqualifiedSequenceValue("SeqSpContainer", "ValueSpace1");
        tmp2.addUnqualifiedSequenceValue("SeqSpContainer", "ValueSpace2");
        tmp2.addUnqualifiedSequenceValue("SeqSpContainer", "ValueSpace3");

        metadata.addSchema(tmp);

        metadata.addSchema(tmp2);

        // Check schema getting
        Assert.assertEquals(tmp, metadata.getSchema(tmpNsURI));
        Assert.assertNull(metadata.getSchema("THIS URI NOT EXISTS !"));
    }

    @Test
    public void testAddingSchem()
    {

        List<XMPSchema> vals = metadata.getAllSchemas();
        Assert.assertTrue(vals.contains(tmp));
        Assert.assertTrue(vals.contains(tmp2));
    }

    /*
     * @Test public void displayResult() throws TransformException { System.out.println
     * ("info used:\n XPacketBegin:"+metadata.getXpacketBegin()+ "\n XPacketID:"+metadata.getXpacketId());
     * SaveMetadataHelper.serialize(metadata, true, System.out);
     *
     * }
     */

    @Test(expected = org.apache.xmpbox.xml.XmpSerializationException.class)
    public void testTransformerExceptionMessage() throws XmpSerializationException
    {
        throw new XmpSerializationException("TEST");
    }

    @Test(expected = org.apache.xmpbox.xml.XmpSerializationException.class)
    public void testTransformerExceptionWithCause() throws XmpSerializationException
    {
        throw new XmpSerializationException("TEST", new Throwable());
    }

    @Test
    public void testInitMetaDataWithInfo() throws Exception
    {
        String xpacketBegin = "TESTBEG", xpacketId = "TESTID", xpacketBytes = "TESTBYTES", xpacketEncoding = "TESTENCOD";
        metadata = XMPMetadata.createXMPMetadata(xpacketBegin, xpacketId, xpacketBytes, xpacketEncoding);
        Assert.assertEquals(xpacketBegin, metadata.getXpacketBegin());
        Assert.assertEquals(xpacketId, metadata.getXpacketId());
        Assert.assertEquals(xpacketBytes, metadata.getXpacketBytes());
        Assert.assertEquals(xpacketEncoding, metadata.getXpacketEncoding());
    }

    /**
     * Test whether the bug reported in PDFBOX-3257 and PDFBOX-3258 has been fixed: setting
     * CreateDate twice must not insert two elements, and fixing this must not interfere with the
     * handling of lists.
     *
     * @throws IOException
     * @throws XmpParsingException
     */
    @Test
    public void testPDFBOX3257() throws IOException, XmpParsingException
    {
        // taken from file test-landscape2.pdf
        String xmpmeta = "<?xpacket id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
                + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:14:39\">\n"
                + "   <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
                + "      <rdf:Description rdf:about=\"\"\n"
                + "            xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
                + "         <xap:CreatorTool>Acrobat PDFMaker 8.1 for Word</xap:CreatorTool>\n"
                + "         <xap:ModifyDate>2008-11-12T15:29:43+01:00</xap:ModifyDate>\n"
                + "         <xap:CreateDate>2008-11-12T15:29:40+01:00</xap:CreateDate>\n"
                + "         <xap:MetadataDate>2008-11-12T15:29:43+01:00</xap:MetadataDate>\n"
                + "      </rdf:Description>\n"
                + "      <rdf:Description rdf:about=\"\"\n"
                + "            xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
                + "         <pdf:Producer>Acrobat Distiller 8.1.0 (Windows)</pdf:Producer>\n"
                + "      </rdf:Description>\n"
                + "      <rdf:Description rdf:about=\"\"\n"
                + "            xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
                + "         <dc:format>application/pdf</dc:format>\n"
                + "         <dc:creator>\n"
                + "            <rdf:Seq>\n"
                + "               <rdf:li>R002325</rdf:li>\n"
                + "            </rdf:Seq>\n"
                + "         </dc:creator>\n"
                + "         <dc:subject>\n"
                + "            <rdf:Bag>\n"
                + "               <rdf:li>one</rdf:li>\n"
                + "               <rdf:li>two</rdf:li>\n"
                + "               <rdf:li>three</rdf:li>\n"
                + "               <rdf:li>four</rdf:li>\n"
                + "            </rdf:Bag>\n"
                + "         </dc:subject>\n"
                + "         <dc:title>\n"
                + "            <rdf:Alt>\n"
                + "               <rdf:li xml:lang=\"x-default\"> </rdf:li>\n"
                + "            </rdf:Alt>\n"
                + "         </dc:title>\n"
                + "      </rdf:Description>\n"
                + "      <rdf:Description rdf:about=\"\"\n"
                + "            xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
                + "         <xapMM:DocumentID>uuid:31ae92cf-9a27-45e0-9371-0d2741e25919</xapMM:DocumentID>\n"
                + "         <xapMM:InstanceID>uuid:2c7eb5da-9210-4666-8cef-e02ef6631c5e</xapMM:InstanceID>\n"
                + "      </rdf:Description>\n"
                + "   </rdf:RDF>\n"
                + "</x:xmpmeta>\n"
                + "<?xpacket end=\"w\"?>";
        DomXmpParser xmpParser = new DomXmpParser();
        xmpParser.setStrictParsing(false);
        //IOUtils.copy(meta.createInputStream(),System.out);
        XMPMetadata xmp = xmpParser.parse(xmpmeta.getBytes());
        XMPBasicSchema basicSchema = xmp.getXMPBasicSchema();
        Calendar createDate1 = basicSchema.getCreateDate();
        basicSchema.setCreateDate(new GregorianCalendar());
        Calendar createDate2 = basicSchema.getCreateDate();
        Assert.assertFalse("CreateDate has not been set", createDate1.equals(createDate2));

        // check that bugfix does not interfere with lists of properties with same name
        DublinCoreSchema dublinCoreSchema = xmp.getDublinCoreSchema();
        List<String> subjects = dublinCoreSchema.getSubjects();
        Assert.assertEquals(4, subjects.size());
    }

}


text:
/*jshint white:false, camelcase:false */
define([
    'require',
    'config',
    'router',
    'message', //tells the router how to connect workers
    'loader',
    'request',
    'tabs',
    'extension_storage',
    'observer',
    'clipboard'
], function ( require ) {

    console.log('hello inside browser module')

    var config            = require('config'),
        message           = require('message'),
        router            = require('router'),
        loader            = require('loader'),
        request           = require('request'),
        tabs              = require('tabs'), //self-inits
        extension_storage = require('extension_storage'),
        clipboard         = require('clipboard');

    var get_core = function () {
            return {
                router:             router,
                request:            request,
                loader:             loader,
                extension_storage:  extension_storage
            };
        },

        is_ready = false,

        ready_listeners = [],

        ready = function ( cb ) {
            ready_listeners.push( cb );
            if ( is_ready ) {
                call_ready();
            }
        },

        call_ready = function () {
            while ( ready_listeners.length ) {
                var cb = ready_listeners.shift();
                cb( get_core() );
            }
        },

        init = function () {
            //optionally change the request spacing
            request.init({
                spacing: 100
            });

            loader.init({
                //router: router
            });

            is_ready = true;

            call_ready();
        };

    //console.log('hello browser', config, get_core() );

    init();

    /* Browser delegate model the actual low-level browser operations that
     * differ from each other. The following interfaces need to be defined
     * for a delegate object:
     *      init(config): intiialization
     *      storage: storage interfaces
     *      requests: ajax request interfaces
     *      message: inter-component messaging interfaces
     */

    return {
        ready: ready,
        get_core: get_core
    };
});


text:
require 'chefspec'
require 'chefspec/berkshelf'

describe 'pentestenv::default' do
  let(:subject) do
    ChefSpec::SoloRunner.new(step_into: %w(pentestenv_pentestrc),
                             platform: 'debian',
                             version: '9.11') do |node|
      node.override['pentestenv']['user'] = 'elliot'
      node.override['pentestenv']['install_dir'] = '/opt/pentest-env'
      node.override['pentestenv']['custom_berksfile']['cookbook'] = 'pentestenv'
      node.override['pentestenv']['custom_berksfile']['file'] = 'pentestd'
      node.override['pentestenv']['repository'] = 'https://another/repository.git'
      node.override['pentestenv']['reference'] = 'custom'
      node.override['pentestenv']['resources'] = {
        '/root/.pentestrc' => {
          instances_path: '~/.pentest.d/instances',
          instances: ['kali'],
          targets: ['metasploitable3'],
        },
      }
    end.converge(described_recipe)
  end

  it 'syncs git[/opt/pentest-env]' do
    expect(subject).to sync_git('/opt/pentest-env')
      .with(user: 'elliot',
            group: 'root',
            repository: 'https://another/repository.git',
            reference: 'custom',
            enable_submodules: true)
  end

  it 'creates pentestenv_rc[/root/.pentestrc]' do
    expect(subject).to create_pentestenv_rc('/root/.pentestrc')
      .with(owner: 'elliot',
            group: 'root',
            cookbook: 'pentestenv',
            source: 'rc.erb',
            mode: '0644')
  end

  it 'creates cookbook_file[/opt/pentest-env/Berksfile.custom]' do
    expect(subject).to create_cookbook_file('/opt/pentest-env/Berksfile.custom')
      .with(owner: 'elliot',
            group: 'root',
            mode: '0644',
            cookbook: 'pentestenv',
            source: 'berksfiles/pentestd')
  end
end


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef WIN32
#include "condor_header_features.h"
#include "condor_sys_nt.h"
#else
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#endif
#include "write_user_log.h"
#include <sys/types.h>

struct hostent *NameEnt;
/*
**#define NUL       "\0";
*/

int writeSubmitEvent(WriteUserLog *log);
int writeExecuteEvent(WriteUserLog *log);
int writeJobTerminatedEvent(WriteUserLog *log);
/*
int writeRemoteErrorEvent();
int writeExecutableErrorEvent();
int writeCheckpointedEvent();
int writeJobAbortedEvent();
int writeJobEvictedEvent();
int writeNodeTerminatedEvent();
int writePostScriptTerminatedEvent();
int writeGlobusSubmitEvent();
int writeGlobusSubmitFailedEvent();
int writeGlobusResourceUpEvent();
int writeGlobusResourceDownEvent();
int writeJobImageSizeEvent();
int writeShadowExceptionEvent();
int writeJobSuspendedEvent();
int writeJobUnsuspendedEvent();
int writeJobHeldEvent();
int writeJobReleasedEvent();
int writeNodeExecuteEvent();
*/

int
main(int argc, char **argv)
{

	if(argc != 4) {
		printf("ussage: x_write_joblog_events log event count\n");
		exit(1);
	}

	char *logname = argv[1];
	int count = atoi(argv[3]);

	if( strcmp(argv[2],"submit") == 0) {
		//printf("Drop submit events\n");
		for(int cluster = 1;cluster <= count;cluster++) {
			WriteUserLog log("owner", NULL, logname, cluster, 0, 0, (bool)0, NULL);
			writeSubmitEvent(&log);
		}
	} else if( strcmp(argv[2],"execute") == 0) {
		//printf("Drop execute event\n");
		for(int cluster = 1;cluster <= count;cluster++) {
			WriteUserLog log("owner", NULL, logname, cluster, 0, 0, (bool)0, NULL);
			writeExecuteEvent(&log);
		}
	} else if( strcmp(argv[2],"terminated") == 0) {
		//printf("Drop terminated event\n");
		for(int cluster = 1;cluster <= count;cluster++) {
			WriteUserLog log("owner", NULL, logname, cluster, 0, 0, (bool)0, NULL);
			writeJobTerminatedEvent(&log);
		}
	}
	/*
	***********************************
	writeSubmitEvent();
	writeRemoteErrorEvent();
	writeExecuteEvent();
	writeExecutableErrorEvent();
	writeCheckpointedEvent();
	writeJobAbortedEvent();
	writeJobEvictedEvent();
	writeJobTerminatedEvent();
	writeNodeTerminatedEvent();
	writePostScriptTerminatedEvent();
	writeGlobusSubmitEvent();
	writeGlobusSubmitFailedEvent();
	writeGlobusResourceUpEvent();
	writeGlobusResourceDownEvent();
	writeJobImageSizeEvent();
	writeShadowExceptionEvent();
	writeJobSuspendedEvent();
	writeJobUnsuspendedEvent();
	writeJobHeldEvent();
	writeJobReleasedEvent();
	writeNodeExecuteEvent();
	***********************************
	*/
	exit(0);
}

int writeSubmitEvent(WriteUserLog *log)
{
	SubmitEvent submit;
	submit.setSubmitHost("<128.105.165.12:32779>");
	submit.submitEventLogNotes = strdup("DAGMan info");
	submit.submitEventUserNotes = strdup("User info");
	if ( !log->writeEvent(&submit) ) {
		printf("Bad submit write\n");
		exit(1);
	}
	return(0);
}

int writeExecuteEvent(WriteUserLog *log)
{
	ExecuteEvent execute;
	execute.setExecuteHost("<128.105.165.12:32779>");
	if ( !log->writeEvent(&execute) ) {
		printf("Bad execute write\n");
		exit(1);
	}
	return(0);
}

int writeJobTerminatedEvent(WriteUserLog *log)
{
	struct rusage ru;

	JobTerminatedEvent jobterminated;
	jobterminated.normal = true;
	jobterminated.signalNumber = 0;
	jobterminated.returnValue = 0;
	jobterminated.run_remote_rusage = ru;
	jobterminated.total_remote_rusage = ru;
	jobterminated.recvd_bytes = 200000;
	jobterminated.sent_bytes = 400000;
	jobterminated.total_recvd_bytes = 800000;
	jobterminated.total_sent_bytes = 900000;
	if ( !log->writeEvent(&jobterminated) ) {
	        printf("Bad jobterminate write\n");
			exit(1);
	}
	return(0);
}

/*
***************************************************
int writeExecutableErrorEvent(WriteUserLog *log)
{
	ExecutableErrorEvent executeerror;
	executeerror.errType = CONDOR_EVENT_BAD_LINK;
	if ( !log->writeEvent(&executeerror) ) {
		printf("Complain about bad executeerror write\n");
		exit(1);
	}
	return(0);
}

int writeCheckpointedEvent()
{
	CheckpointedEvent checkpoint;
	if ( !log.writeEvent(&checkpoint) ) {
		printf("Complain about bad checkpoint write\n");
		exit(1);
	}
	return(0);
}

int writeRemoteErrorEvent()
{
	RemoteErrorEvent remoteerror;
	remoteerror.setExecuteHost("<128.105.165.12:32779>");
	remoteerror.setDaemonName("<write job log test>");
	remoteerror.setErrorText("this is the write test error string");
	remoteerror.setCriticalError(TRUE);
	if ( !log.writeEvent(&remoteerror) ) {
	        printf("Complain about bad remoteerror write\n");
			exit(1);
	}
	return(0);
}

int writeJobAbortedEvent()
{
	JobAbortedEvent jobabort;
	jobabort.setReason("cause I said so!");
	if ( !log.writeEvent(&jobabort) ) {
	        printf("Complain about bad jobabort write\n");
			exit(1);
	}
	return(0);
}

int writeJobEvictedEvent()
{
	JobEvictedEvent jobevicted;
	jobevicted.setReason("It misbehaved!");
	jobevicted.setCoreFile("corefile");
	if ( !log.writeEvent(&jobevicted) ) {
	        printf("Complain about bad jobevicted write\n");
			exit(1);
	}
	return(0);
}

int writeNodeTerminatedEvent()
{
	struct rusage ru;

	NodeTerminatedEvent nodeterminated;
	nodeterminated.node = 44;
	nodeterminated.normal = false;
	nodeterminated.signalNumber = 9;
	nodeterminated.returnValue = 4;
	nodeterminated.run_remote_rusage = ru;
	nodeterminated.total_remote_rusage = ru;
	nodeterminated.recvd_bytes = 200000;
	nodeterminated.sent_bytes = 400000;
	nodeterminated.total_recvd_bytes = 800000;
	nodeterminated.total_sent_bytes = 900000;
	nodeterminated.setCoreFile( "badfilecore" );
	if ( !log.writeEvent(&nodeterminated) ) {
	        printf("Complain about bad nodeterminated write\n");
			exit(1);
	}
	return(0);
}

int writePostScriptTerminatedEvent()
{
	PostScriptTerminatedEvent postscriptterminated;
	postscriptterminated.normal = false;
	postscriptterminated.signalNumber = 9;
	postscriptterminated.returnValue = 4;
	if ( !log.writeEvent(&postscriptterminated) ) {
	        printf("Complain about bad postscriptterminated write\n");
			exit(1);
	}
	return(0);
}

int writeGlobusSubmitEvent()
{
	GlobusSubmitEvent globussubmitevent;
	globussubmitevent.rmContact = strdup("ResourceManager");;
	globussubmitevent.jmContact = strdup("JobManager");;
	globussubmitevent.restartableJM = true;
	if ( !log.writeEvent(&globussubmitevent) ) {
	        printf("Complain about bad globussubmitevent write\n");
			exit(1);
	}
	return(0);
}

int writeGlobusSubmitFailedEvent()
{
	GlobusSubmitFailedEvent globussubmitfailedevent;
	globussubmitfailedevent.reason = strdup("Cause it could");;
	if ( !log.writeEvent(&globussubmitfailedevent) ) {
	        printf("Complain about bad globussubmitfailedevent write\n");
			exit(1);
	}
	return(0);
}

int writeGlobusResourceUpEvent()
{
	GlobusResourceUpEvent globusresourceupevent;
	globusresourceupevent.rmContact = strdup("ResourceUp");;
	if ( !log.writeEvent(&globusresourceupevent) ) {
	        printf("Complain about bad globusresourceupevent write\n");
			exit(1);
	}
	return(0);
}

int writeGlobusResourceDownEvent()
{
	GlobusResourceDownEvent globusresourcedownevent;
	globusresourcedownevent.rmContact = strdup("ResourceDown");;
	if ( !log.writeEvent(&globusresourcedownevent) ) {
	        printf("Complain about bad globusresourcedownevent write\n");
			exit(1);
	}
	return(0);
}

int writeJobImageSizeEvent()
{
	JobImageSizeEvent jobimagesizeevent;
	jobimagesizeevent.image_size_kb = 128;
	if ( !log.writeEvent(&jobimagesizeevent) ) {
		printf("Complain about bad jobimagesizeevent write\n");
		exit(1);
	}
	return(0);
}

int writeShadowExceptionEvent()
{
	ShadowExceptionEvent shadowexceptionevent;
	shadowexceptionevent.sent_bytes = 4096;
	shadowexceptionevent.recvd_bytes = 4096;
	shadowexceptionevent.message[0] = '\0';
	strncat(shadowexceptionevent.message,"shadow message", 15);
	if ( !log.writeEvent(&shadowexceptionevent) ) {
		printf("Complain about bad shadowexceptionevent write\n");
		exit(1);
	}
	return(0);
}

int writeJobSuspendedEvent()
{
	JobSuspendedEvent jobsuspendevent;
	jobsuspendevent.num_pids = 99;
	if ( !log.writeEvent(&jobsuspendevent) ) {
		printf("Complain about bad jobsuspendevent write\n");
		exit(1);
	}
	return(0);
}

int writeJobUnsuspendedEvent()
{
	JobUnsuspendedEvent jobunsuspendevent;
	//jobunsuspendevent.num_pids = 99;
	if ( !log.writeEvent(&jobunsuspendevent) ) {
		printf("Complain about bad jobunsuspendevent write\n");
		exit(1);
	}
	return(0);
}

int writeJobHeldEvent()
{
	JobHeldEvent jobheldevent;
	jobheldevent.setReason("CauseWeCan");
	jobheldevent.setReasonCode(404);
	jobheldevent.setReasonSubCode(0xff);
	if ( !log.writeEvent(&jobheldevent) ) {
		printf("Complain about bad jobheldevent write\n");
		exit(1);
	}
	return(0);
}

int writeJobReleasedEvent()
{
	JobReleasedEvent jobreleasedevent;
	jobreleasedevent.setReason("MessinWithYou");
	if ( !log.writeEvent(&jobreleasedevent) ) {
		printf("Complain about bad jobreleasedevent write\n");
		exit(1);
	}
	return(0);
}

int writeNodeExecuteEvent()
{
	NodeExecuteEvent nodeexecuteevent;
	nodeexecuteevent.node = 49;
	nodeexecuteevent.executeHost[0] = '\0';
	strcat(nodeexecuteevent.executeHost,"<128.105.165.12:32779>");
	if ( !log.writeEvent(&nodeexecuteevent) ) {
		printf("Complain about bad nodeexecuteevent write\n");
		exit(1);
	}
	return(0);
}
***************************************************
*/


text:
@interface EventSearchController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *allEventsBeingSearched;
@property (strong, nonatomic) NSArray *filteredEvents;
@end


text:
import time
import wpan
from wpan import verify

# -----------------------------------------------------------------------------------------------------------------------
# Test description:
#
# This test covers the situation for SED child (re)attaching to a parent with multiple IPv6 addresses present on the
# child.
#
# Network topology
#
#   leader ---- parent
#                 |
#                 |
#              child (sleepy)
#

test_name = __file__[:-3] if __file__.endswith('.py') else __file__
print('-' * 120)
print('Starting \'{}\''.format(test_name))

# -----------------------------------------------------------------------------------------------------------------------
# Utility functions

def verify_address(node_list, prefix):
    """
    This function verifies that all nodes in the `node_list` contain an IPv6 address with the given `prefix`.
    """
    for node in node_list:
        all_addrs = wpan.parse_list(node.get(wpan.WPAN_IP6_ALL_ADDRESSES))
        verify(any([addr.startswith(prefix[:-1]) for addr in all_addrs]))

# -----------------------------------------------------------------------------------------------------------------------
# Creating `wpan.Nodes` instances

speedup = 4
wpan.Node.set_time_speedup_factor(speedup)

leader = wpan.Node()
parent = wpan.Node()
child = wpan.Node()

# -----------------------------------------------------------------------------------------------------------------------
# Init all nodes

wpan.Node.init_all_nodes()

# -----------------------------------------------------------------------------------------------------------------------
# Build network topology

leader.form('multi-addr-test')

leader.whitelist_node(parent)
parent.whitelist_node(leader)
parent.join_node(leader, wpan.JOIN_TYPE_ROUTER)

parent.whitelist_node(child)
child.whitelist_node(parent)

child.join_node(parent, node_type=wpan.JOIN_TYPE_SLEEPY_END_DEVICE)
child.set(wpan.WPAN_POLL_INTERVAL, '400')

# -----------------------------------------------------------------------------------------------------------------------
# Test implementation

WAIT_TIME = 5
CHILD_SUPERVISION_CHECK_TIMEOUT = 1

prefix1 = 'fd00:1::'
prefix2 = 'fd00:2::'
prefix3 = 'fd00:3::'
prefix4 = 'fd00:4::'

# Add 4 prefixes (all with SLAAC bit set).
leader.add_prefix(prefix1, on_mesh=True, slaac=True, configure=True)
leader.add_prefix(prefix2, on_mesh=True, slaac=True, configure=True)
leader.add_prefix(prefix3, on_mesh=True, slaac=True, configure=True)
leader.add_prefix(prefix4, on_mesh=True, slaac=True, configure=True)

# Verify that the sleepy child gets all 4 SLAAC addresses.

def check_addresses_on_child():
    verify_address([child], prefix1)
    verify_address([child], prefix2)
    verify_address([child], prefix3)
    verify_address([child], prefix4)

wpan.verify_within(check_addresses_on_child, WAIT_TIME)

# Remove child from parent's white-list
parent.remove(
    wpan.WPAN_MAC_WHITELIST_ENTRIES, child.get(wpan.WPAN_EXT_ADDRESS)[1:-1]
)

# Enable supervision check on child, this ensures that child is detached soon.
child.set(
    wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT,
    str(CHILD_SUPERVISION_CHECK_TIMEOUT),
)

# Wait for child to get detached.

def check_child_is_detached():
    verify(not child.is_associated())

wpan.verify_within(check_child_is_detached, WAIT_TIME)

# Now reset parent and wait for it to be associated.
parent.reset()

def check_parent_is_associated():
    verify(parent.is_associated())

wpan.verify_within(check_parent_is_associated, WAIT_TIME)

# Now verify that child is indeed getting attached back.

def check_child_is_associated():
    verify(child.is_associated())

wpan.verify_within(check_child_is_associated, WAIT_TIME)

# Any finally check that we see all the child addresses in the parent's
# child table.

def check_child_addressses_on_parent():
    child_addrs = parent.get(wpan.WPAN_THREAD_CHILD_TABLE_ADDRESSES)
    verify(child_addrs.find(prefix1) > 0)
    verify(child_addrs.find(prefix2) > 0)
    verify(child_addrs.find(prefix3) > 0)
    verify(child_addrs.find(prefix4) > 0)

wpan.verify_within(check_child_addressses_on_parent, WAIT_TIME)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Check the child recovery after a parent reset using quick re-attach
# ("Child Update" exchange).

# Disable supervision check on the child.
child.set(wpan.WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT, '1000')
child.set(wpan.WPAN_POLL_INTERVAL, '10000')
time.sleep(0.1)

# We use the "stat:ncp" wpantund property to verify that child does not
# get detached.
child_num_state_changes = len(wpan.parse_list(child.get("stat:ncp")))

# Reset parent and wait for it to be associated.
parent.reset()
wpan.verify_within(check_parent_is_associated, WAIT_TIME)

child.set(wpan.WPAN_POLL_INTERVAL, '100')

# Verify that we again see all the child addresses in the parent's child table.
# Note that child should register its addresses using "Child Update
# Request" exchange.
wpan.verify_within(check_child_addressses_on_parent, WAIT_TIME)

# Verify that there was no state change on child.
verify(child_num_state_changes == len(wpan.parse_list(child.get("stat:ncp"))))

# -----------------------------------------------------------------------------------------------------------------------
# Test finished

wpan.Node.finalize_all_nodes()

print('\'{}\' passed.'.format(test_name))


text:
package libcore.javax.crypto;

import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherSpi;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;

/**
 * Mock CipherSpi used by {@link CipherTest}.
 */
public class MockCipherSpi extends CipherSpi {
    public static class SpecificKeyTypes extends MockCipherSpi {
        @Override
        public void checkKeyType(Key key) throws InvalidKeyException {
            if (!(key instanceof MockKey)) {
                throw new InvalidKeyException("Must be MockKey!");
            }
        }
    }

    public static class SpecificKeyTypes2 extends MockCipherSpi {
        @Override
        public void checkKeyType(Key key) throws InvalidKeyException {
            System.err.println("Checking key of type " + key.getClass().getName());
            if (!(key instanceof MockKey2)) {
                throw new InvalidKeyException("Must be MockKey2!");
            }
        }
    }

    public static class SpecificAlgorithmParameterSpecTypes extends MockCipherSpi {
        @Override
        public void checkAlgorithmParameterSpec(AlgorithmParameterSpec aps)
                throws InvalidAlgorithmParameterException {
            if (!(aps instanceof MockAlgorithmParameterSpec)) {
                throw new InvalidAlgorithmParameterException("Must be "
                        + MockAlgorithmParameterSpec.class.getName());
            }
        }
    }

    public static class SpecificAlgorithmParameterSpecTypes2 extends MockCipherSpi {
        @Override
        public void checkAlgorithmParameterSpec(AlgorithmParameterSpec aps)
                throws InvalidAlgorithmParameterException {
            if (!(aps instanceof MockAlgorithmParameterSpec2)) {
                throw new InvalidAlgorithmParameterException("Must be "
                        + MockAlgorithmParameterSpec2.class.getName());
            }
        }
    }

    public static class SpecificAlgorithmParameterAesAlgorithm extends MockCipherSpi {
        @Override
        public void checkAlgorithmParameters(AlgorithmParameters ap)
                throws InvalidAlgorithmParameterException {
            if (!ap.getAlgorithm().equals("AES")) {
                throw new InvalidAlgorithmParameterException("Must be AES");
            }
        }
    }

    public static class SpecificAlgorithmParametersDesAlgorithm extends MockCipherSpi {
        @Override
        public void checkAlgorithmParameters(AlgorithmParameters ap)
                throws InvalidAlgorithmParameterException {
            if ((!ap.getAlgorithm().equals("DES"))) {
                throw new InvalidAlgorithmParameterException("Must be DES");
            }
        }
    }

    public static class AllKeyTypes extends MockCipherSpi {
    }

    public static class MustInitWithAlgorithmParameterSpec_RejectsAll extends MockCipherSpi {
        @Override
        protected void engineInit(int opmode, Key key, SecureRandom random)
                throws InvalidKeyException {
            throw new AssertionError("Must have AlgorithmParameterSpec");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new InvalidAlgorithmParameterException("expected rejection");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameters params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new AssertionError("Must have AlgorithmParameterSpec");
        }
    }

    public static class MustInitWithAlgorithmParameters_RejectsAll extends MockCipherSpi {
        @Override
        protected void engineInit(int opmode, Key key, SecureRandom random)
                throws InvalidKeyException {
            throw new AssertionError("Must have AlgorithmParameterSpec");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new AssertionError("Must have AlgorithmParameterSpec");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameters params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new InvalidAlgorithmParameterException("expected rejection");
        }
    }

    public static class MustInitWithAlgorithmParameters_ThrowsNull extends MockCipherSpi {
        @Override
        protected void engineInit(int opmode, Key key, SecureRandom random)
                throws InvalidKeyException {
            throw new NullPointerException("expected rejection");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new NullPointerException("expected rejection");
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameters params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            throw new NullPointerException("expected rejection");
        }
    }

    public static class MustInitForEncryptModeOrRejects extends MockCipherSpi {
        @Override
        protected void engineInit(int opmode, Key key, SecureRandom random)
                throws InvalidKeyException {
            if (opmode != Cipher.ENCRYPT_MODE) {
                throw new InvalidKeyException("expected rejection");
            }
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            if (opmode != Cipher.ENCRYPT_MODE) {
                throw new InvalidKeyException("expected rejection");
            }
        }

        @Override
        protected void engineInit(int opmode, Key key, AlgorithmParameters params,
                SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
            if (opmode != Cipher.ENCRYPT_MODE) {
                throw new InvalidKeyException("expected rejection");
            }
        }
    }

    public void checkKeyType(Key key) throws InvalidKeyException {
    }

    public void checkAlgorithmParameterSpec(AlgorithmParameterSpec aps)
            throws InvalidAlgorithmParameterException {
    }

    public void checkAlgorithmParameters(AlgorithmParameters ap)
            throws InvalidAlgorithmParameterException {
    }

    @Override
    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
        if (!"FOO".equals(mode)) {
            throw new UnsupportedOperationException("not implemented");
        }
    }

    @Override
    protected void engineSetPadding(String padding) throws NoSuchPaddingException {
        if (!"FOO".equals(padding)) {
            throw new UnsupportedOperationException("not implemented");
        }
    }

    @Override
    protected int engineGetBlockSize() {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected int engineGetOutputSize(int inputLen) {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected byte[] engineGetIV() {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected AlgorithmParameters engineGetParameters() {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
        checkKeyType(key);
    }

    @Override
    protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
            SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
        checkKeyType(key);
        checkAlgorithmParameterSpec(params);
    }

    @Override
    protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        checkKeyType(key);
        checkAlgorithmParameters(params);
    }

    @Override
    protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output,
            int outputOffset) throws ShortBufferException {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
            throws IllegalBlockSizeException, BadPaddingException {
        throw new UnsupportedOperationException("not implemented");
    }

    @Override
    protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
            int outputOffset) throws ShortBufferException, IllegalBlockSizeException,
            BadPaddingException {
        throw new UnsupportedOperationException("not implemented");
    }

    public static class MockAlgorithmParameterSpec implements AlgorithmParameterSpec {
    }

    public static class MockAlgorithmParameterSpec2 implements AlgorithmParameterSpec {
    }
}


text:
using System;
using System.IO;
using System.Linq;
using System.Text;
using Registry.Other;
using Serilog;
using static Registry.Other.Helpers;

namespace Registry;

public class RegistryBase : IRegistry
{
    public RegistryBase()
    {
        throw new NotSupportedException("Call the other constructor and pass in the path to the Registry hive!");
    }

    public RegistryBase(byte[] rawBytes, string hivePath)
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        FileBytes = rawBytes;
        HivePath = "None";

        if (!HasValidSignature())
        {
            Log.Error("Data in byte array is not a Registry hive (bad signature)");

            throw new ArgumentException("Data in byte array is not a Registry hive (bad signature)");
        }

        HivePath = hivePath;

        Initialize();
    }

    public RegistryBase(string hivePath)
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        if (hivePath == null) throw new ArgumentNullException("hivePath cannot be null");

        if (!File.Exists(hivePath))
        {
            var fullPath = Path.GetFullPath(hivePath);
            throw new FileNotFoundException($"The specified file {fullPath} was not found.", fullPath);
        }

        var fileStream = new FileStream(hivePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        var binaryReader = new BinaryReader(fileStream);

        binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);

        FileBytes = binaryReader.ReadBytes((int) binaryReader.BaseStream.Length);

        binaryReader.Close();
        fileStream.Close();

        if (!HasValidSignature())
        {
            Log.Error("{HivePath} is not a Registry hive (bad signature)", hivePath);

            throw new Exception($"{hivePath} is not a Registry hive (bad signature)");
        }

        HivePath = hivePath;

        //    Logger.Trace("Set HivePath to {0}", hivePath);

        Initialize();
    }

    public long TotalBytesRead { get; internal set; }
    public string Version { get; private set; }

    public byte[] FileBytes { get; internal set; }

    public HiveTypeEnum HiveType { get; private set; }

    public string HivePath { get; }

    public RegistryHeader Header { get; set; }

    public byte[] ReadBytesFromHive(long offset, int length)
    {
        var readLength = Math.Abs(length);

        var remaining = FileBytes.Length - offset;

        if (remaining <= 0) return new byte[0];

        if (readLength > remaining) readLength = (int) remaining;

        var r = new ArraySegment<byte>(FileBytes, (int) offset, readLength);

        return r.ToArray();
    }

    internal void Initialize()
    {
        var header = ReadBytesFromHive(0, 4096);

        //    Logger.Trace("Getting header");

        Header = new RegistryHeader(header);

        var fileNameSegs = Header.FileName.Split('\\');

        var fNameBase = fileNameSegs.Last().ToLowerInvariant();

        Log.Debug("Got hive header. Embedded file name {FileName}. Base Name {Base}", Header.FileName,fNameBase);

        switch (fNameBase)
        {
            case "ntuser.dat":
                HiveType = HiveTypeEnum.NtUser;
                break;
            case "sam":
                HiveType = HiveTypeEnum.Sam;
                break;
            case "security":
                HiveType = HiveTypeEnum.Security;
                break;
            case "software":
                HiveType = HiveTypeEnum.Software;
                break;
            case "system":
                HiveType = HiveTypeEnum.System;
                break;
            case "drivers":
                HiveType = HiveTypeEnum.Drivers;
                break;
            case "usrclass.dat":
                HiveType = HiveTypeEnum.UsrClass;
                break;
            case "components":
                HiveType = HiveTypeEnum.Components;
                break;
            case "bcd":
                HiveType = HiveTypeEnum.Bcd;
                break;
            case "amcache.hve":
            case "amcache.hve.tmp":
                HiveType = HiveTypeEnum.Amcache;
                break;
            case "syscache.hve":
                HiveType = HiveTypeEnum.Syscache;
                break;
            default:
                HiveType = HiveTypeEnum.Other;
                break;
        }

        //    Logger.Trace("Hive is a {0} hive", HiveType);

        Version = $"{Header.MajorVersion}.{Header.MinorVersion}";

        //   Logger.Trace("Hive version is {0}", version);
    }

    public bool HasValidSignature()
    {
        var sig = BitConverter.ToInt32(FileBytes, 0);

        return sig.Equals(RegfSignature);
    }
}


text:
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:

### Template For Submitting Bug Reports

    [Short description of problem here]

    **Reproduction Steps:**

    1. [First Step]
    2. [Second Step]
    3. [Other Steps...]

    **Screenshots and GIFs**

    ![Screenshots and GIFs which follow reproduction steps to demonstrate the problem](url)

    **Additional information:**

### Git Commit Messages

* Use the present tense ("Add feature" not "Added feature")
* Reference issues and pull requests liberally
* Consider starting the commit message with an applicable emoji:
    * :art: `:art:` when improving the format/structure of the code
    * :memo: `:memo:` when writing docs
    * :penguin: `:penguin:` when fixing something on Linux
    * :apple: `:apple:` when fixing something on Mac OS
    * :checkered_flag: `:checkered_flag:` when fixing something on Windows
    * :bug: `:bug:` when fixing a bug
    * :fire: `:fire:` when removing code or files


text:
include_recipe 'apt::default'

package 'git'

%w(
  user::default
  valhalla::setup
  valhalla::install_from_source
).each do |r|
  include_recipe r
end


text: require 'acts_as_has_default'


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. Pilze (Würzburg) 72 (1816)

#### Original name
Alternaria Nees

### Remarks
null


text:
package org.apache.nifi.processors.azure.storage;

import org.apache.nifi.processor.Processor;
import org.apache.nifi.util.MockFlowFile;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;

public class ITListAzureBlobStorage extends AbstractAzureBlobStorageIT {

    @Override
    protected Class<? extends Processor> getProcessorClass() {
        return ListAzureBlobStorage.class;
    }

    @Before
    public void setUp() throws Exception {
        uploadTestBlob();

        Thread.sleep(ListAzureBlobStorage.LISTING_LAG_MILLIS.get(TimeUnit.SECONDS) * 2);
    }

    @Test
    public void testListBlobs() throws Exception {
        runner.assertValid();
        runner.run(1);

        assertResult();
    }

    @Test
    public void testListBlobsUsingCredentialService() throws Exception {
        configureCredentialsService();

        runner.assertValid();
        runner.run(1);

        assertResult();
    }

    private void assertResult() {
        runner.assertTransferCount(ListAzureBlobStorage.REL_SUCCESS, 1);
        runner.assertAllFlowFilesTransferred(ListAzureBlobStorage.REL_SUCCESS, 1);

        for (MockFlowFile entry : runner.getFlowFilesForRelationship(ListAzureBlobStorage.REL_SUCCESS)) {
            entry.assertAttributeEquals("azure.length", "36");
            entry.assertAttributeEquals("mime.type", "application/octet-stream");
        }
    }
}


text:
TestHelpers.commonWidgetTests( "sortable", {
	defaults: {
		appendTo: "parent",
		axis: false,
		cancel: "input,textarea,button,select,option",
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		delay: 0,
		disabled: false,
		distance: 1,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000
	}
});


text:
using System.Collections.Immutable;
using System.IO;

namespace Kaleidoscope
{
	public class SourceTextFile
	{
		ImmutableArray<ushort> m_lineNumbers;
		ImmutableArray<int> m_lineStartIndex;

		public readonly string FilePath;
		public readonly string FileName;
		public readonly string FileContent;

		public char this[int index] => FileContent[index];
		public int Length => FileContent.Length;

		public SourceTextFile(string filePath, string fileContent)
		{
			FilePath = filePath;
			FileName = Path.GetFileName(filePath);
			FileContent = fileContent;

			//Calculate line number for each character, and each line's start index
			var lineNumbers = ImmutableArray.CreateBuilder<ushort>(FileContent.Length + 1);
			var lineStartIndex = ImmutableArray.CreateBuilder<int>(64);
			lineStartIndex.Add(0);
			ushort currentLine = 1;
			for (int cnt = 0; cnt < FileContent.Length; ++cnt) {
				lineNumbers.Add(currentLine);
				if (FileContent[cnt] == '\n') {
					++currentLine;
					lineStartIndex.Add(cnt + 1);
				}
			}
			lineNumbers.Add(currentLine);
			lineStartIndex.Add(FileContent.Length);
			lineStartIndex.Capacity = lineStartIndex.Count;

			m_lineNumbers = lineNumbers.MoveToImmutable();
			m_lineStartIndex = lineStartIndex.MoveToImmutable();
		}

		public override string ToString()
		{
			return "[SourceTextFile] " + FilePath;
		}

		public int GetLine(int index)
		{
			return m_lineNumbers[index];
		}

		public void GetLineColumn(int index, out int line, out int column)
		{
			line = m_lineNumbers[index];
			column = index - m_lineStartIndex[line - 1];
		}

		public string Substring(int startIndex, int endIndex)
		{
			return FileContent.Substring(startIndex, endIndex - startIndex);
		}
	}
}


text:
namespace media {

// Class to encapsulate a random number generator with an implementation for
// tests that provides repeatable, platform-independent sequences.
class COMPONENT_EXPORT(LEARNING_IMPL) RandomNumberGenerator {
 public:
  RandomNumberGenerator() = default;
  virtual ~RandomNumberGenerator() = default;

  // Return a random generator that will return unpredictable values in the
  // //base/rand_util.h sense.  See TestRandomGenerator if you'd like one that's
  // more predictable for tests.
  static RandomNumberGenerator* Default();

  // Taken from rand_util.h
  // Returns a random number in range [0, UINT64_MAX]. Thread-safe.
  virtual uint64_t Generate() = 0;

  // Returns a random number in range [0, range).  Thread-safe.
  uint64_t Generate(uint64_t range);

  // Returns a floating point number in the range [0, range).  Thread-safe.
  // This isn't an overload of Generate() to be sure that one isn't surprised by
  // the result.
  double GenerateDouble(double range);

 private:
  DISALLOW_COPY_AND_ASSIGN(RandomNumberGenerator);
};

// Handy mix-in class if you want to support rng injection.
class COMPONENT_EXPORT(LEARNING_IMPL) HasRandomNumberGenerator {
 public:
  // If |rng| is null, then we'll create a new one as a convenience.
  explicit HasRandomNumberGenerator(RandomNumberGenerator* rng = nullptr);
  ~HasRandomNumberGenerator();

  void SetRandomNumberGeneratorForTesting(RandomNumberGenerator* rng);

 protected:
  RandomNumberGenerator* rng() const { return rng_; }

 private:
  RandomNumberGenerator* rng_ = nullptr;
};

}  // namespace media

#endif  // MEDIA_LEARNING_IMPL_RANDOM_NUMBER_GENERATOR_H_


text:
/*jshint node:true*/
'use strict';

var grunt = require('grunt'),
  normalize = grunt.util.normalizelf;

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.component = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },
  'default': function(test) {
    test.expect(2);

    var actual,
      expected;

    actual = normalize(grunt.file.read('tmp/default.js'));
    expected = normalize(grunt.file.read('test/expected/default.js'));

    test.equal(actual, expected, 'no options');

    actual = normalize(grunt.file.read('tmp/default-dev.js'));
    expected = normalize(grunt.file.read('test/expected/default-dev.js'));

    test.equal(actual, expected, 'with --dev');

    test.done();
  },
  dependency: function(test) {
    test.expect(1);

    var actual,
      expected;

    actual = normalize(grunt.file.read('tmp/dependency.js'));
    expected = normalize(grunt.file.read('test/expected/dependency.js'));

    test.equal(actual, expected, 'no options');

    test.done();
  }
};


text:
namespace Ui {
class UIFloat3;
}

class UIFloat3 : public QWidget
{
	Q_OBJECT

public:
	explicit UIFloat3(std::string const & label, float x, float y, float z, QWidget *parent = 0);
	~UIFloat3();

//    inline float x() const { return m_x; }
//    inline float y() const { return m_y; }
//    inline float z() const { return m_z; }

	// return true if the value is modified by Inspector
	bool CheckUpdate(std::string const & label, float & x, float & y, float & z);

private Q_SLOTS:
	inline void setX(float v) { m_x = v; m_changed = true; }
	inline void setY(float v) { m_y = v; m_changed = true; }
	inline void setZ(float v) { m_z = v; m_changed = true; }

private:
	Ui::UIFloat3 *ui;

	bool        m_changed = false;

	std::string m_label;
	float       m_x;
	float       m_y;
	float       m_z;

};

#endif // UIFLOAT3_HPP


text:
import React from 'react';
import { connect } from 'react-redux';
import { translate as $t } from '../../../helpers';
import { actions } from '../../../store';

import { registerModal } from '../../ui/modal';
import ModalContent from '../../ui/modal/content';
import CancelAndSubmit from '../../ui/modal/cancel-and-submit-buttons';

export const MODAL_SLUG = 'confirm-disable-discovery-modal';

const ConfirmDisableDiscoveryModal = connect(
    null,

    dispatch => {
        return {
            handleDisable() {
                actions.setBoolSetting(dispatch, 'discovery-mode', false);
                actions.hideModal(dispatch);
            }
        };
    }
)(props => {
    const body = (
        <form id={MODAL_SLUG} onSubmit={props.handleDisable}>
            <p>{$t('client.settings.customization.confirm_disable_discovery')}</p>
        </form>
    );

    return (
        <ModalContent
            title={$t('client.settings.customization.discovery')}
            body={body}
            footer={<CancelAndSubmit formId={MODAL_SLUG} />}
        />
    );
});

registerModal(MODAL_SLUG, () => <ConfirmDisableDiscoveryModal />);


text:
import { Hitbox } from "./Hitbox"
import { V } from "./Vector"

export class Model {
  hitbox: Hitbox
  textureOrigin: V
  textureSize: V
  spriteSheet: HTMLImageElement
  spriteSheetPath: string
  isMovingSprite: boolean
  spriteBobbing: boolean

  constructor(
    hitbox: Hitbox,
    textureOrigin: V,
    textureSize: V,
    spriteSheetPath: string,
    isMovingSprite: boolean = false,
    spriteBobbing: boolean = false
  ) {
    this.hitbox = hitbox
    this.textureSize = textureSize
    this.textureOrigin = textureOrigin
    this.spriteSheetPath = spriteSheetPath
    this.isMovingSprite = isMovingSprite
    this.spriteBobbing = spriteBobbing
  }

  checkCollision(origin: V, originHitbox: V, model: Model): boolean {
    return this.hitbox.checkCollision(origin, originHitbox, model.hitbox)
  }

  preloadImage(): Promise<void>  {
    let texture = new Image()
    texture.src = this.spriteSheetPath
    this.spriteSheet = texture

    return new Promise((resolve, reject) => {
      texture.addEventListener('load', () => {
        resolve()
      })
    })
  }
}


text:
package androidx.car.app.sample.navigation.common.car;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.car.app.CarAppService;
import androidx.car.app.Session;
import androidx.car.app.SessionInfo;
import androidx.car.app.sample.navigation.common.R;
import androidx.car.app.validation.HostValidator;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

/**
 * Entry point for the templated app.
 *
 *
{@link CarAppService} is the main interface between the app and the car host. For more
 * details, see the Android for
 * Cars Library developer guide.
 */
public final class NavigationCarAppService extends CarAppService {
    /** Navigation session channel id. */
    public static final String CHANNEL_ID = "NavigationSessionChannel";

    /** The identifier for the notification displayed for the foreground service. */
    private static final int NOTIFICATION_ID = 97654321;

    /** Create a deep link URL from the given deep link action. */
    @NonNull
    public static Uri createDeepLinkUri(@NonNull String deepLinkAction) {
        return Uri.fromParts(
                NavigationSession.URI_SCHEME, NavigationSession.URI_HOST, deepLinkAction);
    }

    @SuppressWarnings("deprecation")
    @Override
    @NonNull
    public Session onCreateSession(@NonNull SessionInfo sessionInfo) {
        createNotificationChannel();

        // Turn the car app service into a foreground service in order to make sure we can use all
        // granted "while-in-use" permissions (e.g. location) in the app's process.
        // The "while-in-use" location permission is granted as long as there is a foreground
        // service running in a process in which location access takes place. Here, we set this
        // service, and not NavigationService (which runs only during navigation), as a
        // foreground service because we need location access even when not navigating. If
        // location access is needed only during navigation, we can set NavigationService as a
        // foreground service instead.
        // See https://developer.android.com/reference/com/google/android/libraries/car/app
        // /CarAppService#accessing-location for more details.
        startForeground(NOTIFICATION_ID, getNotification());
        NavigationSession session = new NavigationSession(sessionInfo);
        session.getLifecycle()
                .addObserver(
                        new DefaultLifecycleObserver() {
                            @Override
                            public void onDestroy(@NonNull LifecycleOwner owner) {
                                stopForeground(true);
                            }
                        });

        return session;
    }

    @NonNull
    @Override
    public HostValidator createHostValidator() {
        if ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
        } else {
            return new HostValidator.Builder(getApplicationContext())
                    .addAllowedHosts(androidx.car.app.R.array.hosts_allowlist_sample)
                    .build();
        }
    }

    private void createNotificationChannel() {
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Car App Service";
            NotificationChannel serviceChannel =
                    new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(serviceChannel);
        }
    }

    /** Returns the {@link NotificationCompat} used as part of the foreground service. */
    private Notification getNotification() {
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("Navigation App")
                        .setContentText("App is running")
                        .setSmallIcon(R.drawable.ic_launcher);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
            builder.setPriority(NotificationManager.IMPORTANCE_HIGH);
        }
        return builder.build();
    }
}


text:
using OfficeOpenXml;
using System.Collections.Generic;
using wwwplatform.Models;
using OfficeOpenXml.Style;

namespace wwwplatform.Extensions.Export
{
    public static class ExcelExtensions
    {
        public static void Export(this IEnumerable<MailingListSubscriber> subscribers, ExcelWorksheet worksheet)
        {
            worksheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
            worksheet.Row(1).Style.Fill.BackgroundColor.SetColor(0xFF, 0x44, 0x72, 0xC4);
            worksheet.Row(1).Style.Font.Color.SetColor(0xFF, 0xFF, 0xFF, 0xFF);
            var col = 1;
            var row = 1;
            worksheet.Cells[row, col++].Value = "FirstName";
            worksheet.Cells[row, col++].Value = "LastName";
            worksheet.Cells[row, col++].Value = "Email";
            worksheet.Cells[row, col++].Value = "Verified";
            foreach (var subscriber in subscribers)
            {
                col = 1;
                row++;
                worksheet.Cells[row, col++].Value = subscriber.FirstName;
                worksheet.Cells[row, col++].Value = subscriber.LastName;
                worksheet.Cells[row, col++].Value = subscriber.Email;
                worksheet.Cells[row, col++].Value = subscriber.Enabled ? "Yes" : "No";
            }
            worksheet.Cells[1, 1, row, col].AutoFitColumns();
        }
    }
}


text:
(function() {

  /**
   * A lightweight class used to store coordinates on the 2-dimensional
   * Cartesian plane. It is distinct from {@link Point}, which is a subclass of
   * {@link Geometry}. Unlike objects of type {@link Point} (which contain
   * additional information such as an envelope, a precision model, and spatial
   * reference system information), a Coordinate only contains
   * coordinate values and accessor methods.
   *
   * @requires jsts/geom/Geometry.js
   */

  /**
   * @constructor
   */
  jsts.geom.Coordinate = function(x, y) {
    if (typeof x === 'number') {
      this.x = x;
      this.y = y;
    } else if (x instanceof jsts.geom.Coordinate) {
      this.x = parseFloat(x.x);
      this.y = parseFloat(x.y);
    } else if (x === undefined || x === null) {
      this.x = 0;
      this.y = 0;
    } else if (typeof x === 'string') {
      this.x = parseFloat(x);
      this.y = parseFloat(y);
    }
  };

  /**
   * Sets this Coordinates (x,y,z) values to that of
   * other.
   *
   * @param {Coordinate}
   *          other the Coordinate to copy.
   */
  jsts.geom.Coordinate.prototype.setCoordinate = function(other) {
    this.x = other.x;
    this.y = other.y;
  };

  /**
   * Clones this instance.
   *
   * @return {Coordinate} A point instance cloned from this.
   */
  jsts.geom.Coordinate.prototype.clone = function() {
    return new jsts.geom.Coordinate(this.x, this.y);
  };

  /**
   * Computes the 2-dimensional Euclidean distance to another location. The
   * Z-ordinate is ignored.
   *
   * @param {Coordinate}
   *          p a point.
   * @return {number} the 2-dimensional Euclidean distance between the
   *         locations.
   */
  jsts.geom.Coordinate.prototype.distance = function(p) {
    var dx = this.x - p.x;
    var dy = this.y - p.y;

    return Math.sqrt(dx * dx + dy * dy);
  };

  /**
   * Returns whether the planar projections of the two Coordinates
   * are equal.
   *
   * @param {Coordinate}
   *          other a Coordinate with which to do the 2D
   *          comparison.
   * @return {boolean} true if the x- and y-coordinates are
   *         equal; the z-coordinates do not have to be equal.
   */
  jsts.geom.Coordinate.prototype.equals2D = function(other) {
    if (this.x !== other.x) {
      return false;
    }

    if (this.y !== other.y) {
      return false;
    }

    return true;
  };

  /**
   * Returns true if other has the same values for
   * the x and y ordinates. Since Coordinates are 2.5D, this routine ignores the
   * z value when making the comparison.
   *
   * @param {Coordinate}
   *          other a Coordinate with which to do the comparison.
   * @return {boolean} true if other is a
   *         Coordinate with the same values for the x and y
   *         ordinates.
   */
  jsts.geom.Coordinate.prototype.equals = function(other) {
    if (!other instanceof jsts.geom.Coordinate || other === undefined) {
      return false;
    }
    return this.equals2D(other);
  };

  /**
   * Compares this {@link Coordinate} with the specified {@link Coordinate} for
   * order. This method ignores the z value when making the comparison. Returns:
   *

   *
 -1 : this.x < other.x || ((this.x == other.x) && (this.y < other.y))
   *
 0 : this.x == other.x && this.y = other.y
   *
 1 : this.x > other.x || ((this.x == other.x) && (this.y > other.y))
   *
   *

   * Note: This method assumes that ordinate values are valid numbers. NaN
   * values are not handled correctly.
   *
   * @param {Coordinate}
   *          other the Coordinate with which this
   *          Coordinate is being compared.
   * @return {number} -1, zero, or 1 as explained above.
   */
  jsts.geom.Coordinate.prototype.compareTo = function(other) {
    if (this.x < other.x) {
      return -1;
    }
    if (this.x > other.x) {
      return 1;
    }
    if (this.y < other.y) {
      return -1;
    }
    if (this.y > other.y) {
      return 1;
    }

    return 0;
  };

  jsts.geom.Coordinate.prototype.toString = function() {
    return '(' + this.x + ', ' + this.y + ')';
  };

})();


text:
package ca.jeffrey.watcard;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import java.io.Serializable;
import java.text.NumberFormat;
import java.util.Locale;

public class WatTransaction implements Serializable {

    // Date format to be passed in URL
    protected static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy/MM/dd+HH:mm:ss");
    // Base transactions URL
    protected static final String BASE_URL = "https://watcard.uwaterloo.ca/OneWeb/Financial/TransactionsPass";

    // Fields
    private LocalDateTime dateTime;
    private float amount;
    private int account;
    private WatBalanceType balanceType;
    private int unit;
    private String type;
    private String terminal;

    /**
     * Constructor
     *
     * @param dateTime a LocalDateTime instance
     * @param amount transaction amount
     * @param account account used to make transaction
     * @param unit unit
     * @param type type of transaction
     * @param terminal location of transaction
     */
    public WatTransaction(LocalDateTime dateTime, float amount, int account, int unit, String type, String terminal) {
        this.dateTime = dateTime;
        this.amount = amount;
        this.account = account;
        this.unit = unit;
        this.type = type;
        this.terminal = terminal;
        balanceType = determineBalanceType();
    }

    /**
     * Determines from what balance account funds were deducted from
     * @return WatBalanceType enum
     */
    private WatBalanceType determineBalanceType() {
        switch (account) {
            case 1:
                return WatBalanceType.VILLAGE_MEAL;
            case 2:
                return WatBalanceType.BEST_BUY_MEAL;
            case 3:
                return WatBalanceType.FOOD_PLAN;
            case 4:
                return WatBalanceType.FLEX1;
            case 5:
                return WatBalanceType.FLEX2;
            case 6:
                return WatBalanceType.FLEX3;
            case 7:
                return WatBalanceType.TRANSFER;
            case 8:
                return WatBalanceType.DON_MEAL;
            case 9:
                return WatBalanceType.DON_FLEX;
            case 10:
                return WatBalanceType.REWARDS;
            case 11:
                return WatBalanceType.DEPT_CHARGE;
            case 12:
                return WatBalanceType.OVERDRAFT;
            default:
                return WatBalanceType.OTHER;
        }
    }

    @Override
    public String toString() {
        return String.format(Locale.CANADA, "Date: %s%nAmount: $%.2f%nAccount: %s%nUnit: %d%nType: %s%nTerminal: %s",
                dateTime.toString(), amount, account, unit, type, terminal);
    }

    // Getters and setters
    public LocalDateTime getDateTime() {
        return dateTime;
    }

    // Formatted time
    public String getTimeString() {
        DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd MMM 'at' h:mm a");
        return myFormat.format(dateTime);
    }

    private boolean isFlex() {
        return balanceType == WatBalanceType.FLEX1 || balanceType == WatBalanceType.FLEX2
                || balanceType == WatBalanceType.FLEX3;
    }

    private boolean isMeal() {
        return balanceType == WatBalanceType.VILLAGE_MEAL
                || balanceType == WatBalanceType.BEST_BUY_MEAL
                || balanceType == WatBalanceType.FOOD_PLAN
                || balanceType == WatBalanceType.DON_MEAL;
    }

    public String getAccountTypeString() {
        if (isFlex()) {
            return "Flex Dollars";
        }
        else if (isMeal()) {
            return "Meal Plan";
        }
        else {
            return "Other";
        }
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }

    public float getAmount() {
        return amount;
    }

    public String getAmountString() {
        return NumberFormat.getCurrencyInstance(Locale.CANADA).format(amount);
    }

    public void setAmount(float amount) {
        this.amount = amount;
    }

    public int getAccount() {
        return account;
    }

    public void setAccount(int account) {
        this.account = account;
    }

    public int getUnit() {
        return unit;
    }

    public void setUnit(int unit) {
        this.unit = unit;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTerminal() {
        return terminal;
    }

    public String getCleanTerminal() {
        return terminal.replace("WAT-FS-", "").split(" : ")[1];
    }

    public void setTerminal(String terminal) {
        this.terminal = terminal;
    }
}


text:
"""create jenkins_job_groups table

Revision ID: 73c55823bd16
Revises: 987bb2a53069
Create Date: 2017-08-04 14:25:17.525066

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '73c55823bd16'
down_revision = '987bb2a53069'
branch_labels = None
depends_on = None

def upgrade():
    op.create_table( 'jenkins_groups',
        sa.Column('id', sa.Integer, primary_key=True, nullable=False),
        sa.Column('name', sa.String(255), nullable=False),
        sa.Column('jobs_base_path', sa.String(512), nullable=False)
    )
    op.create_index('jenkins_groups_unq_index', 'jenkins_groups', ['name'], unique=True)

    op.create_table( 'jenkins_jobs',
        sa.Column('id', sa.Integer, primary_key=True, nullable=False),
        sa.Column('name', sa.String(255), nullable=False),
        sa.Column('jenkins_group_id', sa.Integer, nullable=False),
        sa.Column('jenkins_job_perent_id', sa.Integer, nullable=True),
        sa.Column('gitlab_project_id', sa.Integer, nullable=False)
    )
    op.create_index('jenkins_jobs_unq_index', 'jenkins_jobs', ['name', 'jenkins_group_id'], unique=True)
    op.create_index('jenkins_jobs_group_idx', 'jenkins_jobs', ['jenkins_group_id'])

def downgrade():
    op.drop_idnex('jenkins_jobs_unq_index')
    op.drop_idnex('jenkins_groups_unq_index')
    op.drop_idnex('jenkins_jobs_group_idx')
    op.drop_table('jenkins_jobs')
    op.drop_table('jenkins_groups')


text:
This package is a wrapper around the PDO DBMS driver. It enables easy paramterisation of queries with one function call, aditionally it expoess CRUD operations.

## Install
Using composer
`composer require DavidFricker/DataAbstracter`

## Usage
```php
use DavidFricker\DataAbstracter\Adapter\MySQLDatabaseWrapper ;

$MySQLDatabaseWrapper = new MySQLDatabaseWrapper($dsn, $username, $password);
```

## API
### delete()
Remove one or more rows. As this is intended to be a simple helper function the only 'glue' to hold together the where clauses is 'AND' more complex delete statements should be performed using `run()`.
#### Example
```php
$where = ['col_name' => 'expected_value'];
$limit = 10;
$MySQLDatabaseWrapper->delete('table_name', $where, $limit);
```
### update()
Update one or more rows. This is intended to be a simple helper function the only 'glue' to hold together the where clauses is 'AND' more complex update statements should be performed using `run()`.
#### Example
```php
$data = ['col_name' => 'new_value'];
$where = ['col_name' => 'expected_value'];
$limit = 10;
$MySQLDatabaseWrapper->update('table_name', $data, $where, $limit);
```
### fetch()
Pull one or more rows. As this is intended to be a simple helper function the only 'glue' to hold together the where clauses is 'AND' more complex update statements should be performed using `run()`. IMPORTANT: Ensure the $columns variable does not contain user input as it is inserted as-is into the statement and as so creates an SQL injection vulnerable.
#### Example
```php
$columns = ['col_name_1', 'col_name_2'];
$where = ['col_name' => 'expected_value'];
$limit = 10;
$MySQLDatabaseWrapper->fetch('table_name', $columns, $where, $limit);
```
### insert()
Create a new row.
#### Example
```php
$data = ['col_name_1' => 'new_value', 'col_name_2' => 'new_value'];
$MySQLDatabaseWrapper->insert('table_name', $data);
```
### run()
Execute any SQL query. To ensure your query is safe from SQL injection attacks pass all values via the `$bind` array.
#### Example
```php
$new_record = ['col_name_1' => 'new_value', 'col_name_2' => 'new_value'];
$MySQLDatabaseWrapper->insert('table_name', $new_record);
```
### rowCount()
Fetch the number of rows returned from the last query performed.
#### Example
```php
$new_record = ['col_name_1' => 'new_value', 'col_name_2' => 'new_value'];
$MySQLDatabaseWrapper->insert('table_name', $new_record);
```
## Bugs
Please report bugs by creating an issue and supply code to replicate the issue. Code contributions are always welcome.

## Licence
Released under the MIT licenses.