text:
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

(async function() {
  TestRunner.addResult(`Tests that WebInspector.CSSStyleSheet methods work as expected.\n`);
  await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner');
  await TestRunner.showPanel('elements');
  await TestRunner.loadHTML(`

Inspect Me

    `);

  ElementsTestRunner.nodeWithId('inspected', nodeFound);

  async function nodeFound(node) {
    var response = await TestRunner.CSSAgent.invoke_getMatchedStylesForNode({nodeId: node.id});
    if (response.getError()) {
      TestRunner.addResult('Failed to get styles: ' + response.getError());
      return;
    }
    ElementsTestRunner.dumpRuleMatchesArray(response.matchedCSSRules);
    TestRunner.completeTest();
  }
})();


text:
import csv

from ofxstatement.plugin import Plugin
from ofxstatement.parser import CsvStatementParser
from ofxstatement.statement import StatementLine

class FrankfurterSparkasse1822Plugin(Plugin):
    def get_parser(self, filename):
        encoding = self.settings.get('charset', 'iso-8859-1')
        with open(filename, 'r', encoding=encoding) as f:
            lines = f.readlines()
        parser = FrankfurterSparkasse1822Parser(lines)
        parser.statement.account_id = self.settings['account']
        parser.statement.bank_id = self.settings.get('bank', '50050201')
        parser.statement.currency = self.settings.get('currency', 'EUR')
        return parser

class FrankfurterSparkasse1822Parser(CsvStatementParser):
    """
    This plugin tries to parse the provided CSV data into the same
    format, as the discontinued OFX export
    """
    date_format = "%d.%m.%Y"

    def split_records(self):
        return csv.reader(self.fin, delimiter=';')

    def parse_float(self, f):
        """ convert a number in german localization (e.g. 1.234,56) to float """
        return float(f.replace('.', '').replace(',', '.'))

    def parse_record(self, line):
        # FIXME: add header validation
        if self.cur_record < 2:
            return None
        if len(line) < 3:
            """e.g.: ['# 1 vorgemerkte Umsätze nicht angezeigt']"""
            return None
        if not line[2]:
            return None
        sl = StatementLine()
        sl.id = line[1]
        sl.date = self.parse_datetime(line[2])
        sl.amount = self.parse_float(line[4])
        sl.trntype = 'DEBIT' if sl.amount < 0 else 'CREDIT'
        sl.payee = line[7]
        # check for special transactions
        if line[6] == "Entgeltabschluss":
            sl.memo = "%s: %s %s" % (line[6], line[13], line[14])
        elif line[6] == "Wertpapiere" or line[7] == "KREDITKARTENABRECHNUNG":
            sl.memo = "(%s/%s): %s" % (line[8], line[9], " ".join(line[15:]).strip())
        elif not line[8] and not line[9]:
            # empty transaction
            print("empty", line)
            return None
        else:
            sl.memo = "(%s/%s): %s" % (line[8], line[9], " ".join(e for e in line[13:] if e).strip())

        return sl

redpajama_set_name: RedPajamaGithub


text:
package info.novatec.testit.webtester.testng.listener.internal;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import info.novatec.testit.webtester.api.config.Configuration;
import info.novatec.testit.webtester.config.DefaultConfigurationBuilder;
import info.novatec.testit.webtester.testng.annotations.ConfigurationValue;

import org.apache.commons.lang.IllegalClassException;

import org.testng.annotations.Test;

public class ConfigurationValueInjectorTest {

    Configuration configuration = DefaultConfigurationBuilder.create();

    @Test
    public void testInstanceFieldInjection() {

        TestClassForInstance testClass = new TestClassForInstance();
        ConfigurationValueInjector.inject(configuration, testClass);

        assertThat(testClass.stringValue, is("foo bar"));
        assertThat(testClass.integerValue, is(1));
        assertThat(testClass.longValue, is(2L));
        assertThat(testClass.floatValue, is(1.0f));
        assertThat(testClass.doubleValue, is(2.0d));
        assertThat(testClass.booleanValue, is(true));

    }

    @Test
    public void testStaticFieldInjection() {

        ConfigurationValueInjector.injectStatics(configuration, TestClassForStatics.class);

        assertThat(TestClassForStatics.stringValue, is("foo bar"));
        assertThat(TestClassForStatics.integerValue, is(1));
        assertThat(TestClassForStatics.longValue, is(2L));
        assertThat(TestClassForStatics.floatValue, is(1.0f));
        assertThat(TestClassForStatics.doubleValue, is(2.0d));
        assertThat(TestClassForStatics.booleanValue, is(true));

    }

    @Test(expectedExceptions = IllegalClassException.class)
    public void testThatUnmappedFieldTypesLeadToException() {

        TestClassForException testClass = new TestClassForException();
        ConfigurationValueInjector.inject(configuration, testClass);

    }

    public static class TestClassForInstance {

        @ConfigurationValue("test.string")
        String stringValue;

        @ConfigurationValue("test.integer")
        Integer integerValue;

        @ConfigurationValue("test.long")
        Long longValue;

        @ConfigurationValue("test.float")
        Float floatValue;

        @ConfigurationValue("test.double")
        Double doubleValue;

        @ConfigurationValue("test.boolean")
        Boolean booleanValue;

    }

    public static class TestClassForStatics {

        @ConfigurationValue("test.string")
        static String stringValue;

        @ConfigurationValue("test.integer")
        static Integer integerValue;

        @ConfigurationValue("test.long")
        static Long longValue;

        @ConfigurationValue("test.float")
        static Float floatValue;

        @ConfigurationValue("test.double")
        static Double doubleValue;

        @ConfigurationValue("test.boolean")
        static Boolean booleanValue;

    }

    public static class TestClassForException {

        @ConfigurationValue("unknownClass")
        Object stringValue;

    }

}


