text:
import {
  report,
  ruleMessages,
  cssWordIsVariable,
  validateOptions,
} from "../../utils"

export const ruleName = "declaration-block-no-duplicate-properties"

export const messages = ruleMessages(ruleName, {
  rejected: p => `Unexpected duplicate property "${p}"`,
})

export default function (actual) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, { actual })
    if (!validOptions) { return }

    // In order to accommodate nested blocks (postcss-nested),
    // we need to run a shallow loop (instead of eachDecl() or eachRule(),
    // which loop recursively) and allow each nested block to accumulate
    // its own list of properties -- so that a property in a nested rule
    // does not conflict with the same property in the parent rule
    root.each(node => {
      if (node.type === "rule" || node.type === "atrule") {
        checkRulesInNode(node)
      }
    })

    function checkRulesInNode(node) {
      const decls = []
      node.each(child => {
        if (child.nodes && child.nodes.length) {
          checkRulesInNode(child)
        }
        if (child.type !== "decl") { return }
        const prop = child.prop

        if (cssWordIsVariable(prop)) { return }

        // Ignore the src property as commonly duplicated in at-fontface
        if (prop === "src") { return }

        if (decls.indexOf(prop) !== -1) {
          report({
            message: messages.rejected(prop),
            node: child,
            result,
            ruleName,
          })
        }
        decls.push(prop)
      })
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.coveo.blitz</groupId>
  <artifactId>client</artifactId>
  <version>1.2.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer>
                  <mainClass>com.coveo.blitz.client.Main</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>hamcrest-core</artifactId>
          <groupId>org.hamcrest</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.unitils</groupId>
      <artifactId>unitils-core</artifactId>
      <version>3.4.2</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>commons-lang</artifactId>
          <groupId>commons-lang</groupId>
        </exclusion>
        <exclusion>
          <artifactId>commons-collections</artifactId>
          <groupId>commons-collections</groupId>
        </exclusion>
        <exclusion>
          <artifactId>ognl</artifactId>
          <groupId>ognl</groupId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
@class FMDatabase;
@class EXRate;

@interface EXRHistoricalDAO : NSObject

+ (NSString *)queryDateNeedToUpdateWithIndex:(NSInteger)index;

+ (void)updateHistoricalData:(NSArray<EXRate *> *)dataArray withIndex:(NSInteger)index;

+ (BOOL)deleteDateOfIndex:(NSInteger)index;

+ (void)getDataWithEndDate:(NSDate *)endDate withFromDate:(NSDate *)fromDate withIndex:(NSInteger)index withCompletionBlock:(void (^)(NSArray<EXRate *> *, BOOL, BOOL))completion;

+ (BOOL)haveDataWithEndDate:(NSDate *)endDate withTimeInterval:(NSTimeInterval)time withIndex:(NSInteger)index;

@end


text:
@interface METEJSONSerializationTests : XCTestCase

@end

@implementation METEJSONSerializationTests

- (void)testObjectFromEJSONObjectConvertsDate {
  NSDate *date = [NSDate date];
  id EJSONObject = @{@"$date": @(floor([date timeIntervalSince1970] * 1000.0))};

  NSError *error;
  NSDate *convertedDate = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];

  XCTAssertEqualWithAccuracy([date timeIntervalSinceDate:convertedDate], 0, 0.001);
  XCTAssertNil(error);
}

- (void)testObjectFromEJSONObjectConvertDateWithoutNumberOfMillisecondsReturnsNilAndError {
  id EJSONObject = @{@"$date": @"bla"};

  NSError *error;
  NSDate *convertedDate = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];
  XCTAssertNil(convertedDate);
  XCTAssertNotNil(error);
}

- (void)testObjectFromEJSONObjectConvertsBinaryData {
  NSData *data = [self randomData];
  id EJSONObject = @{@"$binary": [data base64EncodedStringWithOptions:0]};

  NSError *error;
  NSData *convertedData = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];

  XCTAssertEqualObjects(data, convertedData);
  XCTAssertNil(error);
}

- (void)testObjectFromEJSONObjectConvertBinaryDataWithoutStringReturnsNilAndError {
  id EJSONObject = @{@"$binary": @1};

  NSError *error;
  NSData *convertedData = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];
  XCTAssertNil(convertedData);
  XCTAssertNotNil(error);
}

- (void)testObjectFromEJSONObjectConvertsEscapedValues {
  id EJSONObject = @{@"$escape": @{@"$date": @10000}};

  NSError *error;
  NSData *convertedObject = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];

  XCTAssertEqualObjects(@{@"$date": @10000}, convertedObject);
  XCTAssertNil(error);
}

- (void)testObjectFromEJSONObjectConvertsObjectsNestedInDictionaries {
  id EJSONObject = @{@"createdAt": @{@"$date": @(floor([[NSDate date] timeIntervalSince1970] * 1000.0))}};

  NSError *error;
  NSDictionary *object = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];
  XCTAssertTrue([object[@"createdAt"] isKindOfClass:[NSDate class]]);
  XCTAssertNil(error);
}