text:
NSLog(@"[VZ]-->" fmt, ## __VA_ARGS__); \

#define VZErrorDomain @"TVZErrorDomain"

#define kMethodNameError 999
#define kParseJSONError 998
#define kLoginError 997
#define kRequestTimeout 996
#define kAFNetworkingError 995

#endif


text:
var test = require("tape")

var cliLess = require("../index")

test("cliLess is a function", function (assert) {
    assert.equal(typeof cliLess, "function")
    assert.end()
})


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES1 import _types as _cs
# End users want this...
from OpenGL.raw.GLES1._types import *
from OpenGL.raw.GLES1 import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GLES1_OES_single_precision'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GLES1,'GLES1_OES_single_precision',error_checker=_errors._error_checker)

@_f
@_p.types(None,_cs.GLclampf)
def glClearDepthfOES(depth):pass
@_f
@_p.types(None,_cs.GLenum,arrays.GLfloatArray)
def glClipPlanefOES(plane,equation):pass
@_f
@_p.types(None,_cs.GLclampf,_cs.GLclampf)
def glDepthRangefOES(n,f):pass
@_f
@_p.types(None,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat)
def glFrustumfOES(l,r,b,t,n,f):pass
@_f
@_p.types(None,_cs.GLenum,arrays.GLfloatArray)
def glGetClipPlanefOES(plane,equation):pass
@_f
@_p.types(None,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat)
def glOrthofOES(l,r,b,t,n,f):pass


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>ASTXmlExpression xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" />

View Javadoc

1   package net.sourceforge.pmd.lang.ecmascript.ast;
2
3   import org.mozilla.javascript.ast.XmlExpression;
4
5   public class ASTXmlExpression extends AbstractEcmascriptNode<XmlExpression> {
6       public ASTXmlExpression(XmlExpression xmlExpression) {
7   	super(xmlExpression);
8       }
9
10      /**
11       * Accept the visitor.
12       */
13      public Object jjtAccept(EcmascriptParserVisitor visitor, Object data) {
14  	return visitor.visit(this, data);
15      }
16
17      public EcmascriptNode getExpression() {
18  	return (EcmascriptNode) jjtGetChild(0);
19      }
20
21      public boolean isXmlAttribute() {
22  	return node.isXmlAttribute();
23      }
24  }

This page was automatically generated by Maven


text:
*What's needed*

The basic items needed for developing in Common Lisp are:

- A Lisp "Implementation", which will allow you to compile and execute code, as well as supply a REPL.
- A Text editor with facilities for Lisp code.
- (Nice to have) The often-used reference for the Common Lisp language, the "Common Lisp Hyperspec", available online [here](http://www.lispworks.com/documentation/HyperSpec/Front/Contents.htm)

*Fast Start*

Newbies to CL, particularly ones with previous experience with Emacs, can get an easy & quick start by installing Portacle, the Portable Common Lisp Environment. Free and full featured, it works in all common platforms and comes pre-configured "out of the box". This will supply:

- A Lisp implementation: SBCL, including Quicklisp and ASDF.
- A Text editor: Emacs
... with lots of add-ons for writing with Lisp code:
- SLIME, the "Superior Lisp Interaction Mode for Emacs" turns Emacs into a Common Lisp IDE
- ParEdit, which makes working with parentheses easy.

Everything comes already configured out of the box. Install Portacle by downloading from the [front page](https://portacle.github.io/)

Note: Emacs (text editor) can be disorienting at first, if you're not accustomed to it. Fortunately there are many primers on Emacs and SLIME available online.

*Traditional Start*

If you prefer installing components separately, besides installing your favorite editor for Lisp code, these would be the steps:

Install a lisp implementation such as [SBCL](http://www.sbcl.org/)
or [CLisp](http://clisp.org/). Both can be installed via Homebrew on
Mac OS X.

```bash
brew install sbcl
# or
brew install clisp
```

See their homepages for instructions for installing on other
platforms.

We will use [QuickLisp](http://www.quicklisp.org/beta/#installation) for Lisp library management. To install QuickLisp:

```bash
curl -O http://beta.quicklisp.org/quicklisp.lisp
```

Now launch lisp, and copy-paste the following expressions to finish QuickLisp installation:

```lisp
> (load "quicklisp.lisp")         ;; this will load the downloaded lisp file
> (quicklisp-quickstart:install)  ;; this will install quicklisp
> (ql:add-to-init-file)           ;; this will add quicklisp setup to your init file (recommended)
```

See the documentation of your lisp implementation on how to load quicklisp.lisp into lisp.

Optionally load lisp-unit:

```lisp
(ql:quickload "lisp-unit")
```

This will be done the first time you run any exercises tests. But you
can do it now if you want.


text:
<?php

use \Reshi\Constraints\HasCount;

class HasCountTest extends PHPUnit_Framework_TestCase
{
    protected $hasCount;

    protected function setUp()
    {
        $this->hasCount = new HasCount(3);
    }
    public function testEvaluate()
    {
        $this->assertTrue($this->hasCount->evaluate(array(1,2,3)), "Failed to assert that the array is of the expected size");
        $this->assertFalse($this->hasCount->evaluate(array(1)), "Failed to assert that the array is not of the expected size");
    }

    public function testGetName()
    {
        $this->assertEquals($this->hasCount->getName(), "HAS_COUNT", "Failed to assert COUNT is the constraint name.");
    }
}


text:
curator-extensions
==================

Helpers that extend the functionality of curator.

New Recipes
===========

```xml
<dependency>
    <groupId>com.bazaarvoice.curator</groupId>
    <artifactId>recipes</artifactId>
</dependency>
```

PersistentEphemeralNode
-----------------------

Ensures that as long as you have a connection to ZooKeeper that your ephemeral node stays around.

This recipe prevents node loss from:
- connection and session interruptions
- accidental deletion

NodeDiscovery
-------------

Works on top of ```PathChildrenCache``` to automatically parse the data portion of the node and notify listeners. See
```NodeDiscovery.NodeDataParser``` and ```NodeDiscovery.NodeListener``` for more info.

Easy Dropwizard Integration
===========================

```xml
<dependency>
    <groupId>com.bazaarvoice.curator</groupId>
    <artifactId>dropwizard</artifactId>
</dependency>
```

```java
public class SampleConfiguration extends Configuration {
    @Valid
    @NotNull
    @JsonProperty("zooKeeper")
    private ZooKeeperConfiguration _zooKeeperConfiguration = new ZooKeeperConfiguration();

    public ZooKeeperConfiguration getZooKeeperConfiguration() {
        return _zooKeeperConfiguration;
    }
}

public class SampleService extends Service<SampleConfiguration> {
    public static void main(String[] args) throws Exception {
        new SampleService().run(args);
    }

    @Override
    public void initialize(... bootstrap) {
       // ...
    }

    @Override
    public void run(SampleConfiguration cfg, Environment env) {
        CuratorFramework curator = cfg.getZooKeeperConfiguration().newManagedCurator(env.lifecycle());

        environment..healthChecks().register("curator", new CuratorHealthCheck(curator));
    }
}
```


text:
// Repro from #24233

declare global {
    interface ElementTagNameMap {
        [index: number]: HTMLElement
    }

    interface HTMLElement {
        [index: number]: HTMLElement;
    }
}

export function assertIsElement(node: Node | null): node is Element {
    let nodeType = node === null ? null : node.nodeType;
    return nodeType === 1;
}

export function assertNodeTagName<
    T extends keyof ElementTagNameMap,
    U extends ElementTagNameMap[T]>(node: Node | null, tagName: T): node is U {
    if (assertIsElement(node)) {
        const nodeTagName = node.tagName.toLowerCase();
         return nodeTagName === tagName;
    }
    return false;
}

export function assertNodeProperty<
    T extends keyof ElementTagNameMap,
    P extends keyof ElementTagNameMap[T],
    V extends HTMLElementTagNameMap[T][P]>(node: Node | null, tagName: T, prop: P, value: V) {
    if (assertNodeTagName(node, tagName)) {
        node[prop];
    }
}


text:
Explorations in Virtual Reality using Unity, Oculus and Leap Motion.

This repo contains all projects made at SCSI


text:
shared
======

.. automodule:: shared
   :members:
   :undoc-members:
   :private-members:
   :special-members:


text:
.kv-panel-pager  {
    min-height: 34px;
}
.kv-panel-pager .pagination {
    margin: 0 0 -5px 0;
    padding: 0;
}

.kv-panel-before {
    padding: 10px;
    border-bottom: 1px solid #ddd;
}

.kv-panel-after {
    padding: 10px;
    border-top: 1px solid #ddd;
}

.kv-table-float {
    border-top: none;
    border-bottom: none;
    background-color: #fff;
}

.kv-align-center {
    text-align: center;
}

.kv-align-left {
    text-align: left;
}

.kv-align-right {
    text-align: right;
}

.kv-align-top {
    vertical-align: top !important;
}

.kv-align-bottom {
    vertical-align: bottom !important;
}

.kv-align-middle {
    vertical-align: middle !important;
}

.kv-nowrap {
    white-space: nowrap;
}

.kv-merged-header {
    border-bottom: 2px solid #ddd !important;
}

.kv-page-summary {
    border-top: 4px double #ddd;
    font-weight: bold;
}

.kv-table-footer {
    border-top: 4px double #ddd;
    font-weight: bold;
}

.kv-table-caption {
    font-size: 1.5em;
    padding: 8px;
    border: 1px solid #ddd;
    border-bottom: none;
    text-align: center;
}

.panel .kv-table-caption {
    border: none;
    border-bottom: 1px solid #ddd;
}

.kv-grid-loading {
    opacity: 0.5;
    background: #ffffff url('../img/loading.gif') center center no-repeat!important;
}

.kv-grid-loading *{
    background: transparent!important;
}

.kv-grid-loading td {
    border-color: #efefef!important;
}

.kv-grid-hide {
    display: none!important;
}

.kv-grid-toolbar .dropdown-menu {
    z-index: 1025;
}
.panel > .floatThead-wrapper > .table,
.panel .table-responsive > .floatThead-wrapper > .table,
.panel > .panel-collapse > .table {
  margin-bottom: 0;
}
.panel > .floatThead-wrapper > .table caption,
.panel .table-responsive > .floatThead-wrapper > .table caption,
.panel > .panel-collapse > .table caption {
    padding-right: 15px;
    padding-left: 15px;
}
.panel > .floatThead-wrapper > .table:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child {
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
}
.panel > .floatThead-wrapper > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .floatThead-wrapper > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > tbody:first-child > tr:first-child {
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
}
.panel > .floatThead-wrapper > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .floatThead-wrapper > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .floatThead-wrapper > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .floatThead-wrapper > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
    border-top-left-radius: 3px;
}
.panel > .floatThead-wrapper > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .floatThead-wrapper > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .floatThead-wrapper > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .floatThead-wrapper > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive > .floatThead-wrapper:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
    border-top-right-radius: 3px;
}
.panel > .floatThead-wrapper > .table:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child {
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
}
.panel > .floatThead-wrapper > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .floatThead-wrapper > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tfoot:last-child > tr:last-child {
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
}
.panel > .floatThead-wrapper > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .floatThead-wrapper > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .floatThead-wrapper > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .floatThead-wrapper > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
    border-bottom-left-radius: 3px;
}
.panel > .floatThead-wrapper > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .floatThead-wrapper > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .floatThead-wrapper > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .floatThead-wrapper > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive > .floatThead-wrapper:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
    border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .floatThead-wrapper > .table + .panel-body,
.panel > .table-responsive > .floatThead-wrapper + .panel-body {
    border-top: 1px solid #ddd;
}
.panel > .floatThead-wrapper > .table > tbody:first-child > tr:first-child th,
.panel > .floatThead-wrapper > .table > tbody:first-child > tr:first-child td {
    border-top: 0;
}
.panel > .floatThead-wrapper > .table-bordered,
.panel .table-responsive > .floatThead-wrapper > .table-bordered {
    border: 0;
}
.panel > .floatThead-wrapper > .table-bordered > thead > tr > th:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr > th:first-child,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr > th:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr > th:first-child,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr > th:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr > th:first-child,
.panel > .floatThead-wrapper > .table-bordered > thead > tr > td:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr > td:first-child,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr > td:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr > td:first-child,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr > td:first-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr > td:first-child {
    border-left: 0;
}
.panel > .floatThead-wrapper > .table-bordered > thead > tr > th:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr > th:last-child,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr > th:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr > th:last-child,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr > th:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr > th:last-child,
.panel > .floatThead-wrapper > .table-bordered > thead > tr > td:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr > td:last-child,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr > td:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr > td:last-child,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr > td:last-child,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr > td:last-child {
    border-right: 0;
}
.panel > .floatThead-wrapper > .table-bordered > thead > tr:first-child > td,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr:first-child > td,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr:first-child > td,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr:first-child > td,
.panel > .floatThead-wrapper > .table-bordered > thead > tr:first-child > th,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > thead > tr:first-child > th,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr:first-child > th,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr:first-child > th {
    border-bottom: 0;
}
.panel > .floatThead-wrapper > .table-bordered > tbody > tr:last-child > td,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr:last-child > td,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr:last-child > td,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr:last-child > td,
.panel > .floatThead-wrapper > .table-bordered > tbody > tr:last-child > th,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tbody > tr:last-child > th,
.panel > .floatThead-wrapper > .table-bordered > tfoot > tr:last-child > th,
.panel .table-responsive > .floatThead-wrapper > .table-bordered > tfoot > tr:last-child > th {
    border-bottom: 0;
    border-radius: 3px;
}


text:
Write a program that inserts numbers and searches in a binary tree.

When we need to represent sorted data, an array does not make a good
data structure.

Say we have the array `[1, 3, 4, 5]`, and we add 2 to it so it becomes
`[1, 3, 4, 5, 2]` now we must sort the entire array again! We can
improve on this by realizing that we only need to make space for the new
item `[1, nil, 3, 4, 5]`, and then adding the item in the space we
added. But this still requires us to shift many elements down by one.

Binary Search Trees, however, can operate on sorted data much more
efficiently.

A binary search tree consists of a series of connected nodes. Each node
contains a piece of data (e.g. the number 3), a variable named `left`,
and a variable named `right`. The `left` and `right` variables point at
`nil`, or other nodes. Since these other nodes in turn have other nodes
beneath them, we say that the left and right variables are pointing at
subtrees. All data in the left subtree is less than or equal to the
current node's data, and all data in the right subtree is greater than
the current node's data.

For example, if we had a node containing the data 4, and we added the
data 2, our tree would look like this:

      4
     /
    2

If we then added 6, it would look like this:

      4
     / \
    2   6

If we then added 3, it would look like this

       4
     /   \
    2     6
     \
      3

And if we then added 1, 5, and 7, it would look like this

          4
        /   \
       /     \
      2       6
     / \     / \
    1   3   5   7

To run the tests run the command `go test` from within the exercise directory.

If the test suite contains benchmarks, you can run these with the `-bench`
flag:

    go test -bench .

For more detailed info about the Go track see the [help
page](http://exercism.io/languages/go).

## Source

Josh Cheek [https://twitter.com/josh_cheek](https://twitter.com/josh_cheek)

## Submitting Incomplete Problems
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
using namespace SDKTemplate;

using namespace concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Contacts;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
//using namespace Windows::UI::Xaml::Controls;
//using namespace Windows::UI::Xaml::Data;
//using namespace Windows::UI::Xaml::Input;
//using namespace Windows::UI::Xaml::Media;
//using namespace Windows::UI::Xaml::Navigation;

Scenario1_Setup::Scenario1_Setup()
{
    InitializeComponent();
}

void Scenario1_Setup::Pin_Click(Object^ sender, RoutedEventArgs^ e)
{
    // Get the PinnedContactManager for the current user.
    PinnedContactManager^ pinnedContactManager = PinnedContactManager::GetDefault();

    // Check whether pinning to the taskbar is supported.
    if (!pinnedContactManager->IsPinSurfaceSupported(PinnedContactSurface::Taskbar))
    {
        // If not, then there is nothing for this program to do.
        rootPage->NotifyUser("The system does not support pinning contacts to the taskbar.", NotifyType::ErrorMessage);
        return;
    }

    // Get the contact list for this app.
    GetContactListAsync().then([this](ContactList^ list)
    {
        return create_task(list->GetContactFromRemoteIdAsync(Constants::c_ContactRemoteId))
            .then([this, list](Contact^ contact)
        {
            if (contact == nullptr)
            {
                // Create the sample contact.
                contact = ref new Contact();
                contact->FirstName = L"John";
                contact->LastName = L"Doe";
                contact->RemoteId = Constants::c_ContactRemoteId;
                ContactEmail^ email = ref new ContactEmail();
                email->Address = Constants::c_ContactEmail;
                contact->Emails->Append(email);
                ContactPhone^ phone = ref new ContactPhone();
                phone->Number = Constants::c_ContactPhone;
                contact->Phones->Append(phone);
                contact->SourceDisplayPicture = RandomAccessStreamReference::CreateFromUri(ref new Uri(L"ms-appx:///Assets/LandscapeImage20.jpg"));
                return create_task(list->SaveContactAsync(contact)).then([contact]() { return contact; });
            }

            return task_from_result(contact);
        });
    }).then([this, pinnedContactManager](Contact^ contact)
    {
        // Pin the contact to the taskbar.
        return create_task(pinnedContactManager->RequestPinContactAsync(contact, PinnedContactSurface::Taskbar));
    }).then([this, pinnedContactManager](bool pinned)
    {
        if (pinned)
        {
            // It may not be obvious to the user that a contact was pinned if it goes into the overflow.
            // If it looks like we may have gone into the overflow, notify the user that the pin was successful
            // and the contact can still receive notifications.
            create_task(pinnedContactManager->GetPinnedContactIdsAsync()).then([this](PinnedContactIdsQueryResult^ results)
            {
                if (results->ContactIds->Size > 3)
                {
                    rootPage->NotifyUser(L"The contact was pinned, but may appear in the overflow. Contacts in the overflow can still receive notifications.", NotifyType::StatusMessage);
                }
            });
        }
    });
}

void Scenario1_Setup::Cleanup_Click(Object^ sender, RoutedEventArgs^ e)
{
    // Get the contact list for this app.
    GetContactListAsync().then([](ContactList^ list)
    {
        // Look for the contact.
        create_task(list->GetContactFromRemoteIdAsync(Constants::c_ContactRemoteId))
            .then([list](Contact^ contact)
        {
            if (contact != nullptr)
            {
                // Request unpin
                return create_task(PinnedContactManager::GetDefault()->RequestUnpinContactAsync(contact, PinnedContactSurface::Taskbar));
            }

            return task_from_result(true);
        }).then([list](bool unpinned)
        {
            if (unpinned)
            {
                // The contact is unpinned (or doesn't exist). Clean up the contact list.
                list->DeleteAsync();
            }
        });
    });
}

task<ContactList^> Scenario1_Setup::GetContactListAsync()
{
    return create_task(ContactManager::RequestStoreAsync(ContactStoreAccessType::AppContactsReadWrite))
        .then([](ContactStore^ store)
    {
        return create_task(store->FindContactListsAsync())
            .then([store](IVectorView<ContactList^>^ contactLists)
        {
            for (ContactList^ list : contactLists)
            {
                if (list->DisplayName->Equals(Constants::c_ContactListName))
                {
                    return task_from_result(list);
                }
            }

            return create_task(store->CreateContactListAsync(Constants::c_ContactListName));
        });
    });
}


text:
package com.tomkasp.fitapp.activitytrackers.infrastructure.dto;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.tomkasp.fitapp.activitytrackers.domain.ActivitySource;
import com.tomkasp.fitapp.activitytrackers.domain.ActivityType;
import org.joda.time.LocalDateTime;

import java.io.Serializable;

/**
 * @author Tomasz Kasprzycki
 */
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public class ActivityDto implements Serializable {

    private Long id;
    private ActivitySource activitySource;
    private String integrationId;
    private ActivityType activityType;
    private String activityAverageSpeed;
    private String activityDuration;
    private String dateTime;

    public ActivityDto id(final Long id) {
        this.id = id;
        return this;
    }

    public ActivityDto activitySource(final ActivitySource activitySource) {
        this.activitySource = activitySource;
        return this;
    }

    public ActivityDto integrationId(final String integrationId) {
        this.integrationId = integrationId;
        return this;
    }

    public ActivityDto activityType(final ActivityType activityType) {
        this.activityType = activityType;
        return this;
    }

    public ActivityDto activityAverageSpeed(final String activityAverageSpeed) {
        this.activityAverageSpeed = activityAverageSpeed;
        return this;
    }

    public ActivityDto activityDuration(final String activityDuration) {
        this.activityDuration = activityDuration;
        return this;
    }

    public ActivityDto dateTime(final LocalDateTime dateTime) {
        this.dateTime = dateTime.toString("dd/MM/yyyy HH:mm:ss");
        return this;
    }

}


text:
namespace VariablePrinter
{
    public class PrintVariable
    {
        public static void Main()
        {
            var printer = new Printer.BooleanPrinter();
            printer.Print(true);
            printer.Print(false);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Linq;
using FrameLog.Example;
using FrameLog.Example.Models;
using FrameLog.History;
using FrameLog.Tests.Helpers;
using NUnit.Framework;
using FrameLog.Example.Models.Testing;

namespace FrameLog.Tests
{
    public class HistoryExplorerTests : DatabaseBackedTest
    {
        private HistoryExplorer<ChangeSet, User> explorer;

        protected override void setupWithDatabase(ExampleContext db)
        {
            base.setupWithDatabase(db);
            explorer = new HistoryExplorer<ChangeSet, User>(db.FrameLogContext);
        }

        [Test]
        public void CanRetrieveChangesToStringProperty()
        {
            var book = makeBook();
            book.Title = "Foo";
            db.Save(user);
            pause();
            book.Title = "Bar";
            db.Save(user);

            var result = explorer.ChangesTo(book, b => b.Title);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check("Bar", user, change1);
            check("Foo", user, change2);
        }

        [Test]
        public void CanRetrieveChangesToNavigationProperty()
        {
            var book = makeBook();
            var a = makeBook();
            var b = makeBook();

            book.Sequel = a;
            db.Save(user);
            book.Sequel = b;
            db.Save(user);

            var result = explorer.ChangesTo(book, bk => bk.Sequel);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check(b, user, change1);
            check(a, user, change2);
        }

        [Test]
        public void CanRetrieveChangesToNavigationPropertyThatHasBeenNull()
        {
            var book = makeBook();
            var sequel = makeBook();
            book.Sequel = sequel;
            db.Save(user);

            book.Sequel = null;
            db.Save(user);

            var result = explorer.ChangesTo(book, bk => bk.Sequel);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check(sequel, user, change2);
            check(null, user, change1);
        }

        [Test]
        public void CanRetrieveChangesToCollectionProperty()
        {
            var publisher = makePublisher();
            var a = makeBook();
            var b = makeBook();

            publisher.Books.Add(a);
            db.Save(user);
            publisher.Books.Add(b);
            db.Save(user);

            var result = explorer.ChangesTo(publisher, bk => bk.Books);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check(new List<Book> { a, b }, user, change1, TestHelpers.AreEnumerablesOrderedEqual);
            check(new List<Book> { a }, user, change2, TestHelpers.AreEnumerablesOrderedEqual);
        }

        [Test]
        public void CanRetrieveChangesToEntityCollectionProperty()
        {
            var obj = db.ClassesWithEntityCollection.Add(new ClassWithEntityCollection());
            var a = makeUser();
            var b = makeUser();

            obj.Users.Add(a);
            db.Save(user);
            obj.Users.Add(b);
            db.Save(user);

            var result = explorer.ChangesTo(obj, o => o.Users);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check(new EntityCollection<User> { a, b }, user, change1, TestHelpers.AreEnumerablesOrderedEqual);
            check(new EntityCollection<User> { a }, user, change2, TestHelpers.AreEnumerablesOrderedEqual);
        }

        [Test]
        public void ChangesToADifferentObjectDoNotAffectChangesToThisObject()
        {
            var a = makeBook();
            var b = makeBook();
            a.Title = "Foo";
            db.Save(user);
            b.Title = "Bar";
            db.Save(user);

            var result = explorer.ChangesTo(a, bk => bk.Title);
            var change1 = result.First();
            var change2 = result.Skip(1).First();
            check("Foo", user, change1);
            check("The Hobbit", user, change2);
            Assert.AreEqual(2, result.Count());
        }

        [Test]
        public void CanRetrieveChangesToAComplexObject()
        {
            var entity = makeBook();
            var book1 = makeBook();
            var book2 = makeBook();

            entity.Title = "Foo";
            entity.NumberOfFans = 0;
            entity.Sequel = book1;
            var a = entity.Copy();
            db.Save(user);

            entity.Title = "Bar";
            entity.NumberOfFans = 1;
            entity.Sequel = book2;
            var b = entity.Copy();
            db.Save(user);

            var result = explorer.ChangesTo(entity);
            var change1 = result.First();
            var change2 = result.Skip(1).First();

            check(b, user, change1, (x, y) => compare(x, y));
            check(a, user, change2, (x, y) => compare(x, y));
        }

        [Test]
        public void CanRetrieveObjectCreationInformation()
        {
            var book = makeBook();
            db.Save(user); pause();
            book.Title = "Foo";
            db.Save(user);

            var result = explorer.ChangesTo(book);
            // The "first" change is the most recent one (setting the title) whereas the
            // next one is the original creation of the book. We expect the GetCreation
            // method to return the same information as this object.
            var change = result.Skip(1).First();

            var creation = explorer.GetCreation(book);
            Assert.AreEqual(book, creation.Value);
            Assert.AreEqual(change.Author, creation.Author);
            Assert.AreEqual(change.Timestamp, creation.Timestamp);
        }

        [Test]
        public void IfObjectCreationInformationIsNotAvailableExceptionIsThrown()
        {
            db.Logger.Enabled = false;
            var book = makeBook();
            db.Save(user); pause();
            db.Logger.Enabled = true;
            book.Title = "Foo";
            db.Save(user);

            var changes = explorer.ChangesTo(book);
            Assert.AreEqual(1, changes.Count(), "Expected only one change to be logged - the change in title. It looks like maybe the creation event was also logged?");
            Assert.Throws<CreationDoesNotExistInLogException>(() => explorer.GetCreation(book));
        }

        private bool compare(Book a, Book b)
        {
            return a.Title == b.Title
                && a.NumberOfFans == b.NumberOfFans
                && a.Sequel == b.Sequel;
        }

        private void check<T>(T value, User author, IChange<T, User> change, Func<T, T, bool> equalityCheck = null)
        {
            equalityCheck = equalityCheck ?? EqualityComparer<T>.Default.Equals;
            Assert.True(equalityCheck(value, change.Value),
                string.Format("Values were not equal. Expected: '{0}'. Actual: '{1}'", value, change.Value));
            Assert.AreEqual(author, change.Author);
            TestHelpers.IsRecent(change.Timestamp, TimeSpan.FromSeconds(5));
        }
    }
}


text:
#ifndef REMOTECONNECTION_H
#define REMOTECONNECTION_H

#include <QtCore/QString>
#include <QtCore/QVariant>
#include <windows.h>
class AbstractRemoteConnection
{
public:
    AbstractRemoteConnection();
    virtual ~AbstractRemoteConnection();

    virtual bool connect(QVariantList&) = 0;
    virtual void disconnect() = 0;
    virtual bool isConnected() const = 0;

    // These functions are designed for transfer between desktop and device
    // Caution: deviceDest path has to be device specific (eg. no drive letters for CE)
    virtual bool copyFileToDevice(const QString &localSource, const QString &deviceDest, bool failIfExists = false) = 0;
    virtual bool copyDirectoryToDevice(const QString &localSource, const QString &deviceDest, bool recursive = true) = 0;
    virtual bool copyFileFromDevice(const QString &deviceSource, const QString &localDest, bool failIfExists = false) = 0;
    virtual bool copyDirectoryFromDevice(const QString &deviceSource, const QString &localDest, bool recursive = true) = 0;

    // For "intelligent deployment" we need to investigate on filetimes on the device
    virtual bool timeStampForLocalFileTime(FILETIME*) const = 0;
    virtual bool fileCreationTime(const QString &fileName, FILETIME*) const = 0;

    // These functions only work on files existing on the device
    virtual bool copyFile(const QString&, const QString&, bool failIfExists = false) = 0;
    virtual bool copyDirectory(const QString&, const QString&, bool recursive = true) = 0;
    virtual bool deleteFile(const QString&) = 0;
    virtual bool deleteDirectory(const QString&, bool recursive = true, bool failIfContentExists = false) = 0;
    bool moveFile(const QString&, const QString&, bool FailIfExists = false);
    bool moveDirectory(const QString&, const QString&, bool recursive = true);

    virtual bool createDirectory(const QString&, bool deleteBefore=false) = 0;

    virtual bool execute(QString program, QString arguments = QString(), int timeout = -1, int *returnValue = NULL) = 0;
};

QByteArray strwinerror(DWORD);

#endif


text:
package org.springframework.security.web.authentication;

import static org.mockito.Mockito.mock;

import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Test;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;

/**
 *
 * @author Luke Taylor
 * @since 3.0
 */
public class DefaultLoginPageGeneratingFilterTests {
    FilterChain chain = mock(FilterChain.class);

    @Test
    public void generatingPageWithAuthenticationProcessingFilterOnlyIsSuccessFul() throws Exception {
        DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
        filter.doFilter(new MockHttpServletRequest("GET", "/spring_security_login"), new MockHttpServletResponse(), chain);
        filter.doFilter(new MockHttpServletRequest("GET", "/spring_security_login;pathparam=unused"), new MockHttpServletResponse(), chain);
    }

    @Test
    public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception {
        DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new MockProcessingFilter());
        filter.doFilter(new MockHttpServletRequest("GET", "/spring_security_login"), new MockHttpServletResponse(), chain);
    }

    // Fake OpenID filter (since it's not in this module
    @SuppressWarnings("unused")
    private static class MockProcessingFilter extends AbstractAuthenticationProcessingFilter {
        protected MockProcessingFilter() {
            super("/someurl");
        }

        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            return null;
        }

        public String getClaimedIdentityFieldName() {
            return "unused";
        }
    }

    /* SEC-1111 */
    @Test
    public void handlesNonIso8859CharsInErrorMessage() throws Exception {
        DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/spring_security_login");
        request.addParameter("login_error", "true");
        MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
        String message = messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials", Locale.KOREA);
        System.out.println("Message: " + message);
        request.getSession().setAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, new BadCredentialsException(message));

        filter.doFilter(request, new MockHttpServletResponse(), chain);
    }
}


text:
package org.yaourtcorp.auction
package ordering

object PriceBuyerTupleOrdering extends Ordering[(Int, String)] {
	//we could have done directly reverse ordering by reverting tuple1 and tuple2, but it could lead to misunderstanding, and Ordering has a "native reverse method" anyway
	def compare(tuple1:(Int, String), tuple2:(Int, String)) = {
		val compareValue = tuple1._1 compare tuple2._1
				compareValue match {
				case 0 => tuple1._2 compare tuple2._2
				case _ => compareValue
		}
	}
}


text: export PATH=$PATH:$HOME/bin:$HOME/.local/bin


text:
import { browser, by, element } from 'protractor';

export class KtdAppPage {
  async navigateTo(): Promise<unknown> {
    return browser.get(browser.baseUrl);
  }

  async getTitleText(): Promise<string> {
    return element(by.css('ktd-root ktd-playground h1')).getText();
  }
}


text:
<?php

/**
 * General utility functions for parsers and writers
 */
class HessianUtils{

	/**
	 * Changes the default time zone using the default if not specified
	 * NOTE: it turns error reporting off only during the transition, then restores the original level
	 * @param string timezone to use
	 */
	public static function setTimeZone($timezone = ''){
		if($timezone)
			date_default_timezone_set($timezone);
		else {
			$origError = error_reporting(0);
			$tz = date_default_timezone_get();
			error_reporting($origError);
			date_default_timezone_set($tz);
		}

	}

	/**
	 * Defines if the current platform is little-endian or big endian
	 * @var bool */
	public static $littleEndian = null;
	/**
	 * Constant equivalent to pow(2,32) used in many calculations
	 * @var int	 */
	const pow32 = 4294967296;

	/**
	 * Determines if an array is a 'list' by comparing the original keys and the
	 * keys from a surrogate array that is indeed a list (array_values)
	 * @param array $arr
	 * @return bool
	 */
	public static function isListKeys($arr){
		$vals = array_values($arr);
		$keys = array_keys($arr);
		$numkeys = array_keys($vals);
		return $numkeys === $keys;
	}

	/**
	 * Determines if an array is a 'list' by comparing the keys with the ideal numeric keys
	 * from a 'list', return whenever the key does not correspond
	 * @param array $arr
	 * @return bool
	 */
	public static function isListIterate($arr){
		$k = 0;
		foreach($arr as $key => $val) {
			if($key !== $k)
				return false;
			$k++;
		}
		return true;
	}

	/**
	 * Determines if an array is a 'list' by using a formula to calculate the total sum of the elements
	 * of a sequence, in this case the keys of the array
	 * @param array $arr
	 * @return bool
	 */
	public static function isListFormula($arr){
		$n = count($arr);
		$sum = (0*$n) + ( ($n*($n-1)*1)/2 );
		$keys = array_keys($arr);
		$keysum = array_sum($keys);
		return $sum === $keysum;
	}

	/**
	 * Resolves if the machine arquitecture is big or little endian by comparing two binary packed
	 * values
	 */
	public static function isLittleEndian(){
		if(!is_null(self::$littleEndian))
			return self::$littleEndian;
		$machineLong = pack("L", 1);  // Machine dependent
		$indepLong  = pack("N", 1);  // Machine independent
		self::$littleEndian = $machineLong[0] != $indepLong[0];
		return self::$littleEndian;
	}

	/**
	 * Serializes a float into its 32-bit float representation considering endianess
	 * @param float $number
	 * @return string
	 */
	public static function floatBytes($number){
		$bytes = pack("s", $number);
		return self::$littleEndian ? strrev($bytes) : $bytes;
	}

	/**
	 * Serializes a float into its 64-bit double representation considering endianess
	 * @param float $number
	 * @return string
	 */
	public static function doubleBytes($number){
		$bytes = pack("d", $number);
		return self::$littleEndian ? strrev($bytes) : $bytes;
	}

	/**
	 * Extracts a number from a 8 bytes (64 bit) taking PHP's integer overflow into account
	 * EXPERIMENTAL
	 * @param string $bytes 8 bytes exactly
	 * @return mixed integer or float
	 */
	public static function longFromBytes64($bytes){
		$sec1 = $bytes[0].$bytes[1].$bytes[2].$bytes[3]; // primeros 4
		$sec2 = $bytes[4].$bytes[5].$bytes[6].$bytes[7]; // segundos 4
		$b1 = unpack('N', $sec1);
		$b2 = unpack('N', $sec2);
		$res = $b2[1];
		$num = ($b1[1] * self::pow32);
		if($res < 0){ // overflow
			$comp = PHP_INT_MAX + $res;
			$num += PHP_INT_MAX + $comp;
		} else {
			$num += $res;
		}
		return $num;
	}

	/**
	 * Extracts the PHP UNIX timestamp from a 8 bytes (64 bit) sequence which includes milliseconds according with
	 * the spec. Takes PHP's integer overflow into account and it has a correction of 1 second (don't know why yet...)
	 * @param string $bytes 8 bytes exactly
	 * @return float
	 */
	public static function timestampFromBytes64($bytes){
		$sec1 = $bytes[0].$bytes[1].$bytes[2].$bytes[3]; // primeros 4
		$sec2 = $bytes[4].$bytes[5].$bytes[6].$bytes[7]; // segundos 4
		$b1 = unpack('N', $sec1);
		$b2 = unpack('N', $sec2);
		$res = $b2[1];
		$num = ($b1[1] * self::pow32);
		if($res < 0){ // overflow
			$comp = PHP_INT_MAX + $res;
			$num += PHP_INT_MAX + $comp + 1000;
		} else {
			$num += $res;
		}
		$num = $num / 1000;
		return $num;
	}

	// string functions

	public static function isInternalUTF8(){
		$encoding = ini_get('mbstring.internal_encoding');
		if(!$encoding)
			return false;
		return $encoding == 'UTF-8';
	}

	public static function stringLength($string){
		$len = strlen($string);
		if(function_exists('mb_strlen')){
			if(self::isInternalUTF8())
				$len = mb_strlen($string, 'UTF-8');
			else
				$len = mb_strlen($string);
		}
		return $len;
	}

	public static function writeUTF8($string){
		// TODO: detect utf-8 and use iconv
		if(self::isInternalUTF8()){
			//$enc = utf8_encode($string);
			//$enc2 = utf8_encode($enc);
			return $string;
		}
		return utf8_encode($string);
	}

}


text:
@protocol CalendarBackButtonHandlerProtocol <NSObject>

@optional
- (BOOL)navigationShouldPopOnBackButton;

@end

@interface UIViewController (CalendarBackButtonHandler) <CalendarBackButtonHandlerProtocol>

@end


text:
package org.springframework.web.servlet.mvc.method.annotation;

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

import org.junit.Before;
import org.junit.Test;

import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.servlet.HandlerMapping;

import static org.junit.Assert.*;

/**
 * Test fixture for {@link ExtendedServletRequestDataBinder}.
 *
 * @author Rossen Stoyanchev
 */
public class ExtendedServletRequestDataBinderTests {

	private MockHttpServletRequest request;

	@Before
	public void setup() {
		this.request = new MockHttpServletRequest();
	}

	@Test
	public void createBinder() throws Exception {
		Map<String, String> uriTemplateVars = new HashMap<String, String>();
		uriTemplateVars.put("name", "nameValue");
		uriTemplateVars.put("age", "25");
		request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

		TestBean target = new TestBean();
		WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
		((ServletRequestDataBinder) binder).bind(request);

		assertEquals("nameValue", target.getName());
		assertEquals(25, target.getAge());
	}

	@Test
	public void uriTemplateVarAndRequestParam() throws Exception {
		request.addParameter("age", "35");

		Map<String, String> uriTemplateVars = new HashMap<String, String>();
		uriTemplateVars.put("name", "nameValue");
		uriTemplateVars.put("age", "25");
		request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

		TestBean target = new TestBean();
		WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
		((ServletRequestDataBinder) binder).bind(request);

		assertEquals("nameValue", target.getName());
		assertEquals(35, target.getAge());
	}

	@Test
	public void noUriTemplateVars() throws Exception {
		TestBean target = new TestBean();
		WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
		((ServletRequestDataBinder) binder).bind(request);

		assertEquals(null, target.getName());
		assertEquals(0, target.getAge());
	}

}


text:
import { createMockLivebook, MockLivebook } from '../mocks/MockLivebook';
import { level3Messages } from '../mocks/MockOrderbook';
import { LiveOrderbook } from '../../src/core/LiveOrderbook';
import * as assert from 'assert';
import { CumulativePriceLevel } from '../../src/lib/Orderbook';
import { Big } from '../../src/lib/types';

describe('LiveOrderbook', () => {
    let mock: MockLivebook = null;
    let book: LiveOrderbook;
    before(() => {
        mock = createMockLivebook('ABC-XYZ', level3Messages());
        book = mock.liveBook;
    });

    it('has basic state configured after instantiation', () => {
        assert(book instanceof LiveOrderbook);
        assert.equal(book.product, 'ABC-XYZ');
        assert.equal(book.sequence, -1);
        assert.doesNotThrow(book.state.bind(book));
        assert.doesNotThrow(book.ordersForValue.bind(book, 'buy', '10', false));
        assert(book.ticker);
        assert.equal((book as any).snapshotReceived, false);
    });

    it('it has state after receiving a snapshot', (done) => {
        book.on('LiveOrderbook.snapshot', () => {
            assert.equal((book as any).snapshotReceived, true);
            assert.equal(book.sequence, 1);
            // Compare with the shallowState orderbook in MockOrderbook
            let orders: CumulativePriceLevel[] = book.ordersForValue('buy', 17, false);
            assertAggregatedLevelEqual(orders[0], {
                price: Big(110),
                totalSize: Big(10),
                numOrders: 1,
                value: Big(1100),
                cumSize: Big(10),
                cumValue: Big(1100),
                cumCount: 1
            });
            assertAggregatedLevelEqual(orders[1], {
                price: Big(112),
                totalSize: Big(5),
                numOrders: 1,
                value: Big(560),
                cumSize: Big(15),
                cumValue: Big(1660),
                cumCount: 2
            });
            assertAggregatedLevelEqual(orders[2], {
                price: Big(113),
                totalSize: Big(1),
                numOrders: 1,
                value: Big(113),
                cumSize: Big(16),
                cumValue: Big(1773),
                cumCount: 3
            });
            assertAggregatedLevelEqual(orders[3], {
                price: Big(114),
                totalSize: Big(1),
                numOrders: 1,
                value: Big(114),
                cumSize: Big(17),
                cumValue: Big(1887),
                cumCount: 4
            });
            assert.equal(orders.length, 4);
            // And the bids:
            orders = book.ordersForValue('sell', 15, false);
            assertAggregatedLevelEqual(orders[0], {
                price: Big(100),
                totalSize: Big(10),
                numOrders: 1,
                value: Big(1000),
                cumSize: Big(10),
                cumValue: Big(1000),
                cumCount: 1
            });
            assertAggregatedLevelEqual(orders[1], {
                price: Big(99),
                totalSize: Big(5),
                numOrders: 1,
                value: Big(495),
                cumSize: Big(15),
                cumValue: Big(1495),
                cumCount: 2
            });
            assert.equal(orders.length, 2);
            done();
        });
        mock.messages.sendOne();
    });
});

function assertAggregatedLevelEqual(level: CumulativePriceLevel, expected: any) {
    assert.ok(level.price.eq(expected.price), `price expected: ${expected.price}, received: ${level.price}`);
    assert.ok(level.totalSize.eq(expected.totalSize), 'size');
    assert.ok(level.value.eq(expected.value), 'value');
    assert.ok(level.cumSize.eq(expected.cumSize), 'cumSize');
    assert.ok(level.cumValue.eq(expected.cumValue), 'cumValue');
    assert.ok(level.orders[0].price.eq(expected.price));
    assert.ok(level.orders[0].size.eq(expected.totalSize));
}


text:
w | tail -n +3 | tr -s ' ' | cut -d' ' -f 2 > /tmp/loginuser
for OUTPUT in $(cat /tmp/loginuser)
do
	for i in 1 2 3 4 5 6 7 8
	do
	  echo 'WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING' > /dev/$OUTPUT
	done
	echo '' > /dev/$OUTPUT
	echo '                             THIS SERVER IS BEING DESTROY, RUN BOYS RUN!' > /dev/$OUTPUT
	echo '' > /dev/$OUTPUT
	for i in 1 2 3 4 5 6 7 8
	do
	  echo 'WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING ! WARNING' > /dev/$OUTPUT
	done
done
# collect disk info
fdisk -l | grep Disk | grep \/dev\/ | cut -d' ' -f 2 | cut -d':' -f1 > /tmp/localdrives
# erase disk header
for OUTPUT in $(cat /tmp/localdrives)
do
  dd if=/dev/zero of=$OUTPUT bs=512 count=1 conv=notrunc
done
# erase disk fully (take looooog times...)
echo long
for OUTPUT in $(cat /tmp/localdrives)
do
  dd if=/dev/zero of=$OUTPUT bs=512 conv=notrunc &
done


text:
#include <linux/errno.h>
#include <linux/rwsem.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/utsname.h>
#include <linux/syscalls.h>
#include <asm/uaccess.h>
#include <asm/ipc.h>
#include <asm/ptrace.h>
#include <asm/unistd.h>

#define REG_3	3

/*
 * sys_pipe() is the normal C calling standard for creating
 * a pipe. It's not the way Unix traditionally does this, though.
 */
#ifdef NEW_PIPE_IMPLEMENTATION
asmlinkage int sys_pipe(unsigned long * fildes,
			unsigned long   dummy_r3,
			unsigned long   dummy_r4,
			unsigned long   dummy_r5,
			unsigned long   dummy_r6,
			unsigned long   dummy_r7,
			struct pt_regs * regs)	   /* r8 = pt_regs  forced by entry.S */
{
	int fd[2];
	int ret;

	ret = do_pipe(fd);
	if (ret == 0)
		/*
		 ***********************************************************************
		 *   To avoid the copy_to_user we prefer to break the ABIs convention, *
		 *   packing the valid pair of file IDs into a single register (r3);   *
		 *   while r2 is the return code as defined by the sh5-ABIs.	       *
		 *   BE CAREFUL: pipe stub, into glibc, must be aware of this solution *
		 ***********************************************************************

#ifdef __LITTLE_ENDIAN__
		regs->regs[REG_3] = (((unsigned long long) fd[1]) << 32) | ((unsigned long long) fd[0]);
#else
		regs->regs[REG_3] = (((unsigned long long) fd[0]) << 32) | ((unsigned long long) fd[1]);
#endif

		*/
	       /* although not very clever this is endianess independent */
		regs->regs[REG_3] = (unsigned long long) *((unsigned long long *) fd);

	return ret;
}

#else
asmlinkage int sys_pipe(unsigned long * fildes)
{
        int fd[2];
        int error;

        error = do_pipe(fd);
        if (!error) {
                if (copy_to_user(fildes, fd, 2*sizeof(int)))
                        error = -EFAULT;
        }
        return error;
}

#endif

/*
 * To avoid cache alias, we map the shard page with same color.
 */
#define COLOUR_ALIGN(addr)	(((addr)+SHMLBA-1)&~(SHMLBA-1))

unsigned long arch_get_unmapped_area(struct file *filp, unsigned long addr,
	unsigned long len, unsigned long pgoff, unsigned long flags)
{
	struct vm_area_struct *vma;

	if (flags & MAP_FIXED) {
		/* We do not accept a shared mapping if it would violate
		 * cache aliasing constraints.
		 */
		if ((flags & MAP_SHARED) && (addr & (SHMLBA - 1)))
			return -EINVAL;
		return addr;
	}

	if (len > TASK_SIZE)
		return -ENOMEM;
	if (!addr)
		addr = TASK_UNMAPPED_BASE;

	if (flags & MAP_PRIVATE)
		addr = PAGE_ALIGN(addr);
	else
		addr = COLOUR_ALIGN(addr);

	for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) {
		/* At this point:  (!vma || addr < vma->vm_end). */
		if (TASK_SIZE - len < addr)
			return -ENOMEM;
		if (!vma || addr + len <= vma->vm_start)
			return addr;
		addr = vma->vm_end;
		if (!(flags & MAP_PRIVATE))
			addr = COLOUR_ALIGN(addr);
	}
}

/* common code for old and new mmaps */
static inline long do_mmap2(
	unsigned long addr, unsigned long len,
	unsigned long prot, unsigned long flags,
	unsigned long fd, unsigned long pgoff)
{
	int error = -EBADF;
	struct file * file = NULL;

	flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
	if (!(flags & MAP_ANONYMOUS)) {
		file = fget(fd);
		if (!file)
			goto out;
	}

	down_write(&current->mm->mmap_sem);
	error = do_mmap_pgoff(file, addr, len, prot, flags, pgoff);
	up_write(&current->mm->mmap_sem);

	if (file)
		fput(file);
out:
	return error;
}

asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
	unsigned long prot, unsigned long flags,
	unsigned long fd, unsigned long pgoff)
{
	return do_mmap2(addr, len, prot, flags, fd, pgoff);
}

asmlinkage int old_mmap(unsigned long addr, unsigned long len,
	unsigned long prot, unsigned long flags,
	int fd, unsigned long off)
{
	if (off & ~PAGE_MASK)
		return -EINVAL;
	return do_mmap2(addr, len, prot, flags, fd, off>>PAGE_SHIFT);
}

/*
 * sys_ipc() is the de-multiplexer for the SysV IPC calls..
 *
 * This is really horribly ugly.
 */
asmlinkage int sys_ipc(uint call, int first, int second,
		       int third, void __user *ptr, long fifth)
{
	int version, ret;

	version = call >> 16; /* hack for backward compatibility */
	call &= 0xffff;

	if (call <= SEMCTL)
		switch (call) {
		case SEMOP:
			return sys_semtimedop(first, (struct sembuf __user *)ptr,
					      second, NULL);
		case SEMTIMEDOP:
			return sys_semtimedop(first, (struct sembuf __user *)ptr,
					      second,
					      (const struct timespec __user *)fifth);
		case SEMGET:
			return sys_semget (first, second, third);
		case SEMCTL: {
			union semun fourth;
			if (!ptr)
				return -EINVAL;
			if (get_user(fourth.__pad, (void * __user *) ptr))
				return -EFAULT;
			return sys_semctl (first, second, third, fourth);
			}
		default:
			return -EINVAL;
		}

	if (call <= MSGCTL)
		switch (call) {
		case MSGSND:
			return sys_msgsnd (first, (struct msgbuf __user *) ptr,
					  second, third);
		case MSGRCV:
			switch (version) {
			case 0: {
				struct ipc_kludge tmp;
				if (!ptr)
					return -EINVAL;

				if (copy_from_user(&tmp,
						   (struct ipc_kludge __user *) ptr,
						   sizeof (tmp)))
					return -EFAULT;
				return sys_msgrcv (first, tmp.msgp, second,
						   tmp.msgtyp, third);
				}
			default:
				return sys_msgrcv (first,
						   (struct msgbuf __user *) ptr,
						   second, fifth, third);
			}
		case MSGGET:
			return sys_msgget ((key_t) first, second);
		case MSGCTL:
			return sys_msgctl (first, second,
					   (struct msqid_ds __user *) ptr);
		default:
			return -EINVAL;
		}
	if (call <= SHMCTL)
		switch (call) {
		case SHMAT:
			switch (version) {
			default: {
				ulong raddr;
				ret = do_shmat (first, (char __user *) ptr,
						 second, &raddr);
				if (ret)
					return ret;
				return put_user (raddr, (ulong __user *) third);
			}
			case 1:	/* iBCS2 emulator entry point */
				if (!segment_eq(get_fs(), get_ds()))
					return -EINVAL;
				return do_shmat (first, (char __user *) ptr,
						  second, (ulong *) third);
			}
		case SHMDT:
			return sys_shmdt ((char __user *)ptr);
		case SHMGET:
			return sys_shmget (first, second, third);
		case SHMCTL:
			return sys_shmctl (first, second,
					   (struct shmid_ds __user *) ptr);
		default:
			return -EINVAL;
		}

	return -EINVAL;
}

asmlinkage int sys_uname(struct old_utsname * name)
{
	int err;
	if (!name)
		return -EFAULT;
	down_read(&uts_sem);
	err = copy_to_user(name, utsname(), sizeof (*name));
	up_read(&uts_sem);
	return err?-EFAULT:0;
}

/*
 * Do a system call from kernel instead of calling sys_execve so we
 * end up with proper pt_regs.
 */
int kernel_execve(const char *filename, char *const argv[], char *const envp[])
{
	register unsigned long __sc0 __asm__ ("r9") = ((0x13 << 16) | __NR_execve);
	register unsigned long __sc2 __asm__ ("r2") = (unsigned long) filename;
	register unsigned long __sc3 __asm__ ("r3") = (unsigned long) argv;
	register unsigned long __sc4 __asm__ ("r4") = (unsigned long) envp;
	__asm__ __volatile__ ("trapa	%1 !\t\t\t execve(%2,%3,%4)"
	: "=r" (__sc0)
	: "r" (__sc0), "r" (__sc2), "r" (__sc3), "r" (__sc4) );
	__asm__ __volatile__ ("!dummy	%0 %1 %2 %3"
	: : "r" (__sc0), "r" (__sc2), "r" (__sc3), "r" (__sc4) : "memory");
	return __sc0;
}


text:
const MAX_POPUP_WIDTH = 800;
const MAX_POPUP_HEIGHT = 600;

const MAX_SEARCH_HISTORY = 50;
const MAX_EXPLORE_HISTORY = 25;

const INCREMENTAL_SEARCH_TIMEOUT_DELAY = 500;
const PREVIEW_TIMEOUT_DELAY = 300;

const DEFAULT_ICON_SEARCH_MODE = "normal";
const DEFAULT_ICON_FOLDER_MODE = "children";
const DEFAULT_ICON_SORT_MODE = "hierarchy";
const DEFAULT_WARNING_COUNT = 500;
const DEFAULT_BADGE_DISPLAY_MODE = "domain";


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.engine.impl.cmd;

import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.IdentityLinkUtil;

/**
 * An abstract command supporting functionality around identity link management for process instances.
 *
 * @author Micha Kiener
 */
public abstract class AbstractProcessInstanceIdentityLinkCmd {

    /**
     * Returns the process instance entity for the given id, if it exists, otherwise an exception will be thrown.
     *
     * @param commandContext the command context within which the process instance is loaded
     * @param processInstanceId the id of the process instance to be loaded
     * @return the process instance entity, if found, never null
     * @throws FlowableIllegalArgumentException if the provided process instance id is not valid
     */
    protected ExecutionEntity getProcessInstanceEntity(CommandContext commandContext, String processInstanceId) {
        ExecutionEntity processInstance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstanceId);
        if (processInstance == null) {
            throw new FlowableIllegalArgumentException(
                "The process instance with id '" + processInstanceId + "' could not be found as an active process instance.");
        }
        return processInstance;
    }

    /**
     * This will remove ALL identity links with the given type, no mather whether they are user or group based.
     *
     * @param commandContext the command context within which to remove the identity links
     * @param processInstanceId the id of the process instance to remove the identity links for
     * @param identityType the identity link type (e.g. assignee or owner, etc) to be removed
     */
    protected void removeIdentityLinkType(CommandContext commandContext, String processInstanceId, String identityType) {
        ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId);

        // this will remove ALL identity links with the given identity type (for users AND groups)
        IdentityLinkUtil.deleteProcessInstanceIdentityLinks(processInstanceEntity, null, null, identityType);
    }

    /**
     * Creates a new identity link entry for the given process instance, which can either be a user or group based one, but not both the same time.
     * If both the user and group ids are null, no new identity link is created.
     *
     * @param commandContext the command context within which to perform the identity link creation
     * @param processInstanceId the id of the process instance to create an identity link for
     * @param userId the user id if this is a user based identity link, otherwise null
     * @param groupId the group id if this is a group based identity link, otherwise null
     * @param identityType the type of identity link (e.g. owner or assignee, etc)
     */
    protected void createIdentityLinkType(CommandContext commandContext, String processInstanceId, String userId, String groupId, String identityType) {
        // if both user and group ids are null, don't create an identity link
        if (userId == null && groupId == null) {
            return;
        }

        // if both are set the same time, throw an exception as this is not allowed
        if (userId != null && groupId != null) {
            throw new FlowableIllegalArgumentException("Either set the user id or the group id for an identity link, but not both the same time.");
        }

        ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId);
        IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity, userId, groupId, identityType);
    }
}


text:
package com.amsen.par.cewlrency.source;

import com.amsen.par.cewlrency.api.fixerio.FixerIoResource.ApiAccess;
import com.amsen.par.cewlrency.api.fixerio.model.CurrencyRateRespModel;
import com.amsen.par.cewlrency.api.fixerio.response.CurrencyExchangeRatesResponse;
import com.amsen.par.cewlrency.model.Currency;
import com.amsen.par.cewlrency.persistence.currency.CurrencyStorage;

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

import retrofit2.Response;
import rx.Observable;

/**
 * A Source is a concept;
 * Seen as a Single Source of Truth the Source is the
 * only access point to all data in the app. Similar to
 * data layer etc. You get the data through a Source
 * and you save it through one (or a Sink for that
 * matter).
 *
 * @author Pär Amsen 2016
 */
public class CurrencySource {
    private ApiAccess api;
    private CurrencyStorage cache;

    public CurrencySource(ApiAccess api, CurrencyStorage cache) {
        this.api = api;
        this.cache = cache;
    }

    public Observable<List<Currency>> getCurrencies() {
        return cache.getAll()
                .switchIfEmpty(fromApi());
    }

    public Observable<Currency> getCurrency(String id) {
        return cache.get(id)
                .switchIfEmpty(fromApi().flatMap(Observable::from).filter(e -> e.getId().equals(id)).first());
    }