- (void)testObjectFromEJSONObjectConvertsObjectsNestedInArrays {
  id EJSONObject = @[@{@"$date": @(floor([[NSDate date] timeIntervalSince1970] * 1000.0))}];

  NSError *error;
  NSArray *object = [METEJSONSerialization objectFromEJSONObject:EJSONObject error:&error];
  XCTAssertTrue([object[0] isKindOfClass:[NSDate class]]);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectConvertsDate {
  NSDate *date = [NSDate date];

  NSError *error;
  id EJSONObject = [METEJSONSerialization EJSONObjectFromObject:date error:&error];

  XCTAssertEqualObjects(@{@"$date": @(floor([date timeIntervalSince1970] * 1000.0))}, EJSONObject);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectConvertsBinaryData {
  NSData *data = [self randomData];

  NSError *error;
  id EJSONObject = [METEJSONSerialization EJSONObjectFromObject:data error:&error];

  XCTAssertEqualObjects(@{@"$binary": [data base64EncodedStringWithOptions:0]}, EJSONObject);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectEscapesValuesIfNecessary {
  id object = @{@"$date": @10000};

  NSError *error;
  id EJSONObject = [METEJSONSerialization EJSONObjectFromObject:object error:&error];

  XCTAssertEqualObjects(@{@"$escape": @{@"$date": @10000}}, EJSONObject);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectOnlyEscapesValuesOneLevelDown {
  NSDate *date = [NSDate date];
  id object = @{@"$date": date};

  NSError *error;
  id EJSONObject = [METEJSONSerialization EJSONObjectFromObject:object error:&error];

  XCTAssertEqualObjects(@{@"$escape": @{@"$date": [METEJSONSerialization EJSONObjectFromObject:date error:&error]}}, EJSONObject);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectConvertsObjectsNestedInDictionaries {
  id object = @{@"createdAt": [NSDate date]};

  NSError *error;
  NSDictionary *EJSONObject = [METEJSONSerialization EJSONObjectFromObject:object error:&error];
  XCTAssertTrue([EJSONObject[@"createdAt"] isKindOfClass:[NSDictionary class]]);
  XCTAssertNil(error);
}

- (void)testEJSONObjectFromObjectConvertsObjectsNestedInArrays {
  id object = @[[NSDate date]];

  NSError *error;
  NSArray *EJSONObject = [METEJSONSerialization EJSONObjectFromObject:object error:&error];
  XCTAssertTrue([EJSONObject[0] isKindOfClass:[NSDictionary class]]);
  XCTAssertNil(error);
}

#pragma mark - Helper Methods

- (NSData *)randomData {
  NSMutableData *data = [NSMutableData dataWithLength:1024];
  arc4random_buf([data mutableBytes], data.length);
  return data;
}

@end


text:
<?php return '<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
                        <id>http://localhost/feedBaseUrl/feed3</id>
                                <link href="http://localhost/feedBaseUrl/feed3"></link>
                                <title><![CDATA[Feed 3]]></title>
                                <description>This is feed 3 from the unit tests</description>
                                <language>en-US</language>
                                <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
                        <entry>
            <title><![CDATA[feedItemTitle]]></title>
            <link rel="alternate" href="https://localhost/news/testItem1" />
            <id>http://localhost/1</id>
            <author>
                <name> <![CDATA[feedItemAuthor]]></name>
            </author>
            <summary type="html">
                <![CDATA[feedItemSummary]]>
            </summary>
                          <enclosure url="http://localhost/image1.jpg" length="31300" type="image/jpeg" />
                                    <category type="html">
                <![CDATA[feedItemCategory]]>
            </category>
                        <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
        </entry>
            <entry>
            <title><![CDATA[feedItemTitle]]></title>
            <link rel="alternate" href="https://localhost/news/testItem1" />
            <id>http://localhost/1</id>
            <author>
                <name> <![CDATA[feedItemAuthor]]></name>
            </author>
            <summary type="html">
                <![CDATA[feedItemSummary]]>
            </summary>
                          <enclosure url="http://localhost/image1.jpg" length="31300" type="image/jpeg" />
                                    <category type="html">
                <![CDATA[feedItemCategory]]>
            </category>
                        <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
        </entry>
            <entry>
            <title><![CDATA[feedItemTitle]]></title>
            <link rel="alternate" href="https://localhost/news/testItem1" />
            <id>http://localhost/1</id>
            <author>
                <name> <![CDATA[feedItemAuthor]]></name>
            </author>
            <summary type="html">
                <![CDATA[feedItemSummary]]>
            </summary>
                          <enclosure url="http://localhost/image1.jpg" length="31300" type="image/jpeg" />
                                    <category type="html">
                <![CDATA[feedItemCategory]]>
            </category>
                        <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
        </entry>
            <entry>
            <title><![CDATA[feedItemTitle]]></title>
            <link rel="alternate" href="https://localhost/news/testItem1" />
            <id>http://localhost/1</id>
            <author>
                <name> <![CDATA[feedItemAuthor]]></name>
            </author>
            <summary type="html">
                <![CDATA[feedItemSummary]]>
            </summary>
                          <enclosure url="http://localhost/image1.jpg" length="31300" type="image/jpeg" />
                                    <category type="html">
                <![CDATA[feedItemCategory]]>
            </category>
                        <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
        </entry>
            <entry>
            <title><![CDATA[feedItemTitle]]></title>
            <link rel="alternate" href="https://localhost/news/testItem1" />
            <id>http://localhost/1</id>
            <author>
                <name> <![CDATA[feedItemAuthor]]></name>
            </author>
            <summary type="html">
                <![CDATA[feedItemSummary]]>
            </summary>
                          <enclosure url="http://localhost/image1.jpg" length="31300" type="image/jpeg" />
                                    <category type="html">
                <![CDATA[feedItemCategory]]>
            </category>
                        <updated>Fri, 01 Jan 2016 00:00:00 +0100</updated>
        </entry>
    </feed>
';


text:
(function($){

    var score = 0,
    secondes = 60;
    function timer(){
        $('#countdown').html(secondes);
        secondes--;

        if(secondes<0){
            secondes = 0;
            $('#countdown').html('0');
            swal({
              title: 'End Of game',
              text: 'You have ' + score + ' points.',
              type: 'success',
              showCancelButton: true,
              confirmButtonText: 'Play again !',
              closeOnConfirm: true
            },
            function(){
              secondes = 50;
              score = 0;
              $('#score span').html(score);
              $('.letter').remove();
              setTimeout(timer, 1000);
              setTimeout(generateLetters, 1000);
            });
        }else{
            setTimeout(timer, 1000);
            setTimeout(generateLetters, 600);
        }

    }

    timer();
    generateLetters();

    $('body').on('keydown', function(e){
        if(secondes!=0){
             e.preventDefault();
             if(e.keyCode < 62){
                console.log('This key is disable');
             }else{
                var keycode = String.fromCharCode(e.keyCode).toLowerCase();
                $('.letter'+keycode).animate({ 'top'  : '20px', 'opacity': 0 }, 'fast');
                $('.letter'+keycode).fadeOut('slow').hide('slow', function() {
                    score += 5;
                    $('#score span').html(score);
                    $(this).remove();
                });
            }
        }
    });

    function generateLetters () {
        var chars = 'abcdefghijklmnopqrstuvwxyz',
        stringLength = 1,
        randomstring = '';
        for(var i = 0; i < stringLength; i++) {
          var rnum = Math.floor(Math.random() * chars.length);
          randomstring += chars.substring(rnum, rnum + 1);
        }
        var top = Math.floor(Math.random() * 400),
        left = Math.floor(Math.random() * 700);

        $('#container').append('
'+ randomstring.toUpperCase() +'
');
    }

})(jQuery);


text:
require 'nn'

local TVLossCriterion, parent = torch.class('nn.TVLossCriterion', 'nn.Criterion')

function TVLossCriterion:__init()
    parent.__init(self)

    local crop_l = nn.SpatialZeroPadding(-1, 0, 0, 0)
    local crop_r = nn.SpatialZeroPadding(0, -1, 0, 0)
    local crop_t = nn.SpatialZeroPadding(0, 0, -1, 0)
    local crop_b = nn.SpatialZeroPadding(0, 0, 0, -1)
    self.target = torch.zeros(1)
    self.mse = nn.MSECriterion()
    self.mse.sizeAverage = false

    local lr = nn.Sequential()
    lr:add(nn.ConcatTable():add(crop_l):add(crop_r))
    lr:add(nn.CSubTable())
    local tb = nn.Sequential()
    tb:add(nn.ConcatTable():add(crop_t):add(crop_b))
    tb:add(nn.CSubTable())

    self.crit = nn.ConcatTable():add(lr):add(tb)
end

function TVLossCriterion:updateOutput(input)
    local output = self.crit:forward(input)
    local loss = 0
    for i=1,2 do
        local target
        if output[i]:nDimension() == 3 then
            target = self.target:view(1,1,1):expandAs(output[i])
        else
            target = self.target:view(1,1,1,1):expandAs(output[i])
        end
        loss = loss + self.mse:forward(output[i], target)
    end
    self.output = loss
    return self.output
end

function TVLossCriterion:updateGradInput(input)
    self.gradInput:resizeAs(input):zero()
    local output = self.crit.output
    local df_do = {}
    for i=1,2 do
        local target
        if output[i]:nDimension() == 3 then
            target = self.target:view(1,1,1):expandAs(output[i])
        else
            target = self.target:view(1,1,1,1):expandAs(output[i])
        end
        df_do[i] = self.mse:backward(output[i], target):clone()
    end
    local grad = self.crit:backward(input, df_do)
    self.gradInput:copy(self.crit:backward(input, df_do))
    return self.gradInput
end


text:
<?php

abstract class DiffusionFileFutureQuery
  extends DiffusionQuery {

  private $timeout;
  private $byteLimit;

  private $didHitByteLimit = false;
  private $didHitTimeLimit = false;

  public static function getConduitParameters() {
    return array(
      'timeout' => 'optional int',
      'byteLimit' => 'optional int',
    );
  }

  public function setTimeout($timeout) {
    $this->timeout = $timeout;
    return $this;
  }

  public function getTimeout() {
    return $this->timeout;
  }

  public function setByteLimit($byte_limit) {
    $this->byteLimit = $byte_limit;
    return $this;
  }

  public function getByteLimit() {
    return $this->byteLimit;
  }

  final public function getExceededByteLimit() {
    return $this->didHitByteLimit;
  }

  final public function getExceededTimeLimit() {
    return $this->didHitTimeLimit;
  }

  abstract protected function newQueryFuture();

  final public function respondToConduitRequest(ConduitAPIRequest $request) {
    $drequest = $this->getRequest();

    $timeout = $request->getValue('timeout');
    if ($timeout) {
      $this->setTimeout($timeout);
    }

    $byte_limit = $request->getValue('byteLimit');
    if ($byte_limit) {
      $this->setByteLimit($byte_limit);
    }

    $file = $this->execute();

    $too_slow = (bool)$this->getExceededTimeLimit();
    $too_huge = (bool)$this->getExceededByteLimit();

    $file_phid = null;
    if (!$too_slow && !$too_huge) {
      $repository = $drequest->getRepository();
      $repository_phid = $repository->getPHID();

      $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
        $file->attachToObject($repository_phid);
      unset($unguarded);

      $file_phid = $file->getPHID();
    }

    return array(
      'tooSlow' => $too_slow,
      'tooHuge' => $too_huge,
      'filePHID' => $file_phid,
    );
  }

  final public function executeInline() {
    $future = $this->newConfiguredQueryFuture();
    list($stdout) = $future->resolvex();
    return $stdout;
  }

  final protected function executeQuery() {
    $future = $this->newQueryFuture();

    $drequest = $this->getRequest();

    $name = basename($drequest->getPath());
    $relative_ttl = phutil_units('48 hours in seconds');

    try {
      $threshold = PhabricatorFileStorageEngine::getChunkThreshold();
      $future->setReadBufferSize($threshold);

      $source = id(new PhabricatorExecFutureFileUploadSource())
        ->setName($name)
        ->setRelativeTTL($relative_ttl)
        ->setViewPolicy(PhabricatorPolicies::POLICY_NOONE)
        ->setExecFuture($future);

      $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
        $file = $source->uploadFile();
      unset($unguarded);

    } catch (CommandException $ex) {
      if (!$future->getWasKilledByTimeout()) {
        throw $ex;
      }

      $this->didHitTimeLimit = true;
      $file = null;
    }

    $byte_limit = $this->getByteLimit();

    if ($byte_limit && ($file->getByteSize() > $byte_limit)) {
      $this->didHitByteLimit = true;

      $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
        id(new PhabricatorDestructionEngine())
          ->destroyObject($file);
      unset($unguarded);

      $file = null;
    }

    return $file;
  }

  private function newConfiguredQueryFuture() {
    $future = $this->newQueryFuture();

    if ($this->getTimeout()) {
      $future->setTimeout($this->getTimeout());
    }

    $byte_limit = $this->getByteLimit();
    if ($byte_limit) {
      $future->setStdoutSizeLimit($byte_limit + 1);
    }

    return $future;
  }

}


text:
import { isSameTopWindow } from 'cross-domain-utils/src';

import { CONFIG } from '../conf';

export function emulateIERestrictions(sourceWindow, targetWindow) {
    if (!CONFIG.ALLOW_POSTMESSAGE_POPUP) {

        if (isSameTopWindow(sourceWindow, targetWindow) === false) {
            throw new Error('Can not send and receive post messages between two different windows (disabled to emulate IE)');
        }
    }
}


text:
"""
Tests introduced for new utilities.
"""

import StringIO
from textwrap import dedent
import unittest2 as unittest
from cfn_pyplates.utils import (
    _selective_eval,
    templated_read,
)
from cfn_pyplates.functions import ref

class TemplatedReadTests(unittest.TestCase):
    def test_selective_eval_noeval(self):
        """
        Assert selective eval returns s if s is not a function 'atom'
        """
        s = "this is embedded {'Ref': 'AWS::StackId'} in string"
        self.assertEquals(s, _selective_eval(s))

    def test_selective_eval_evaluates(self):
        """
        Given string representing a function, evaluate
        """
        s = "{'Ref': 'AWS::StackId'}"
        expected = dict(Ref='AWS::StackId')
        self.assertEquals(expected, _selective_eval(s))

    def test_template_transform(self):
        """
        Verify that templated_read returns correct output
        """
        template = StringIO.StringIO(dedent('''\
            this is a {{ string_value }} and this is a
            {{ function_value }}'''))
        rendered = {'Fn::Join':
                    ['',
                    [u'this is a String Value and this is a\n',
                    {'Ref': 'AWS::Regions'},
                    u'']]
                    }
        context = dict(string_value="String Value",
                       function_value=ref('AWS::Regions'))

        output = templated_read(template, context)
        self.assertEquals(rendered, output)


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "clojure/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "clojure/" combined with a set of templates)

********************************************************************************

-->

# Quick reference

-	**Maintained by**:
	[the Docker Community](https://github.com/Quantisan/docker-clojure)

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://dockr.ly/slack), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

# Supported tags and respective `Dockerfile` links

-	[`latest`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-slim-buster/latest/Dockerfile)
-	[`openjdk-8`, `openjdk-8-lein`, `openjdk-8-lein-2.9.6`, `openjdk-8-buster`, `openjdk-8-lein-buster`, `openjdk-8-lein-2.9.6-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-buster/lein/Dockerfile)
-	[`openjdk-8-slim-buster`, `openjdk-8-lein-slim-buster`, `openjdk-8-lein-2.9.6-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-slim-buster/lein/Dockerfile)
-	[`openjdk-8-boot`, `openjdk-8-boot-2.8.3`, `openjdk-8-boot-buster`, `openjdk-8-boot-2.8.3-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-buster/boot/Dockerfile)
-	[`openjdk-8-boot-slim-buster`, `openjdk-8-boot-2.8.3-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-slim-buster/boot/Dockerfile)
-	[`openjdk-8-tools-deps`, `openjdk-8-tools-deps-1.10.3.933`, `openjdk-8-tools-deps-buster`, `openjdk-8-tools-deps-1.10.3.933-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-buster/tools-deps/Dockerfile)
-	[`openjdk-8-tools-deps-slim-buster`, `openjdk-8-tools-deps-1.10.3.933-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-8-slim-buster/tools-deps/Dockerfile)
-	[`openjdk-11`, `openjdk-11-lein`, `openjdk-11-lein-2.9.6`, `lein`, `lein-2.9.6`, `openjdk-11-buster`, `openjdk-11-lein-buster`, `openjdk-11-lein-2.9.6-buster`, `lein-buster`, `lein-2.9.6-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-buster/lein/Dockerfile)
-	[`openjdk-11-lein-slim-buster`, `openjdk-11-slim-buster`, `openjdk-11-lein-2.9.6-slim-buster`, `slim-buster`, `lein-slim-buster`, `lein-2.9.6-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-slim-buster/lein/Dockerfile)
-	[`openjdk-11-boot`, `openjdk-11-boot-2.8.3`, `boot`, `boot-2.8.3`, `openjdk-11-boot-buster`, `openjdk-11-boot-2.8.3-buster`, `boot-buster`, `boot-2.8.3-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-buster/boot/Dockerfile)
-	[`openjdk-11-boot-slim-buster`, `openjdk-11-boot-2.8.3-slim-buster`, `boot-slim-buster`, `boot-2.8.3-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-slim-buster/boot/Dockerfile)
-	[`openjdk-11-tools-deps`, `openjdk-11-tools-deps-1.10.3.933`, `tools-deps`, `tools-deps-1.10.3.933`, `openjdk-11-tools-deps-buster`, `openjdk-11-tools-deps-1.10.3.933-buster`, `tools-deps-buster`, `tools-deps-1.10.3.933-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-buster/tools-deps/Dockerfile)
-	[`openjdk-11-tools-deps-slim-buster`, `openjdk-11-tools-deps-1.10.3.933-slim-buster`, `tools-deps-1.10.3.933-slim-buster`, `tools-deps-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-11-slim-buster/tools-deps/Dockerfile)
-	[`openjdk-16`, `openjdk-16-lein`, `openjdk-16-lein-2.9.6`, `openjdk-16-slim-buster`, `openjdk-16-lein-slim-buster`, `openjdk-16-lein-2.9.6-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-slim-buster/lein/Dockerfile)
-	[`openjdk-16-buster`, `openjdk-16-lein-buster`, `openjdk-16-lein-2.9.6-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-buster/lein/Dockerfile)
-	[`openjdk-16-boot`, `openjdk-16-boot-2.8.3`, `openjdk-16-boot-slim-buster`, `openjdk-16-boot-2.8.3-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-slim-buster/boot/Dockerfile)
-	[`openjdk-16-boot-buster`, `openjdk-16-boot-2.8.3-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-buster/boot/Dockerfile)
-	[`openjdk-16-tools-deps`, `openjdk-16-tools-deps-1.10.3.933`, `openjdk-16-tools-deps-slim-buster`, `openjdk-16-tools-deps-1.10.3.933-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-slim-buster/tools-deps/Dockerfile)
-	[`openjdk-16-tools-deps-buster`, `openjdk-16-tools-deps-1.10.3.933-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-16-buster/tools-deps/Dockerfile)
-	[`openjdk-17`, `openjdk-17-lein`, `openjdk-17-lein-2.9.6`, `openjdk-17-slim-buster`, `openjdk-17-lein-slim-buster`, `openjdk-17-lein-2.9.6-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-slim-buster/lein/Dockerfile)
-	[`openjdk-17-buster`, `openjdk-17-lein-buster`, `openjdk-17-lein-2.9.6-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-buster/lein/Dockerfile)
-	[`openjdk-17-boot`, `openjdk-17-boot-2.8.3`, `openjdk-17-boot-slim-buster`, `openjdk-17-boot-2.8.3-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-slim-buster/boot/Dockerfile)
-	[`openjdk-17-boot-buster`, `openjdk-17-boot-2.8.3-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-buster/boot/Dockerfile)
-	[`openjdk-17-tools-deps`, `openjdk-17-tools-deps-1.10.3.933`, `openjdk-17-tools-deps-slim-buster`, `openjdk-17-tools-deps-1.10.3.933-slim-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-slim-buster/tools-deps/Dockerfile)
-	[`openjdk-17-tools-deps-buster`, `openjdk-17-tools-deps-1.10.3.933-buster`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-buster/tools-deps/Dockerfile)
-	[`openjdk-17-alpine`, `openjdk-17-lein-alpine`, `openjdk-17-lein-2.9.6-alpine`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-alpine/lein/Dockerfile)
-	[`openjdk-17-boot-alpine`, `openjdk-17-boot-2.8.3-alpine`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-alpine/boot/Dockerfile)
-	[`openjdk-17-tools-deps-alpine`, `openjdk-17-tools-deps-1.10.3.933-alpine`](https://github.com/Quantisan/docker-clojure/blob/29b35b1cf31e757291632a8dcf146aacde7b944e/target/openjdk-17-alpine/tools-deps/Dockerfile)

# Quick reference (cont.)

-	**Where to file issues**:
	[https://github.com/Quantisan/docker-clojure/issues](https://github.com/Quantisan/docker-clojure/issues)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/clojure/), [`arm64v8`](https://hub.docker.com/r/arm64v8/clojure/)

-	**Published image artifact details**:
	[repo-info repo's `repos/clojure/` directory](https://github.com/docker-library/repo-info/blob/master/repos/clojure) ([history](https://github.com/docker-library/repo-info/commits/master/repos/clojure))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images repo's `library/clojure` label](https://github.com/docker-library/official-images/issues?q=label%3Alibrary%2Fclojure)
	[official-images repo's `library/clojure` file](https://github.com/docker-library/official-images/blob/master/library/clojure) ([history](https://github.com/docker-library/official-images/commits/master/library/clojure))

-	**Source of this description**:
	[docs repo's `clojure/` directory](https://github.com/docker-library/docs/tree/master/clojure) ([history](https://github.com/docker-library/docs/commits/master/clojure))

# What is Clojure?

Clojure is a dialect of the Lisp programming language. It is a general-purpose programming language with an emphasis on functional programming. It runs on the Java Virtual Machine, Common Language Runtime, and JavaScript engines. Like other Lisps, Clojure treats code as data and has a macro system.

> [wikipedia.org/wiki/Clojure](http://en.wikipedia.org/wiki/Clojure)

![logo](https://raw.githubusercontent.com/docker-library/docs/665526c3b12cedfd721234cedb61e8433f73b75a/clojure/logo.png)

# How to use this image

## Build tools

Clojure has three major approaches to building and running projects:

1.	[leiningen](https://leiningen.org)
	1.	The oldest and probably most common tool
2.	[boot](http://boot-clj.com)
	1.	An alternative approach that solves similar problems as leiningen
3.	[tools-deps](https://clojure.org/guides/deps_and_cli)
	1.	A more recent official tool for some of the lein/boot use cases

There are variants of this image for all three of these tools and their respective releases. The most basic form of these tags is:

1.	`clojure:lein`
2.	`clojure:boot`
3.	`clojure:tools-deps`

But you can also append a hyphen and the version of that tool you'd like to use. For example, for lein 2.8.1 you can use this image: `clojure:lein-2.8.1`.

## Run your app with leiningen

Add a `Dockerfile` to an existing Leiningen/Clojure project with the following contents:

```dockerfile
FROM clojure
COPY . /usr/src/app
WORKDIR /usr/src/app
CMD ["lein", "run"]
```

Then, run these commands to build and run the image:

```console
$ docker build -t my-clojure-app .
$ docker run -it --rm --name my-running-app my-clojure-app
```

While the above is the most straightforward example of a `Dockerfile`, it does have some drawbacks. The `lein run` command will download your dependencies, compile the project, and then run it. That's a lot of work, all of which you may not want done every time you run the image. To get around this, you can download the dependencies and compile the project ahead of time. This will significantly reduce startup time when you run your image.

```dockerfile
FROM clojure
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY project.clj /usr/src/app/
RUN lein deps
COPY . /usr/src/app
RUN mv "$(lein uberjar | sed -n 's/^Created \(.*standalone\.jar\)/\1/p')" app-standalone.jar
CMD ["java", "-jar", "app-standalone.jar"]
```

Writing the `Dockerfile` this way will download the dependencies (and cache them, so they are only re-downloaded when the dependencies change) and then compile them into a standalone jar ahead of time rather than each time the image is run.

You can then build and run the image as above.

## Compile your Lein/Clojure project into a jar from within the container

If you have an existing Lein/Clojure project, it's fairly straightforward to compile your project into a jar from a container:

```console
$ docker run -it --rm -v "$PWD":/usr/src/app -w /usr/src/app clojure lein uberjar
```

This will build your project into a jar file located in your project's `target/uberjar` directory.

## More details

See [the official image README](https://github.com/Quantisan/docker-clojure/blob/master/README.md) for more details about using this image with boot and tools-deps.

# Image Variants

The `clojure` images come in many flavors, each designed for a specific use case.

## `clojure:<version>`

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of.

Some of these tags may have names like buster in them. These are the suite code names for releases of [Debian](https://wiki.debian.org/DebianReleases) and indicate which release the image is based on. If your image needs to install any additional packages beyond what comes with the image, you'll likely want to specify one of these explicitly to minimize breakage when there are new releases of Debian.

## `clojure:<version>-slim`

This image does not contain the common packages contained in the default tag and only contains the minimal packages needed to run `clojure`. Unless you are working in an environment where *only* the `clojure` image will be deployed and you have space constraints, we highly recommend using the default image of this repository.

## `clojure:<version>-alpine`

This image is based on the popular [Alpine Linux project](https://alpinelinux.org), available in [the `alpine` official image](https://hub.docker.com/_/alpine). Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.

This variant is useful when final image size being as small as possible is your primary concern. The main caveat to note is that it does use [musl libc](https://musl.libc.org) instead of [glibc and friends](https://www.etalabs.net/compare_libcs.html), so software will often run into issues depending on the depth of their libc requirements/assumptions. See [this Hacker News comment thread](https://news.ycombinator.com/item?id=10782897) for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images.

To minimize image size, it's uncommon for additional related tools (such as `git` or `bash`) to be included in Alpine-based images. Using this image as a base, add the things you need in your own Dockerfile (see the [`alpine` image description](https://hub.docker.com/_/alpine/) for examples of how to install packages if you are unfamiliar).

# License

View [license information](http://clojure.org/license) for the software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `clojure/` directory](https://github.com/docker-library/repo-info/tree/master/repos/clojure).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
class CreateProviderAccounts < ActiveRecord::Migration
  def change
    create_table :provider_accounts do |t|
      t.timestamps
    end
  end
end


text:
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/init.h>
#include <linux/pcieport_if.h>
#include <linux/aer.h>
#include <linux/dmi.h>
#include <linux/pci-aspm.h>

#include "portdrv.h"
#include "aer/aerdrv.h"

/*
 * Version Information
 */
#define DRIVER_VERSION "v1.0"
#define DRIVER_AUTHOR "tom.l.nguyen@intel.com"
#define DRIVER_DESC "PCIe Port Bus Driver"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");

/* If this switch is set, PCIe port native services should not be enabled. */
bool pcie_ports_disabled;

/*
 * If this switch is set, ACPI _OSC will be used to determine whether or not to
 * enable PCIe port native services.
 */
bool pcie_ports_auto = true;

static int __init pcie_port_setup(char *str)
{
	if (!strncmp(str, "compat", 6)) {
		pcie_ports_disabled = true;
	} else if (!strncmp(str, "native", 6)) {
		pcie_ports_disabled = false;
		pcie_ports_auto = false;
	} else if (!strncmp(str, "auto", 4)) {
		pcie_ports_disabled = false;
		pcie_ports_auto = true;
	}

	return 1;
}
__setup("pcie_ports=", pcie_port_setup);

/* global data */

/**
 * pcie_clear_root_pme_status - Clear root port PME interrupt status.
 * @dev: PCIe root port or event collector.
 */
void pcie_clear_root_pme_status(struct pci_dev *dev)
{
	int rtsta_pos;
	u32 rtsta;

	rtsta_pos = pci_pcie_cap(dev) + PCI_EXP_RTSTA;

	pci_read_config_dword(dev, rtsta_pos, &rtsta);
	rtsta |= PCI_EXP_RTSTA_PME;
	pci_write_config_dword(dev, rtsta_pos, rtsta);
}

static int pcie_portdrv_restore_config(struct pci_dev *dev)
{
	int retval;

	retval = pci_enable_device(dev);
	if (retval)
		return retval;
	pci_set_master(dev);
	return 0;
}

#ifdef CONFIG_PM
static int pcie_port_resume_noirq(struct device *dev)
{
	struct pci_dev *pdev = to_pci_dev(dev);

	/*
	 * Some BIOSes forget to clear Root PME Status bits after system wakeup
	 * which breaks ACPI-based runtime wakeup on PCI Express, so clear those
	 * bits now just in case (shouldn't hurt).
	 */
	if(pdev->pcie_type == PCI_EXP_TYPE_ROOT_PORT)
		pcie_clear_root_pme_status(pdev);
	return 0;
}

static const struct dev_pm_ops pcie_portdrv_pm_ops = {
	.suspend	= pcie_port_device_suspend,
	.resume		= pcie_port_device_resume,
	.freeze		= pcie_port_device_suspend,
	.thaw		= pcie_port_device_resume,
	.poweroff	= pcie_port_device_suspend,
	.restore	= pcie_port_device_resume,
	.resume_noirq	= pcie_port_resume_noirq,
};

#define PCIE_PORTDRV_PM_OPS	(&pcie_portdrv_pm_ops)

#else /* !PM */

#define PCIE_PORTDRV_PM_OPS	NULL
#endif /* !PM */

/*
 * pcie_portdrv_probe - Probe PCI-Express port devices
 * @dev: PCI-Express port device being probed
 *
 * If detected invokes the pcie_port_device_register() method for
 * this port device.
 *
 */
static int __devinit pcie_portdrv_probe(struct pci_dev *dev,
					const struct pci_device_id *id)
{
	int status;

	if (!pci_is_pcie(dev) ||
	    ((dev->pcie_type != PCI_EXP_TYPE_ROOT_PORT) &&
	     (dev->pcie_type != PCI_EXP_TYPE_UPSTREAM) &&
	     (dev->pcie_type != PCI_EXP_TYPE_DOWNSTREAM)))
		return -ENODEV;

	if (!dev->irq && dev->pin) {
		dev_warn(&dev->dev, "device [%04x:%04x] has invalid IRQ; "
			 "check vendor BIOS\n", dev->vendor, dev->device);
	}
	status = pcie_port_device_register(dev);
	if (status)
		return status;

	pci_save_state(dev);

	return 0;
}

static void pcie_portdrv_remove(struct pci_dev *dev)
{
	pcie_port_device_remove(dev);
}

static int error_detected_iter(struct device *device, void *data)
{
	struct pcie_device *pcie_device;
	struct pcie_port_service_driver *driver;
	struct aer_broadcast_data *result_data;
	pci_ers_result_t status;

	result_data = (struct aer_broadcast_data *) data;

	if (device->bus == &pcie_port_bus_type && device->driver) {
		driver = to_service_driver(device->driver);
		if (!driver ||
			!driver->err_handler ||
			!driver->err_handler->error_detected)
			return 0;

		pcie_device = to_pcie_device(device);

		/* Forward error detected message to service drivers */
		status = driver->err_handler->error_detected(
			pcie_device->port,
			result_data->state);
		result_data->result =
			merge_result(result_data->result, status);
	}

	return 0;
}

static pci_ers_result_t pcie_portdrv_error_detected(struct pci_dev *dev,
					enum pci_channel_state error)
{
	struct aer_broadcast_data data = {error, PCI_ERS_RESULT_CAN_RECOVER};
	int ret;

	/* can not fail */
	ret = device_for_each_child(&dev->dev, &data, error_detected_iter);

	return data.result;
}

static int mmio_enabled_iter(struct device *device, void *data)
{
	struct pcie_device *pcie_device;
	struct pcie_port_service_driver *driver;
	pci_ers_result_t status, *result;

	result = (pci_ers_result_t *) data;

	if (device->bus == &pcie_port_bus_type && device->driver) {
		driver = to_service_driver(device->driver);
		if (driver &&
			driver->err_handler &&
			driver->err_handler->mmio_enabled) {
			pcie_device = to_pcie_device(device);

			/* Forward error message to service drivers */
			status = driver->err_handler->mmio_enabled(
					pcie_device->port);
			*result = merge_result(*result, status);
		}
	}

	return 0;
}

static pci_ers_result_t pcie_portdrv_mmio_enabled(struct pci_dev *dev)
{
	pci_ers_result_t status = PCI_ERS_RESULT_RECOVERED;
	int retval;

	/* get true return value from &status */
	retval = device_for_each_child(&dev->dev, &status, mmio_enabled_iter);
	return status;
}

static int slot_reset_iter(struct device *device, void *data)
{
	struct pcie_device *pcie_device;
	struct pcie_port_service_driver *driver;
	pci_ers_result_t status, *result;

	result = (pci_ers_result_t *) data;

	if (device->bus == &pcie_port_bus_type && device->driver) {
		driver = to_service_driver(device->driver);
		if (driver &&
			driver->err_handler &&
			driver->err_handler->slot_reset) {
			pcie_device = to_pcie_device(device);

			/* Forward error message to service drivers */
			status = driver->err_handler->slot_reset(
					pcie_device->port);
			*result = merge_result(*result, status);
		}
	}

	return 0;
}

static pci_ers_result_t pcie_portdrv_slot_reset(struct pci_dev *dev)
{
	pci_ers_result_t status = PCI_ERS_RESULT_RECOVERED;
	int retval;

	/* If fatal, restore cfg space for possible link reset at upstream */
	if (dev->error_state == pci_channel_io_frozen) {
		dev->state_saved = true;
		pci_restore_state(dev);
		pcie_portdrv_restore_config(dev);
		pci_enable_pcie_error_reporting(dev);
	}

	/* get true return value from &status */
	retval = device_for_each_child(&dev->dev, &status, slot_reset_iter);

	return status;
}

static int resume_iter(struct device *device, void *data)
{
	struct pcie_device *pcie_device;
	struct pcie_port_service_driver *driver;

	if (device->bus == &pcie_port_bus_type && device->driver) {
		driver = to_service_driver(device->driver);
		if (driver &&
			driver->err_handler &&
			driver->err_handler->resume) {
			pcie_device = to_pcie_device(device);

			/* Forward error message to service drivers */
			driver->err_handler->resume(pcie_device->port);
		}
	}

	return 0;
}

static void pcie_portdrv_err_resume(struct pci_dev *dev)
{
	int retval;
	/* nothing to do with error value, if it ever happens */
	retval = device_for_each_child(&dev->dev, NULL, resume_iter);
}

/*
 * LINUX Device Driver Model
 */
static const struct pci_device_id port_pci_ids[] = { {
	/* handle any PCI-Express port */
	PCI_DEVICE_CLASS(((PCI_CLASS_BRIDGE_PCI << 8) | 0x00), ~0),
	}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, port_pci_ids);

static struct pci_error_handlers pcie_portdrv_err_handler = {
		.error_detected = pcie_portdrv_error_detected,
		.mmio_enabled = pcie_portdrv_mmio_enabled,
		.slot_reset = pcie_portdrv_slot_reset,
		.resume = pcie_portdrv_err_resume,
};

static struct pci_driver pcie_portdriver = {
	.name		= "pcieport",
	.id_table	= &port_pci_ids[0],

	.probe		= pcie_portdrv_probe,
	.remove		= pcie_portdrv_remove,

	.err_handler 	= &pcie_portdrv_err_handler,

	.driver.pm 	= PCIE_PORTDRV_PM_OPS,
};

static int __init dmi_pcie_pme_disable_msi(const struct dmi_system_id *d)
{
	pr_notice("%s detected: will not use MSI for PCIe PME signaling\n",
			d->ident);
	pcie_pme_disable_msi();
	return 0;
}

static struct dmi_system_id __initdata pcie_portdrv_dmi_table[] = {
	/*
	 * Boxes that should not use MSI for PCIe PME signaling.
	 */
	{
	 .callback = dmi_pcie_pme_disable_msi,
	 .ident = "MSI Wind U-100",
	 .matches = {
		     DMI_MATCH(DMI_SYS_VENDOR,
		     		"MICRO-STAR INTERNATIONAL CO., LTD"),
		     DMI_MATCH(DMI_PRODUCT_NAME, "U-100"),
		     },
	 },
	 {}
};

static int __init pcie_portdrv_init(void)
{
	int retval;

	if (pcie_ports_disabled)
		return pci_register_driver(&pcie_portdriver);

	dmi_check_system(pcie_portdrv_dmi_table);

	retval = pcie_port_bus_register();
	if (retval) {
		printk(KERN_WARNING "PCIE: bus_register error: %d\n", retval);
		goto out;
	}
	retval = pci_register_driver(&pcie_portdriver);
	if (retval)
		pcie_port_bus_unregister();
 out:
	return retval;
}

module_init(pcie_portdrv_init);


text:
/**
 * Description: Sample theme for site which extends the Gizmo grid-theme.
 */
@import url(../../../themes/bootstrap/style.css);

#footer {
	background: #eee;
	margin-top: 50px;
	padding-bottom:10px;
	padding-top:20px;
}


text:
using System;
using GeoAPI.Geometries;

namespace DotSpatial.Symbology
{
    /// <summary>
    /// This supports the FeatureLayer event SelectionChanged, for both groups and feature layers, or
    /// any other layer that supports both an ISelection and inherits from IFeatureLayer.
    /// </summary>
    public interface ISelectable
    {
        #region Events

        /// <summary>
        /// Occurs after all of the layers have been updated with new selection content.
        /// </summary>
        event EventHandler SelectionChanged;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether this item is actively supporting selection.
        /// </summary>
        bool SelectionEnabled { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Removes any members from existing in the selected state.
        /// </summary>
        /// <param name="affectedArea">The affected area.</param>
        /// <param name="force">Indicates whether the selection should be cleared although SelectionEnabled is false.</param>
        /// <returns>Boolean, true if members were removed from the selection</returns>
        bool ClearSelection(out Envelope affectedArea, bool force);

        /// <summary>
        /// Inverts the selected state of any members in the specified region.
        /// </summary>
        /// <param name="tolerant">The geographic region to invert the selected state of members</param>
        /// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
        /// <param name="mode">The selection mode determining how to test for intersection</param>
        /// <param name="affectedArea">The geographic region encapsulating the changed members</param>
        /// <returns>Boolean, true if members were changed by the selection process.</returns>
        bool InvertSelection(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea);

        /// <summary>
        /// Adds any members found in the specified region to the selected state as long as
        /// SelectionEnabled is set to true.
        /// </summary>
        /// <param name="tolerant">The geographic region where selection occurs</param>
        /// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
        /// <param name="mode">The selection mode</param>
        /// <param name="affectedArea">The envelope affected area</param>
        /// <param name="clear">Indicates whether prior selected features should be cleared.</param>
        /// <returns>Boolean, true if any members were added to the selection</returns>
        bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea, ClearStates clear);

        /// <summary>
        /// Removes any members found in the specified region from the selection
        /// </summary>
        /// <param name="tolerant">The geographic region to investigate</param>
        /// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
        /// <param name="mode">The selection mode to use for selecting items</param>
        /// <param name="affectedArea">The geographic region containing all the shapes that were altered</param>
        /// <returns>Boolean, true if any members were removed from the selection</returns>
        bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea);

        #endregion
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Ithaca, Ithaca Tompkins Regional Airport, NY</location>
	<station_id>KITH</station_id>
	<latitude>42.49083</latitude>
	<longitude>-76.45833</longitude>
	<observation_time>Last Updated on Jan 4 2016, 9:56 pm EST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 21:56:00 -0500</observation_time_rfc822>
	<weather>Overcast</weather>
	<temperature_string>7.0 F (-14.0 C)</temperature_string>
	<temp_f>7.0</temp_f>
	<temp_c>-14.0</temp_c>
	<relative_humidity>78</relative_humidity>
	<wind_string>North at 11.5 MPH (10 KT)</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>10</wind_degrees>
	<wind_mph>11.5</wind_mph>
	<wind_kt>10</wind_kt>
	<pressure_in>30.45</pressure_in>
	<dewpoint_string>1.4 F (-17.0 C)</dewpoint_string>
	<dewpoint_f>1.4</dewpoint_f>
	<dewpoint_c>-17.0</dewpoint_c>
	<windchill_string>-8 F (-22 C)</windchill_string>
      	<windchill_f>-8</windchill_f>
      	<windchill_c>-22</windchill_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KITH.html</two_day_history_url>
	<icon_url_name>novc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KITH.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Xerces-C++: DOMImplementationRegistry.hpp File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

DOMImplementationRegistry.hpp File Reference

Go to the source code of this file.

Classes

class  	DOMImplementationRegistry

Defines

#define 	XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONREGISTRY_HPP

Define Documentation

          #define XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONREGISTRY_HPP

<address style="text-align: right;">Generated on Wed Apr 21 17:55:49 2010 for Xerces-C++ by

 1.5.6 </address>


text:
package net.sf.esfinge.metadata.validate.prohibits;

import org.junit.Test;

import net.sf.esfinge.metadata.AnnotationValidationException;
import net.sf.esfinge.metadata.validate.MetadataValidator;

public class TestValidateProhibits<Purchase> {

	// CT01
	public class OrderProcessing01 {
		@Init @Finalize
		public void registerPurchase(Purchase p) {
		}
	}

	@Test(expected = AnnotationValidationException.class)
	public void CT01() throws AnnotationValidationException {
		MetadataValidator.validateMetadataOn(OrderProcessing01.class);
	}

	// CT02
	public class OrderProcessing02 {
		@Init
		public void registerPurchase() {
		}
	}

	@Test
	public void CT02() throws AnnotationValidationException {
		MetadataValidator.validateMetadataOn(OrderProcessing02.class);
	}

	// CT03
	@Finalize
	public class OrderProcessing03 {
		@Init
		public void registerPurchase(Purchase p) {
		}
	}

	@Test(expected = AnnotationValidationException.class)
	public void CT03() throws AnnotationValidationException {
		MetadataValidator.validateMetadataOn(OrderProcessing03.class);
	}

}


text:
The Kargo Project is released on an as-needed basis. The process is as follows:

1. An issue is proposing a new release with a changelog since the last release
2. At least on of the [OWNERS](OWNERS) must LGTM this release
3. An OWNER runs `git tag -s $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION`
4. The release issue is closed
5. An announcement email is sent to `kubernetes-dev@googlegroups.com` with the subject `[ANNOUNCE] kargo $VERSION is released`


text:
#pragma once

#include <unordered_map>

#include <glm/glm.hpp>
#include <glowl/glowl.h>

#include "Renderer2D.h"
#include "datatools/table/TableDataCall.h"
#include "mmcore/BoundingBoxes_2.h"
#include "mmcore/CalleeSlot.h"
#include "mmcore/CallerSlot.h"
#include "mmcore/Module.h"
#include "mmcore/param/ParamSlot.h"
#include "mmcore_gl/utility/SDFFont.h"
#include "mmstd/flags/FlagStorage.h"
#include "mmstd_gl/renderer/CallRender2DGL.h"
#include "mmstd_gl/renderer/Renderer2DModuleGL.h"

namespace megamol::infovis_gl {

class ParallelCoordinatesRenderer2D : public Renderer2D {
public:
    /**
     * Answer the name of this module.
     *
     * @return The name of this module.
     */
    static inline const char* ClassName() {
        return "ParallelCoordinatesRenderer2D";
    }

    /**
     * Answer a human readable description of this module.
     *
     * @return A human readable description of this module.
     */
    static inline const char* Description() {
        return "Parallel coordinates renderer for generic tables.\n"
               "Left-Click to pick/stroke\npress [Shift] to filter axis using the two delimiters (hats)\n"
               "press [Alt] to re-order axes";
    }

    /**
     * Answers whether this module is available on the current system.
     *
     * @return 'true' if the module is available, 'false' otherwise.
     */
    static inline bool IsAvailable() {
        return true;
    }

    /**
     * Initialises a new instance.
     */
    ParallelCoordinatesRenderer2D();

    /**
     * Finalises an instance.
     */
    ~ParallelCoordinatesRenderer2D() override;

protected:
    /**
     * Implementation of 'Create'.
     *
     * @return 'true' on success, 'false' otherwise.
     */
    bool create() override;

    /**
     * Implementation of 'Release'.
     */
    void release() override;

    /**
     * The get extents callback. The module should set the members of
     * 'call' to tell the caller the extents of its data (bounding boxes
     * and times).
     *
     * @param call The calling call.
     *
     * @return The return value of the function.
     */
    bool GetExtents(mmstd_gl::CallRender2DGL& call) override;

    /**
     * The OpenGL Render callback.
     *
     * @param call The calling call.
     *
     * @return The return value of the function.
     */
    bool Render(mmstd_gl::CallRender2DGL& call) override;

    bool OnMouseButton(
        core::view::MouseButton button, core::view::MouseButtonAction action, core::view::Modifiers mods) override;

    bool OnMouseMove(double x, double y) override;

protected:
    enum DrawMode {
        DRAW_DISCRETE = 0,
        DRAW_DENSITY,
    };

    enum SelectionMode {
        SELECT_PICK = 0,
        SELECT_STROKE,
    };

    enum InteractionState {
        NONE = 0,
        INTERACTION_DRAG,
        INTERACTION_FILTER,
        INTERACTION_SELECT,
    };

    struct Range {
        float min;
        float max;
    };

    bool assertData(mmstd_gl::CallRender2DGL& call);

    void calcSizes();

    int mouseXtoAxis(float x);

    void mouseToFilterIndicator(float x, float y, int& axis, int& index);

    bool useProgramAndBindCommon(std::unique_ptr<glowl::GLSLProgram> const& program);

    void doPicking(glm::vec2 pos, float pickRadius);

    void doStroking(glm::vec2 start, glm::vec2 end);

    void drawItemLines(uint32_t testMask, uint32_t passMask, bool useTf, glm::vec4 const& color);

    void drawDiscrete(bool useTf, glm::vec4 const& color, glm::vec4 selectedColor);

    void drawDensity(std::shared_ptr<glowl::FramebufferObject> const& fbo);

    void drawAxes(glm::mat4 ortho);

    void drawIndicatorPick(glm::vec2 pos, float pickRadius, glm::vec4 const& color);

    void drawIndicatorStroke(glm::vec2 start, glm::vec2 end, glm::vec4 const& color);

    void storeFilters();

    void loadFilters();

    // Slots
    core::CallerSlot dataSlot_;
    core::CallerSlot tfSlot_;
    core::CallerSlot readFlagsSlot_;
    core::CallerSlot writeFlagsSlot_;

    // Params
    core::param::ParamSlot drawModeParam_;
    core::param::ParamSlot normalizeDensityParam_;
    core::param::ParamSlot sqrtDensityParam_;
    core::param::ParamSlot triangleModeParam_;
    core::param::ParamSlot lineWidthParam_;
    core::param::ParamSlot dimensionNameParam_;
    core::param::ParamSlot useLineWidthInPixelsParam_;
    core::param::ParamSlot drawItemsParam_;
    core::param::ParamSlot drawSelectedItemsParam_;
    core::param::ParamSlot ignoreTransferFunctionParam_;
    core::param::ParamSlot itemsColorParam_;
    core::param::ParamSlot selectedItemsColorParam_;
    core::param::ParamSlot drawAxesParam_;
    core::param::ParamSlot axesLineWidthParam_;
    core::param::ParamSlot axesColorParam_;
    core::param::ParamSlot filterIndicatorColorParam_;
    core::param::ParamSlot smoothFontParam_;
    core::param::ParamSlot selectionModeParam_;
    core::param::ParamSlot pickRadiusParam_;
    core::param::ParamSlot drawSelectionIndicatorParam_;
    core::param::ParamSlot selectionIndicatorColorParam_;
    core::param::ParamSlot scaleToFitParam_;
    core::param::ParamSlot resetFiltersParam_;
    core::param::ParamSlot filterStateParam_;

    // Data Info
    std::size_t currentTableDataHash_;
    unsigned int currentTableFrameId_;

    std::size_t dimensionCount_;
    std::size_t itemCount_;
    std::vector<std::string> names_;
    std::vector<Range> dimensionRanges_;
    std::vector<int> axisIndirection_;
    std::unordered_map<std::string, int> dimensionIndex_;
    std::vector<Range> filters_;
    const std::array<uint32_t, 2> densityMinMaxInit_;

    std::unique_ptr<glowl::BufferObject> dataBuffer_;
    std::unique_ptr<glowl::BufferObject> dimensionRangesBuffer_;
    std::unique_ptr<glowl::BufferObject> axisIndirectionBuffer_;
    std::unique_ptr<glowl::BufferObject> filtersBuffer_;
    std::unique_ptr<glowl::BufferObject> densityMinMaxBuffer_;

    // Layout
    float marginX_;
    float marginY_;
    float axisDistance_;
    float axisHeight_;
    int numTicks_;
    float tickLength_;
    float fontSize_;
    megamol::core::utility::SDFFont font_;
    core::BoundingBoxes_2 bounds_;

    // Interaction state
    float mouseX_;
    float mouseY_;
    InteractionState interactionState_;
    int pickedAxis_;
    int pickedIndicatorAxis_;
    int pickedIndicatorIndex_;
    glm::vec2 strokeStart_;
    glm::vec2 strokeEnd_;
    bool needAxisUpdate_;
    bool needFilterUpdate_;
    bool needSelectionUpdate_;
    bool needFlagsUpdate_;

    // OpenGL
    std::unique_ptr<glowl::GLSLProgram> filterProgram_;
    std::unique_ptr<glowl::GLSLProgram> selectPickProgram_;
    std::unique_ptr<glowl::GLSLProgram> selectStrokeProgram_;
    std::unique_ptr<glowl::GLSLProgram> densityMinMaxProgram_;

    std::unique_ptr<glowl::GLSLProgram> drawItemsLineProgram_;
    std::unique_ptr<glowl::GLSLProgram> drawItemsTriangleProgram_;
    std::unique_ptr<glowl::GLSLProgram> drawItemsDensityProgram_;
    std::unique_ptr<glowl::GLSLProgram> drawAxesProgram_;
    std::unique_ptr<glowl::GLSLProgram> drawIndicatorPickProgram_;
    std::unique_ptr<glowl::GLSLProgram> drawIndicatorStrokeProgram_;

    std::array<GLint, 3> filterWorkgroupSize_;
    std::array<GLint, 3> selectPickWorkgroupSize_;
    std::array<GLint, 3> selectStrokeWorkgroupSize_;
    std::array<GLint, 3> densityMinMaxWorkgroupSize_;

    std::array<GLint, 3> maxWorkgroupCount_;

    std::unique_ptr<glowl::FramebufferObject> densityFbo_;

    // View and camera state
    std::optional<core::view::Camera> cameraCopy_;
    glm::ivec2 viewRes_;
};

} // namespace megamol::infovis_gl


text:
/* global describe, it */

var assert = require('assert');

describe('hypemachine / mp3 detector', function () {
  // var hypem = require('../../app/lib/hypem');

  // Wrapper to a controller that detects embeds (youtube + soundcloud) and MP3 files from a HTML page

  function ContentDetector() {
    console.logBackup = console.log;
    var controller =
      require('../../app/controllers/api/contentExtractor.js').controller;
    var fakeRequest = {
      logToConsole: function () {}, // eslint-disable-line @typescript-eslint/no-empty-function
      checkLogin: function () {
        return { id: 1, name: 'fake' };
      },
    };
    return {
      detect: function (url, title, cb) {
        var params = { url: url };
        if (title) params.title = title;
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        console.log = function () {}; // prevent controller from writing to stdout
        controller(fakeRequest, params, {
          render: function (r) {
            console.log = console.logBackup; // restore console.log
            cb(r);
          },
        });
      },
    };
  }

  // Tests

  /*
  function objToArray(results) {
    var array = [];
    for (let i in results) array.push(results[i]);
    return array;
  }

  function genSearchTest(q) {
    it(
      'finds a match on hypemachine from the title "' + q + '"',
      function (done) {
        //console.log('(hypem.search) query:', q, '...');
        hypem.search(q, function (err, results) {
          assert.ifError(err);
          assert(objToArray(results).length);
          done();
        });
      }
    );
  }

  function genSearchMp3Test(q) {
    it('finds a mp3 file from the title "' + q + '"', function (done) {
      //console.log('(hypem.searchMp3s) query:', q, '...');
      hypem.searchMp3s(q, function (err, results) {
        assert.ifError(err);
        assert(objToArray(results).length);
        done();
      });
    });
  }

  function genExtractMp3Test(url, title) {
    it('extracts the mp3 file from ' + url, function (done) {
      //console.log('(hypem.getMp3FromPostUrl) ', {url:url, title:title}, '...');
      hypem.getMp3FromPostUrl(url, title, function (err, mp3) {
        assert.ifError(err);
        assert(mp3);
        done();
      });
    });
  }
  */

  function genDetectTracksTest(url, title) {
    it('detects title of ' + url, function (done) {
      new ContentDetector().detect(url, title, function (r) {
        assert(r && r.embeds && r.embeds.join && r.embeds.length);
        //console.log("First result: ", r.embeds[0]);
        done();
      });
    });
  }

  // run tests

  /*
	genSearchTest('metronomy');
	genSearchMp3Test('metronomy');
	genExtractMp3Test('http://8106.tv/blog/2012/04/06/elegancia-presentado-por-smirnoff/', 'The Bay');
	genDetectTracksTest('http://8106.tv/blog/2012/04/06/elegancia-presentado-por-smirnoff/');
	genDetectTracksTest('http://8106.tv/blog/2012/04/06/elegancia-presentado-por-smirnoff/', 'The Bay');
	genDetectTracksTest('http://bib-on-the-sofa.blogspot.fr/2012/09/metronomy-tens-and-tens-theatre-of.html', 'Metronomy - Tens And Tens'); // one soundcloud embeds
	genDetectTracksTest('http://musicunderfire.com/2012/09/new-music-releases-for-tuesday-9252012.html', 'Metronomy - Corinne'); // multiple soundcloud embeds
	genDetectTracksTest('http://audioporncentral.com/2012/09/metronomy-hypnose-late-night-tales.html', 'Metronomy - Hypnose'); // one vimeo and 1 soundcloud embed
	*/
  genDetectTracksTest(
    'http://www.deadhorsemarch.com/video-metronomy-everything-goes-my-way-6-5-12/' /*, 'Metronomy – "Everything Goes My Way"'*/
  ); // 1 youtube video embed
  genDetectTracksTest(
    'http://www.deadhorsemarch.com/video-metronomy-everything-goes-my-way-6-5-12/',
    'Metronomy – "Everything Goes My Way"'
  ); // 1 youtube video embed

  // TODO: fix hypem module => re-enable all test cases
});


text:
auto_ssl = (require "resty.auto-ssl").new()

local redis = require "ceryx.redis"
local routes = require "ceryx.routes"

-- Define a function to determine which SNI domains to automatically handle
-- and register new certificates for. Defaults to not allowing any domains,
-- so this must be configured.
auto_ssl:set(
    "allow_domain",
    function(domain)
        local redisClient = redis:client()
        local host = domain
        local target = routes.getTargetForSource(host, redisClient)

        if target == nil then
            return target
        end

        return true
    end
)

-- Set the resty-auto-ssl storage to Redis, using the CERYX_* env variables
auto_ssl:set("storage_adapter", "resty.auto-ssl.storage_adapters.redis")
auto_ssl:set(
    "redis",
    {
        host = redis.host,
        port = redis.port
    }
)

auto_ssl:init()
require "resty.core"


text:
name: Support Request
about: Need help with HAP-NodeJS?
title: ''
labels: question
assignees: ''

---

<!-- If you have an issue with a plugin create an issue on that plugin's GitHub page instead. -->

<!-- Before opening an issue, please review the Troubleshooting Page on the Wiki to ensure that this is a new issue, and alternatively search the closed issues for similar problems. -->

<!-- Link to the the Wiki - https://github.com/homebridge/HAP-NodeJS/wiki -->

<!-- Provide a general summary in the Title above -->

**Describe Your Problem:**
<!-- A clear and concise description of what problem you are trying to solve. -->

**Logs:**
<!-- Paste relevant output between the two ``` lines below -->
<!-- Remove any sensitive information, passwords, etc. -->
<!-- Please include the beginning of the log where the HAP-NodeJS initialization happens -->

**Screenshots:**
<!-- If applicable, add screenshots to help explain your problem. -->

**Environment:**

* **Node.js Version**: <!-- node -v -->
* **NPM Version**: <!-- npm -v -->
* **Operating System**: Raspbian / Ubuntu / Debian / Windows / macOS / Docker / other
* **Process Supervisor**: Systemd / init.d / pm2 / launchctl / Docker / hb-service / other / none

<!-- Click the "Preview" tab before you submit to ensure the formatting is correct. -->


text:
package org.adligo.tests4j_tests.shared.asserts;

import org.adligo.tests4j.shared.asserts.UniformThrownAssertCommand;
import org.adligo.tests4j.shared.asserts.common.ExpectedThrowable;
import org.adligo.tests4j.shared.asserts.common.I_AssertionData;
import org.adligo.tests4j.shared.asserts.common.I_ExpectedThrowable;
import org.adligo.tests4j.shared.asserts.common.I_Thrower;
import org.adligo.tests4j.shared.asserts.common.I_ThrownAssertionData;
import org.adligo.tests4j.shared.asserts.common.MatchType;
import org.adligo.tests4j.shared.asserts.common.ThrownAssertionData;
import org.adligo.tests4j.shared.asserts.reference.AllowedReferences;
import org.adligo.tests4j.shared.asserts.uniform.I_Evaluation;
import org.adligo.tests4j.shared.asserts.uniform.UniformThrownAssertionEvaluator;
import org.adligo.tests4j.shared.en.Tests4J_EnglishConstants;
import org.adligo.tests4j.shared.i18n.I_Tests4J_AssertionInputMessages;
import org.adligo.tests4j.shared.i18n.I_Tests4J_ResultMessages;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_tests.base_trials.I_CountType;
import org.adligo.tests4j_tests.base_trials.SourceFileCountingTrial;
import org.adligo.tests4j_tests.references_groups.Tests4J_Asserts_GwtReferenceGroup;

@SourceFileScope (sourceClass=UniformThrownAssertCommand.class, minCoverage=76.0)
@AllowedReferences (groups=Tests4J_Asserts_GwtReferenceGroup.class)
public class UniformThrownAssertCommandTrial extends SourceFileCountingTrial {

	@Test
	@SuppressWarnings("unused")
	public void test01_ConstructorExceptions() {
		I_Tests4J_AssertionInputMessages messages = Tests4J_EnglishConstants.ENGLISH.getAssertionInputMessages();

		assertThrown(new ExpectedThrowable(new IllegalArgumentException(
				messages.getExpectedThrownDataRequiresThrowable())),
				new I_Thrower() {

          @Override
					public void run() {
						new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH,
						    "failure message", null, null);
					}
				});
		assertThrown(new ExpectedThrowable(new IllegalArgumentException(
				UniformThrownAssertCommand.UNIFORM_THROWN_ASSERT_COMMAND_REQUIRES_A_EVALUATOR)),
				new I_Thrower() {

					@Override
					public void run() {
						new UniformThrownAssertCommand(
						    Tests4J_EnglishConstants.ENGLISH, "failure message",
								new ExpectedThrowable(new IllegalArgumentException("failure message")), null);
					}
				});
		assertThrown(new ExpectedThrowable(new IllegalArgumentException(
        messages.getThrownUniformExpectedThrownDataMustBeMatchTypeAnyEqualsOrNull())),
        new I_Thrower() {

          @Override
          public void run() {
            new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message",
                new ExpectedThrowable(new IllegalArgumentException("failure message"),
                    new ExpectedThrowable(new IllegalArgumentException("mnn"), MatchType.CONTAINS)),
                new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
          }
        });
	}

	@SuppressWarnings("boxing")
  @Test
	public void test02_EqualsHashCode() {
		UniformThrownAssertionEvaluator tue = new UniformThrownAssertionEvaluator(
		    Tests4J_EnglishConstants.ENGLISH);
		UniformThrownAssertCommand a =
				new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message",
				new ExpectedThrowable(new IllegalArgumentException("expected exception messsage")), tue);
		UniformThrownAssertCommand b =
				new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message 2",
				new ExpectedThrowable(new IllegalArgumentException("expected exception messsage")), tue);
		UniformThrownAssertCommand c =
				new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message",
				new ExpectedThrowable(new IllegalArgumentException("expected exception messsage")), tue);
		UniformThrownAssertCommand d =
				new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message",
				new ExpectedThrowable(new IllegalStateException("expected exception messsage")), tue);
		UniformThrownAssertCommand e =
				new UniformThrownAssertCommand(Tests4J_EnglishConstants.ENGLISH, "failure message",
				new ExpectedThrowable(new IllegalStateException("expected exception messsage")), tue);

		assertEquals(a, a);
		assertEquals(a.hashCode(), a.hashCode());

		assertNotEquals(a, b);
		assertNotEquals(a.hashCode(), b.hashCode());

		assertEquals(a, c);
		assertEquals(a.hashCode(), c.hashCode());

		assertTrue(c.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw new IllegalArgumentException("expected exception messsage");
			}
		}));
		assertNotEquals(a, c);
		assertNotEquals(a.hashCode(), c.hashCode());

		assertNotEquals(a, d);
		assertNotEquals(a.hashCode(),d.hashCode());

		assertNotEquals(a, e);
		assertNotEquals(a.hashCode(), e.hashCode());
	}

	@Test
	public void test03_GettersBeforeEvaluate() {
		IllegalArgumentException iae = new IllegalArgumentException("expected exception messsage");
		ExpectedThrowable etd = new ExpectedThrowable(iae);
		final UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH,
				    "failure message", etd, new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertThrown(new ExpectedThrowable(NullPointerException.class),
				new I_Thrower() {

					@Override
					public void run() {
						utac.getData();
					}
				});
	}

	@SuppressWarnings("boxing")
  @Test
	public void test04_GettersAfterEvaluateFailNothingThrown() {

		ExpectedThrowable etd = new ExpectedThrowable(new IllegalArgumentException("bad exeception message\n\r"
				+ "123"));
		UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH,
				    "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
			}
		}));

		I_AssertionData data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		ThrownAssertionData tad = (ThrownAssertionData) data;

		I_ExpectedThrowable expected = tad.getExpected();
		Throwable actual = tad.getActual();
		assertNull(actual);
		assertEquals(IllegalArgumentException.class, expected.getThrowableClass());
		assertEquals("bad exeception message\n\r123", expected.getMessage());

		I_Tests4J_ResultMessages messges = Tests4J_EnglishConstants.ENGLISH.getResultMessages();

		assertEquals(messges.getNothingWasThrown(), tad.getFailureReason());
		assertEquals(1, tad.getFailureThrowable());
	}

	@SuppressWarnings("boxing")
  @Test
	public void test05_EvaluatePass() {
		final IllegalArgumentException iae = new IllegalArgumentException("expected exception messsage");
		ExpectedThrowable etd = new ExpectedThrowable(iae);
		final UniformThrownAssertCommand utac = new UniformThrownAssertCommand(
		    Tests4J_EnglishConstants.ENGLISH, "failure message", etd,
		    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());

		assertThrown(new ExpectedThrowable(NullPointerException.class),
				new I_Thrower() {

					@Override
					public void run() {
						utac.getData();
					}
				});
		assertTrue(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae;
			}
		}));
		I_Evaluation<I_ThrownAssertionData> eval =  utac.getEvaluation();
		assertTrue(eval.isSuccess());
		I_ThrownAssertionData data = eval.getData();
		assertNotNull(data);
		assertNull(data.getFailureReason());
		assertEquals(0, data.getFailureThrowable());
		Throwable actual = data.getActual();
		assertNotNull(actual);
		assertEquals(IllegalArgumentException.class.getName(), actual.getClass().getName());
		assertSame(etd, data.getExpected());
		assertSame(data, utac.getData());

	}

	@SuppressWarnings("boxing")
  @Test
	public void test06_GettersAfterEvaluateFailClassMismatch() {
		final IllegalStateException iae = new IllegalStateException("expected exception messsage\n"
				+ "123");
		ExpectedThrowable etd = new ExpectedThrowable(new IllegalArgumentException("expected exeception message\n\r"
				+ "123"));
		UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH, "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae;
			}
		}));

		I_AssertionData data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		ThrownAssertionData tad = (ThrownAssertionData) data;

		I_ExpectedThrowable expected = tad.getExpected();
		Throwable actual = tad.getActual();
		assertEquals(IllegalStateException.class, actual.getClass());
		assertEquals("expected exception messsage\n123", actual.getMessage());
		assertEquals(IllegalArgumentException.class, expected.getThrowableClass());
		assertEquals("expected exeception message\n\r123", expected.getMessage());

		I_Tests4J_ResultMessages messges = Tests4J_EnglishConstants.ENGLISH.getResultMessages();

		assertEquals(messges.getThrowableClassMismatch(), tad.getFailureReason());
		assertEquals(1, tad.getFailureThrowable());
	}

	@SuppressWarnings("boxing")
  @Test
	public void test07_GettersAfterEvaluateFailTextNotUniform() {
		final IllegalArgumentException iae = new IllegalArgumentException("expected exception messsage\n"
				+ "123");
		ExpectedThrowable etd = new ExpectedThrowable(new IllegalArgumentException("bad exeception message\n\r"
				+ "123"));
		UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH, "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae;
			}
		}));

		I_AssertionData data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		ThrownAssertionData tad = (ThrownAssertionData) data;

		I_ExpectedThrowable expected = tad.getExpected();
		Throwable actual = tad.getActual();
		assertEquals(IllegalArgumentException.class, actual.getClass());
		assertEquals("expected exception messsage\n123", actual.getMessage());
		assertEquals(IllegalArgumentException.class, expected.getThrowableClass());
		assertEquals("bad exeception message\n\r123", expected.getMessage());

		I_Tests4J_ResultMessages messges = Tests4J_EnglishConstants.ENGLISH.getResultMessages();

		assertEquals(messges.getThrowableMessageNotUniform(), tad.getFailureReason());
		assertEquals(1, tad.getFailureThrowable());
	}

	@SuppressWarnings("boxing")
  @Test
	public void test08_GettersAfterEvaluateFailClassMismatchDeep() {
		final IllegalArgumentException iae = new IllegalArgumentException("message");
		iae.initCause(new NullPointerException());
		ExpectedThrowable etd = new ExpectedThrowable(new IllegalArgumentException("message"),
				new ExpectedThrowable(IllegalStateException.class));
		UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH, "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae;
			}
		}));

		I_AssertionData data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		ThrownAssertionData tad = (ThrownAssertionData) data;
		I_Tests4J_ResultMessages messges = Tests4J_EnglishConstants.ENGLISH.getResultMessages();

		assertEquals(messges.getThrowableClassMismatch(), tad.getFailureReason());
		assertEquals(2, tad.getFailureThrowable());

		final IllegalArgumentException iae2 = new IllegalArgumentException("message");
		IllegalStateException x = new IllegalStateException();
		x.initCause(new NullPointerException());
		iae2.initCause(x);
		etd = new ExpectedThrowable(new IllegalArgumentException("message"),
				new ExpectedThrowable(IllegalStateException.class,
				new ExpectedThrowable(IllegalArgumentException.class)));
		utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH, "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae2;
			}
		}));

		data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		tad = (ThrownAssertionData) data;
		assertEquals(messges.getThrowableClassMismatch(), tad.getFailureReason());
		assertEquals(3, tad.getFailureThrowable());
	}

	@SuppressWarnings("boxing")
  @Test
	public void test09_GettersAfterEvaluateFailTextNotUniformDeep() {
		final IllegalArgumentException iae = new IllegalArgumentException("message");
		iae.initCause(new NullPointerException("npe\n2"));
		ExpectedThrowable etd = new ExpectedThrowable(new IllegalArgumentException("message"),
				new ExpectedThrowable(new NullPointerException("npe\n1")));
		UniformThrownAssertCommand utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH,  "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae;
			}
		}));

		I_AssertionData data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		ThrownAssertionData tad = (ThrownAssertionData) data;
		I_Tests4J_ResultMessages messges = Tests4J_EnglishConstants.ENGLISH.getResultMessages();

		assertEquals(messges.getThrowableMessageNotUniform(), tad.getFailureReason());
		assertEquals(2, tad.getFailureThrowable());

		final IllegalArgumentException iae2 = new IllegalArgumentException("message");
		IllegalStateException x = new IllegalStateException("state message");
		x.initCause(new NullPointerException("neo"));
		iae2.initCause(x);
		etd = new ExpectedThrowable(new IllegalArgumentException("message"),
				new ExpectedThrowable(new IllegalStateException("state message"),
				new ExpectedThrowable(new NullPointerException("npe"))));
		utac = new UniformThrownAssertCommand
				(Tests4J_EnglishConstants.ENGLISH, "failure message",  etd,
				    new UniformThrownAssertionEvaluator(Tests4J_EnglishConstants.ENGLISH));
		assertEquals("failure message", utac.getFailureMessage());
		assertFalse(utac.evaluate(new I_Thrower() {

			@Override
			public void run() {
				throw iae2;
			}
		}));

		data = utac.getData();
		assertNotNull(data);
		assertTrue(data instanceof ThrownAssertionData);
		tad = (ThrownAssertionData) data;
		assertEquals(messges.getThrowableMessageNotUniform(), tad.getFailureReason());
		assertEquals(3, tad.getFailureThrowable());
	}

	@Override
	public int getTests(I_CountType type) {
		return super.getTests(type, 9, true);
	}

	@Override
	public int getAsserts(I_CountType type) {
		int thisAsserts = 82;
		if (type.isFromMetaWithCoverage()) {
			//code coverage and circular dependencies +
			//custom afterTrialTests
			return super.getAsserts(type, thisAsserts + 3);
		} else {
			return super.getAsserts(type, thisAsserts);
		}
	}

	@Override
	public int getUniqueAsserts(I_CountType type) {
		int thisUniqueAsserts = 64;
		if (type.isFromMetaWithCoverage()) {
			return super.getUniqueAsserts(type, thisUniqueAsserts + 3);
		}  else {
			return super.getAsserts(type, thisUniqueAsserts);
		}
	}
}