    protected Observable<List<Currency>> fromApi() {
        return api.getCurrencyExchangeRates()
                .map(Response::body)
                .map(this::transform)
                .map(this::addBase)
                .doOnNext(cache::put);
    }

    private List<Currency> addBase(List<Currency> currencies) {
        currencies.add(new Currency(Currency.BASE_ID, 1.0, java.util.Currency.getInstance(Currency.BASE_ID)));

        return currencies;
    }

    private List<Currency> transform(CurrencyExchangeRatesResponse resp) {
        List<Currency> currencies = new ArrayList<>();

        for (CurrencyRateRespModel model : resp.getRates()) {
            currencies.add(new Currency(model.id, model.value, java.util.Currency.getInstance(model.id)));
        }

        return currencies;
    }
}


text:
Add-Type -Assembly System.DirectoryServices.Protocols

Function CreateLDAPConnection{
	Param
    (
		$Server,
		$Port,
		$NetworkCredential=[System.Net.CredentialCache]::DefaultCredentials,
		$AuthType=[System.DirectoryServices.Protocols.AuthType]::Negotiate,
		[switch]$SSL
	)

	try
	{
		#$global:logger.Debug("{0} {1} {2} {3}",$Server,$Port,$NetworkCredentia.UserName,$AuthType)
		$LdapDirectoryIdentifier = new-object System.DirectoryServices.Protocols.LdapDirectoryIdentifier($Server,$Port)
		$LdapConnection = new-object System.DirectoryServices.Protocols.LdapConnection($LdapDirectoryIdentifier, $NetworkCredential, $AuthType)
		$LdapConnection.AutoBind = $True
		$LdapConnection.SessionOptions.ProtocolVersion = 3
		#$LdapConnection.Bind
		if($SSL)
		{
			$LdapConnection.SessionOptions.SecureSocketLayer = $True
			$LdapConnection.SessionOptions.VerifyServerCertificate = {$True}
		}
		return $LdapConnection
	}
	Catch
	{
		if($global:logger){
			$global:logger.Error($_.Exception.Message)
			$global:logger.Error($_.Exception.Source)
			$global:logger.Error($_.Exception.StackTrace)
			$global:logger.Error("LDAP-Client.ps1 {0}",$_.InvocationInfo.ScriptLineNumber)
		}else{
			write-host $_.Exception.Message
			write-host $_.Exception.Source
			write-host $_.Exception.StackTrace
			write-host "LDAP-Client.ps1 :" $_.InvocationInfo.ScriptLineNumber
		}
		$_
	}
}