text:
// @TODO Add Javadoc comments

// @TODO Catch Exceptions thrown by IDGeneratorPart, then
// reflect this in the corresponding BaseIDGeneratorTest class.

package org.collectionspace.services.id;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * BaseIDGenerator
 *
 * Models an identifier (ID) generator, consisting of
 * multiple IDGeneratorParts.
 *
 * $LastChangedRevision$
 * $LastChangedDate$
 */
public class BaseIDGenerator implements IDGenerator {

    protected Vector<IDGeneratorPart> parts = new Vector<IDGeneratorPart>();

    final static int MAX_ID_LENGTH = 50;

    /**
     * Constructor (no argument)
      */
    public BaseIDGenerator() {
    }

    /**
     * Constructor.
     *
     * @param parts A collection of ID generator parts.
     */
    public BaseIDGenerator(Vector<IDGeneratorPart> parts) {
        if (parts != null) {
            this.parts = parts;
        }
    }

    /**
     * Adds a single ID generator part.
     *
     * @param part  An ID generator part.
     */
    public void add(IDGeneratorPart part) {
        if (part != null) {
            this.parts.add(part);
        }
    }

    /**
     * Removes all ID generator parts.
     */
    public void clear() {
        this.parts.clear();
    }

    @Override
    public String getCurrentID() {
        StringBuffer sb = new StringBuffer(MAX_ID_LENGTH);
        for (IDGeneratorPart part : this.parts) {
            sb.append(part.getCurrentID());
        }
        return sb.toString();
    }