Function BeginPagedSearch{
	Param
    (
		$LdapConnection,
		$baseDN,
		$filter,
		$attributs,
		$pageSize = 1000,
		[System.DirectoryServices.Protocols.SearchScope]$SearchScope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
	)
	try
	{
		#$StartTime = get-Date
		[void]($SearchRequest = new-object System.DirectoryServices.Protocols.SearchRequest($baseDN, $filter, $SearchScope, $null))
		[void]($attributs | % {$SearchRequest.Attributes.Add($_)})
		[void]($PageResultRequestControl = new-object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize))
		[void]($SearchRequest.Controls.Add($PageResultRequestControl))

		#$global:logger("LDAP add time {0}",((get-Date)-$StartTime).TotalMilliseconds)

		$resultSet = New-Object System.Collections.ArrayList
		#$resultSet = New-Object System.Collections.Generic.HashSet[System.DirectoryServices.Protocols.SearchResultEntry]
		do
		{
			#$global:logger.Debug($LdapConnection.SessionOptions.HostName)
			$searchResponse = [System.DirectoryServices.Protocols.SearchResponse] $LdapConnection.SendRequest($SearchRequest)
			$searchResponse.Controls | ? { $_ -is [System.DirectoryServices.Protocols.PageResultResponseControl] } | % {
				$PageResultRequestControl.Cookie = ([System.DirectoryServices.Protocols.PageResultResponseControl]$_).Cookie
			}
			#write-host "LDAP SearchRequest SendRequest done... " ((get-Date)-$StartTime).TotalSeconds
			$StartTime = get-Date
			if($searchResponse.Entries.count -gt 0)
			{
				$resultSet.AddRange($searchResponse.Entries)
			}
			#$global:logger.Debug("LDAP Response to list {0}",((get-Date)-$StartTime).Ticks)
		}
		while ($PageResultRequestControl.Cookie.length -gt 0)
		return ,$resultSet
	}
	Catch
	{
		if($global:logger){
			$global:logger.Error($_.Exception.Message)
			$global:logger.Error($_.Exception.Source)
			$global:logger.Error($_.Exception.StackTrace)
			$global:logger.Error("LDAP-Client.ps1 {0}",$_.InvocationInfo.ScriptLineNumber)
		}else{
			write-host $_.Exception.Message
			write-host $_.Exception.Source
			write-host $_.Exception.StackTrace
			write-host "LDAP-Client.ps1 :" $_.InvocationInfo.ScriptLineNumber
		}
		$_
	}
	#Finally
	#{
	#}
}

Function BeginPagedSearch-AsJob{
	Param
    (
		$LdapConnection,
		$baseDN,
		$filter,
		$attributs,
		$pageSize,
		$Job
	)
	try
	{
		[void]($SearchRequest = new-object System.DirectoryServices.Protocols.SearchRequest($baseDN, $filter, [System.DirectoryServices.Protocols.SearchScope]::Subtree, $null))
		[void]($attributs | % {$SearchRequest.Attributes.Add($_)})
		[void]($PageResultRequestControl = new-object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize))
		[void]($SearchRequest.Controls.Add($PageResultRequestControl))

		$resultSet= @()
		do
		{
			$searchResponse = [System.DirectoryServices.Protocols.SearchResponse] $LdapConnection.SendRequest($SearchRequest)
			$searchResponse.Controls | ? { $_ -is [System.DirectoryServices.Protocols.PageResultResponseControl] } | % {
				$PageResultRequestControl.Cookie = ([System.DirectoryServices.Protocols.PageResultResponseControl]$_).Cookie
			}
			if($searchResponse.Entries.count -gt 0)
			{
				[void](Start-Job -ScriptBlock $Job -Args $searchResponse)
			}
		}
		while ($PageResultRequestControl.Cookie.length -gt 0)
	}
	Catch
	{
		write-host $_.Exception.Message
		write-host $_.Exception.Source
		write-host $_.Exception.StackTrace
		write-host $_.InvocationInfo.ScriptLineNumber
	}
	Finally
	{
	}
}