    @Override
    public String newID() throws IllegalStateException {

        int lastPartNum = this.parts.size();
        StringBuffer sb = new StringBuffer(MAX_ID_LENGTH);
        int i = 0;
        for (IDGeneratorPart part : this.parts) {
        	i++;
        	if (i < lastPartNum) {
            	sb.append(part.getCurrentID());
           	} else {
           		sb.append(part.newID());
           	}
        }

        return sb.toString();

    }

    @Override
    public boolean isValidID(String id) {
        return isValidID(id, getRegex());
    }

   /**
     * Validates a supplied ID against the format of the IDs
     * generated by this ID generator.
     *
     * @param    id    An ID.
     *
     * @param    regex  A regular expression for validating IDs against
     *                  a format.
     *
     * @return   true if the supplied ID matches the format of the
     *           IDs generated by this ID generator;
     *           false if it does not match that format.
      */
    public boolean isValidID(String id, String regex) {

        if (id == null) {
            return false;
        }

        // @TODO May potentially throw at least one pattern-related exception.
        // We'll need to catch and handle this here, as well as in all
        // derived classes and test cases that invoke validation.

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(id);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public String getRegex() {
        StringBuffer sb = new StringBuffer();
        for (IDGeneratorPart part : this.parts) {
            sb.append(part.getRegex());
        }
        return sb.toString();
    }

}


text:
require 'vcr'

VCR.configure do |c|
  c.hook_into        :webmock
  c.ignore_localhost = true
end


text:
import * as Immutable from "immutable";
import { v4 as uuid } from "uuid";

export type ExecutionCount = number | null;

// Mutable JSON types
export type PrimitiveImmutable = string | number | boolean | null;
export type JSONType = PrimitiveImmutable | JSONObject | JSONArray;
export interface JSONObject {
  [key: string]: JSONType;
}
export type JSONArray = Array<JSONType>

export type CellId = string;
export function createCellId(): CellId {
  return uuid();
}

// On disk multi-line strings are used to accomodate line-by-line diffs in tools
// like git and GitHub. They get converted to strings for the in-memory format.
export type MultiLineString = string | string[];

/**
 * A mime-type keyed dictionary of data.
 * See https://nbformat.readthedocs.io/en/latest/format_description.html#cell-attachments for docs
 * and https://github.com/jupyter/nbformat/blob/b23aad6e29d8c3909a1b04a7edc9ae541096dc7b/nbformat/v4/nbformat.v4.schema.json#L442
 * for the schema
 */
 export interface MimeBundle<TPayload = string> {
  [mime_type: string]: TPayload;
}

export type ImmutableJSONType =
  | PrimitiveImmutable
  | ImmutableJSONMap
  | ImmutableJSONList;

// Can't (easily) write circularly referenced types so this'll have to do for
// now
export type ImmutableJSONMap = Immutable.Map<string, any>;
export type ImmutableJSONList = Immutable.List<any>;

// tslint:disable:max-line-length
/**
 * Media Bundles as they exist on disk from the notebook format
 * See https://nbformat.readthedocs.io/en/latest/format_description.html#display-data for docs
 * and https://github.com/jupyter/nbformat/blob/master/nbformat/v4/nbformat.v4.schema.json for the schema
 */
// tslint:enable:max-line-length
export interface OnDiskMediaBundle {
  "text/plain"?: MultiLineString;
  "text/html"?: MultiLineString;
  "text/latex"?: MultiLineString;
  "text/markdown"?: MultiLineString;
  "application/javascript"?: MultiLineString;
  "image/png"?: MultiLineString;
  "image/jpeg"?: MultiLineString;
  "image/gif"?: MultiLineString;
  "image/svg+xml"?: MultiLineString;

  // The JSON mimetype has some corner cases because of the protocol / format
  // assuming the values in a media bundle are either:
  //
  //   * A string; which would be deserialized
  //   * An array; which would have to be assumed to be a multiline string
  //
  "application/json"?: string | string[] | {};
  "application/vdom.v1+json"?: {};
  "application/vnd.dataresource+json"?: {};
  "text/vnd.plotly.v1+html"?: MultiLineString | {};
  "application/vnd.plotly.v1+json"?: {};
  "application/geo+json"?: {};
  "application/x-nteract-model-debug+json"?: {};
  "application/vnd.vega.v2+json"?: {};
  "application/vnd.vega.v3+json"?: {};
  "application/vnd.vega.v4+json"?: {};
  "application/vnd.vega.v5+json"?: {};
  "application/vnd.vegalite.v1+json"?: {};
  "application/vnd.vegalite.v2+json"?: {};
  "application/vnd.vegalite.v3+json"?: {};
  "application/vnd.vegalite.v4+json"?: {};

  [key: string]: string | string[] | {} | undefined;
}

// Enumerating over all the media types we currently accept
export interface MediaBundle {
  "text/plain"?: string;
  "text/html"?: string;
  "text/latex"?: string;
  "text/markdown"?: string;
  "application/javascript"?: string;
  "image/png"?: string;
  "image/jpeg"?: string;
  "image/gif"?: string;
  "image/svg+xml"?: string;
  // All our JSON types can only be JSON Objects
  "application/json"?: { [key: string]: any };
  "application/vdom.v1+json"?: { [key: string]: any };
  "application/vnd.dataresource+json"?: { [key: string]: any };
  "text/vnd.plotly.v1+html"?: string | { [key: string]: any };
  "application/vnd.plotly.v1+json"?: { [key: string]: any };
  "application/geo+json"?: { [key: string]: any };
  "application/x-nteract-model-debug+json"?: { [key: string]: any };
  "application/vnd.vega.v2+json"?: { [key: string]: any };
  "application/vnd.vega.v3+json"?: { [key: string]: any };
  "application/vnd.vega.v4+json"?: { [key: string]: any };
  "application/vnd.vega.v5+json"?: { [key: string]: any };
  "application/vnd.vegalite.v1+json"?: { [key: string]: any };
  "application/vnd.vegalite.v2+json"?: { [key: string]: any };
  "application/vnd.vegalite.v3+json"?: { [key: string]: any };
  "application/vnd.vegalite.v4+json"?: { [key: string]: any };
  // Other media types can also come in that we don't recognize
  [key: string]: string | string[] | {} | undefined;
}

/**
 * Turn nbformat multiline strings (arrays of strings for simplifying diffs)
 * into strings
 */
export function demultiline(s: string | string[]): string {
  if (Array.isArray(s)) {
    return s.join("");
  }
  return s;
}

/**
 * Split string into a list of strings delimited by newlines; useful for on-disk
 * git comparisons; and is the expectation for jupyter notebooks on disk
 */
export function remultiline(s: string | string[]): string[] {
  if (Array.isArray(s)) {
    // Assume already multiline string
    return s;
  }
  // Split on newline and retain newline char
  return s.split(/(.*?(?:\r\n|\n))/g).filter(x => x !== "");
}

function isJSONKey(key: string): boolean {
  return /^application\/(.*\+)json$/.test(key);
}

// A type with all ownPropertyNames also readonly; works for all JSON types
type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> };