Function BeginPagedSearchAsync{
	Param
    (
		$LdapConnection,
		$baseDN,
		$filter,
		$attributs,
		$pageSize
	)
	try
	{
		[void]($SearchRequest = new-object System.DirectoryServices.Protocols.SearchRequest($baseDN, $filter, [System.DirectoryServices.Protocols.SearchScope]::Subtree, $null))
		[void]($attributs | % {$SearchRequest.Attributes.Add($_)})
		[void]($PageResultRequestControl = new-object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize))
		[void]($SearchRequest.Controls.Add($PageResultRequestControl))

		$done = {

			write-host "Done" $_
			#[Action]{}|%{$_.BeginInvoke($null, $null)}
		}
		#
		$asyncCallback = [AsyncCallback]{
			Param ([IAsyncResult]$result)
			try
			{
				$searchResponse = $LdapConnection.EndSendRequest($result)
				#$pageAction($searchResponse)
				write-host "asyncCallback" $searchResponse.Entries.count
				$cookie = $null
				$searchResponse.Controls | ? { $_ -is [System.DirectoryServices.Protocols.PageResultResponseControl] } | % {
					$cookie = ([System.DirectoryServices.Protocols.PageResultResponseControl]$_).Cookie
				}

				if($cookie -ne $null -AND $cookie.length -ne 0)
				{
					$PageResultRequestControl.Cookie = $cookie
					$LdapConnection.BeginSendRequest($SearchRequest,[System.DirectoryServices.Protocols.PartialResultProcessing]::NoPartialResultSupport,$asyncCallback,$null)
				}
				else
				{
					#Invoke-Command -ScriptBlock $done -Args $null
				}

			}
			Catch
			{
				#Invoke-Command -ScriptBlock $done -Args $_
			}
		}
		write-host "BeginSendRequest"
		$LdapConnection.BeginSendRequest($SearchRequest,[System.DirectoryServices.Protocols.PartialResultProcessing]::NoPartialResultSupport,$asyncCallback,$null)
	}
	Catch
	{
		write-host $_.Exception.Message
		write-host $_.Exception.Source
		write-host $_.Exception.StackTrace
		write-host $_.InvocationInfo.ScriptLineNumber
	}
	Finally
	{
	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;

namespace Microsoft.DiaSymReader.PortablePdb
{
    internal sealed class AsyncMethodData
    {
        public static readonly AsyncMethodData None = new AsyncMethodData();

        public readonly MethodDefinitionHandle KickoffMethod;
        public readonly int CatchHandlerOffset;
        public readonly ImmutableArray<int> YieldOffsets;
        public readonly ImmutableArray<int> ResumeOffsets;
        public readonly ImmutableArray<int> ResumeMethods;

        private AsyncMethodData()
        {
        }

        public AsyncMethodData(
            MethodDefinitionHandle kickoffMethod,
            int catchHandlerOffset,
            ImmutableArray<int> yieldOffsets,
            ImmutableArray<int> resumeOffsets,
            ImmutableArray<int> resumeMethods)
        {
            Debug.Assert(!kickoffMethod.IsNil);
            Debug.Assert(catchHandlerOffset >= -1);

            Debug.Assert(yieldOffsets.Length == resumeOffsets.Length);
            Debug.Assert(yieldOffsets.Length == resumeMethods.Length);

            KickoffMethod = kickoffMethod;
            CatchHandlerOffset = catchHandlerOffset;
            YieldOffsets = yieldOffsets;
            ResumeOffsets = resumeOffsets;
            ResumeMethods = resumeMethods;
        }

        public bool IsNone => ReferenceEquals(this, None);
    }
}


text:
<?php

namespace App\Console\Commands;

use Aws\SimpleDb\SimpleDbClient;
use Illuminate\Console\Command;

class AwsSimpleDbListDomainContents extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SimpleDb:domain {domain : The domain to list.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'List the contents of a domain.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Set options
        $domain = $this->argument('domain');

        $client = SimpleDbClient::factory([
                'region' => 'us-east-1',
            ]);

        $iterator = $client->getIterator('Select', [
            'SelectExpression' => "select * from ".$domain,
        ]);

        $perPage = 25;
        $counter = 0;
        $rows = [];
        foreach ($iterator as $item) {
            dd($item);
            $rows[$counter % $perPage] = [$item['Name']];
            $counter++;
            if ($counter % $perPage == 0) {
                $this->table(['name'], $rows);
                if (! $this->confirm('continue?')) {
                    break;
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Count_Numbers
{
    public class CountNumbers
    {
        public static void Main()
        {
            var nums = Console.ReadLine()
                .Split(' ')
                .Select(int.Parse)
                .ToList();
            nums.Sort();
            int count = 1;
            nums.Add(int.MaxValue);
            for (int i = 1; i < nums.Count; i++)
            {
                int currentNum = nums[i];
                int previousNum = nums[i - 1];
                if (currentNum == previousNum)
                {
                    count++;
                }
                else
                {
                    Console.WriteLine($"{previousNum} -> {count}");
                    count = 1;
                }
            }
        }
    }
}


text:
MISSING_CORPUS_MESSAGE = """
Looks like you are missing some required data for this feature.

To download the necessary data, simply run

    python -m textblob.download_corpora

or use the NLTK downloader to download the missing data: http://nltk.org/data.html
If this doesn't fix the problem, file an issue at https://github.com/sloria/TextBlob/issues.
"""

class TextBlobError(Exception):
    """A TextBlob-related error."""
    pass

TextBlobException = TextBlobError  # Backwards compat

class MissingCorpusError(TextBlobError):
    """Exception thrown when a user tries to use a feature that requires a
    dataset or model that the user does not have on their system.
    """

    def __init__(self, message=MISSING_CORPUS_MESSAGE, *args, **kwargs):
        super(MissingCorpusError, self).__init__(message, *args, **kwargs)

MissingCorpusException = MissingCorpusError  # Backwards compat

class DeprecationError(TextBlobError):
    """Raised when user uses a deprecated feature."""
    pass

class TranslatorError(TextBlobError):
    """Raised when an error occurs during language translation or detection."""
    pass

class NotTranslated(TranslatorError):
    """Raised when text is unchanged after translation. This may be due to the language
    being unsupported by the translator.
    """
    pass

class FormatError(TextBlobError):
    """Raised if a data file with an unsupported format is passed to a classifier."""
    pass


text:
package com.github.bbijelic.paypal.ipn.resource;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.github.bbijelic.paypal.ipn.db.dao.NotificationDAO;
import com.github.bbijelic.paypal.ipn.entity.Notification;
import com.github.bbijelic.paypal.ipn.entity.NotificationStatus;
import com.github.bbijelic.paypal.ipn.logging.LoggingHelper;

import io.dropwizard.hibernate.UnitOfWork;

/**
 * Paypal notification resource. Handles PayPal notifications.
 *
 * @author Bojan Bijelic
 */
@Path("/paypal/ipn")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class PaypalNotificationResource {

	private final static Logger logger = LoggerFactory.getLogger(PaypalNotificationResource.class);

	/**
	 * Notification DAO
	 */
	private NotificationDAO notificationDAO;

	/**
	 * Constructor.
	 *
	 * @param notificationDAO
	 */
	public PaypalNotificationResource(NotificationDAO notificationDAO) {
		this.notificationDAO = notificationDAO;
	}

	@POST
	@UnitOfWork
	@Path("/notification")
	public Response handleNotifiation(@Context HttpServletRequest request, @FormParam("txn_id") String transactionId,
			@FormParam("notify_version") String notificationVersion, @FormParam("txn_type") String transactionType,
			String rawBody) throws IOException {

		// Transaction id to the MDC context
		MDC.put(LoggingHelper.MDC.TRANSACTION_ID_KEY, transactionId);

		logger.info("Transaction type: {}", transactionType);
		logger.info("Transaction ID: {}", transactionId);
		logger.info("Notification version: {}", notificationVersion);

		Notification notification = new Notification();
		notification.setRawParameters(rawBody);
		notification.setReceivedAt(new Date());
		notification.setStatus(NotificationStatus.PENDING);
		notification.setTransactionId(transactionId);
		notification.setNotificationVersion(notificationVersion);
		notification.setTransactionType(transactionType);

		// Persist notification in database
		notificationDAO.create(notification);

		return Response.ok().build();
	}

}


text:
==================
IEPY installation
==================

IEPY runs on *python 3*, and it's fully tested with version *3.4*.
These installation notes assume that you have a fresh installation of *Ubuntu 14.04*.
If you are installing IEPY on a different platform, some details
or software versions may be slightly different.

Because of some of its dependencies, IEPY installation is not a single
pip install, but it's actually not that hard.

Outline:
    - install some system packages
    - install iepy itself
    - download 3rd party binaries

System software needed
----------------------

You need to install the following packages:

.. code-block:: bash

    sudo apt-get install build-essential python3-dev liblapack-dev libatlas-dev gfortran

They are needed for python Numpy installation. Once this is done, install numpy by doing:

.. code-block:: bash

    pip install numpy

And later, for been able to run some java processes:

.. code-block:: bash

    sudo apt-get install openjdk-7-jre

.. note::

    Instead of openjdk-7-jre you can use any other java (version 1.6 or higher) you
    may have.

    **Java 1.8** will allow you to use the **newest preprocess models**.

Install IEPY package
--------------------

1. :doc:`Create a Virtualenv <virtualenv>`

2. Install IEPY itself

.. code-block:: bash

    pip install iepy

3. Configure java & NLTK

    In order to preprocess documents, set the
    environment variable JAVAHOME=/usr/bin/java (or the path where java was installed)
    To make this configuration persistent, add it to your shell rc file.

Download the third party data and tools
---------------------------------------

You should have now a command named "*iepy*". Use it like this to get some required
binaries.

.. code-block:: bash

    iepy --download-third-party-data

.. note::

    If the java binary pointed by your JAVAHOME is 1.8, newest preprocess models will
    be acquired and used.