// tslint:disable-next-line:max-line-length
// Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
export function deepFreeze<T>(object: T): DeepReadonly<T> {
  // Retrieve the property names defined on object
  const propNames = Object.getOwnPropertyNames(object);

  // Freeze properties before freezing self
  for (const name of propNames) {
    // getOwnPropertyNames assures us we can index on name
    const value = (object as any)[name];

    (object as any)[name] =
      value && typeof value === "object" ? deepFreeze(value) : value;
  }

  return (Object.freeze(object) as unknown) as DeepReadonly<T>;
}

const IS_VEGA = /^application\/vnd.vega(.*\+)json$/;

export function createFrozenMediaBundle(
  mediaBundle: OnDiskMediaBundle
): Readonly<MediaBundle> {
  // Map over all the mimetypes; turning them into our in-memory format
  //
  // {
  //   "application/json": {"a": 3; "b": 2};
  //   "text/html": ["
\n"; "Hey\n"; "
"];
  //   "text/plain": "Hey"
  // }
  //
  // to
  //
  // {
  //   "application/json": {"a": 3; "b": 2};
  //   "text/html": "
\nHey\n
";
  //   "text/plain": "Hey"
  // }

  // Since we have to convert from one type to another that has conflicting
  // types; we need to hand convert it in a way that flow is able to verify
  // correctly.
  // FIXME: Is above comment still valid with the move from flow to ts?
  //
  // The way we do that is create a new object that we declare with the type
  // we want; set the keys and values we need; then seal the object with
  // Object.freeze
  const bundle: MediaBundle = {};

  for (const key in mediaBundle) {
    if (IS_VEGA.test(key)) {
      bundle[key] = JSON.stringify(mediaBundle[key]);
    } else if (typeof mediaBundle[key] === "string") {
      // Strings are immutable and can be just taken as-is.
      //
      // N.B.: This is even true of strings sent directly as the JSON root
      // object -- which Bokeh's output_notebook() is known to do -- so we
      // have to check for them even in the JSON case, as deepFreeze will fail
      // on strings.
      bundle[key] = mediaBundle[key] as string;
    } else if (!isJSONKey(key) && Array.isArray(mediaBundle[key])) {
      bundle[key] = demultiline(mediaBundle[key] as MultiLineString);
    } else {
      // we now know it's an Object of some kind (or a JSON array)
      bundle[key] = deepFreeze(mediaBundle[key]!);
    }
  }

  return Object.freeze(bundle);
}

export function createOnDiskMediaBundle(
  mediaBundle: Readonly<MediaBundle>
): OnDiskMediaBundle {
  // Return the bundle as is
  return mediaBundle;

  // The remultiline function in the code below is costly when the data payload is large
  // TODO: figure out a configurable way to reformat the string when needed.

  // However for the sake of on-disk readability we write out remultilined
  // versions of the array and string ones
  // const freshBundle: OnDiskMediaBundle = {};
  // for (const key in mediaBundle) {
  //   if (IS_VEGA.test(key)) {
  //     freshBundle[key] = JSON.parse(mediaBundle[key] as string);
  //   } else if (
  //     !isJSONKey(key) &&
  //     (typeof mediaBundle[key] === "string" || Array.isArray(mediaBundle[key]))
  //   ) {
  //     freshBundle[key] = remultiline(mediaBundle[key] as MultiLineString);
  //   } else {
  //     freshBundle[key] = mediaBundle[key];
  //   }
  // }
  // return freshBundle;
}