text:
import os
import re
import unittest
from binascii import unhexlify, hexlify

from Crypto.Util.py3compat import b, tobytes, bchr
from Crypto.Util.strxor import strxor_c
from Crypto.Util._file_system import pycryptodome_filename
from Crypto.SelfTest.st_common import list_test_cases

from Crypto.Hash import BLAKE2b, BLAKE2s

class Blake2Test(unittest.TestCase):

    def test_new_positive(self):

        h = self.BLAKE2.new(digest_bits=self.max_bits)
        for new_func in self.BLAKE2.new, h.new:

            for dbits in xrange(8, self.max_bits + 1, 8):
                hobj = new_func(digest_bits=dbits)
                self.assertEqual(hobj.digest_size, dbits // 8)

            for dbytes in xrange(1, self.max_bytes + 1):
                hobj = new_func(digest_bytes=dbytes)
                self.assertEqual(hobj.digest_size, dbytes)

            digest1 = new_func(data=b("\x90"), digest_bytes=self.max_bytes).digest()
            digest2 = new_func(digest_bytes=self.max_bytes).update(b("\x90")).digest()
            self.assertEqual(digest1, digest2)

            new_func(data=b("A"), key=b("5"), digest_bytes=self.max_bytes)

        hobj = h.new()
        self.assertEqual(hobj.digest_size, self.max_bytes)

    def test_new_negative(self):

        self.assertRaises(TypeError, self.BLAKE2.new)

        h = self.BLAKE2.new(digest_bits=self.max_bits)
        for new_func in self.BLAKE2.new, h.new:
            self.assertRaises(TypeError, new_func,
                              digest_bytes=self.max_bytes,
                              digest_bits=self.max_bits)
            self.assertRaises(ValueError, new_func, digest_bytes=0)
            self.assertRaises(ValueError, new_func,
                              digest_bytes=self.max_bytes + 1)
            self.assertRaises(ValueError, new_func, digest_bits=7)
            self.assertRaises(ValueError, new_func, digest_bits=15)
            self.assertRaises(ValueError, new_func,
                              digest_bits=self.max_bits + 1)
            self.assertRaises(TypeError, new_func,
                              digest_bytes=self.max_bytes,
                              key=u"string")
            self.assertRaises(TypeError, new_func,
                              digest_bytes=self.max_bytes,
                              data=u"string")

    def test_update(self):
        pieces = [bchr(10) * 200, bchr(20) * 300]
        h = self.BLAKE2.new(digest_bytes=self.max_bytes)
        h.update(pieces[0]).update(pieces[1])
        digest = h.digest()
        h = self.BLAKE2.new(digest_bytes=self.max_bytes)
        h.update(pieces[0] + pieces[1])
        self.assertEqual(h.digest(), digest)

    def test_update_negative(self):
        h = self.BLAKE2.new(digest_bytes=self.max_bytes)
        self.assertRaises(TypeError, h.update, u"string")

    def test_digest(self):
        h = self.BLAKE2.new(digest_bytes=self.max_bytes)
        digest = h.digest()

        # hexdigest does not change the state
        self.assertEqual(h.digest(), digest)
        # digest returns a byte string
        self.failUnless(isinstance(digest, type(b("digest"))))

    def test_update_after_digest(self):
        msg=b("rrrrttt")

        #import pdb; pdb.set_trace()

        # Normally, update() cannot be done after digest()
        h = self.BLAKE2.new(digest_bits=256, data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = self.BLAKE2.new(digest_bits=256, data=msg).digest()

        # With the proper flag, it is allowed
        h = self.BLAKE2.new(digest_bits=256, data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)

    def test_hex_digest(self):
        mac = self.BLAKE2.new(digest_bits=self.max_bits)
        digest = mac.digest()
        hexdigest = mac.hexdigest()

        # hexdigest is equivalent to digest
        self.assertEqual(hexlify(digest), tobytes(hexdigest))
        # hexdigest does not change the state
        self.assertEqual(mac.hexdigest(), hexdigest)
        # hexdigest returns a string
        self.failUnless(isinstance(hexdigest, type("digest")))

    def test_verify(self):
        h = self.BLAKE2.new(digest_bytes=self.max_bytes, key=b("4"))
        mac = h.digest()
        h.verify(mac)
        wrong_mac = strxor_c(mac, 255)
        self.assertRaises(ValueError, h.verify, wrong_mac)

    def test_hexverify(self):
        h = self.BLAKE2.new(digest_bytes=self.max_bytes, key=b("4"))
        mac = h.hexdigest()
        h.hexverify(mac)
        self.assertRaises(ValueError, h.hexverify, "4556")

    def test_oid(self):

        prefix = "1.3.6.1.4.1.1722.12.2." + self.oid_variant + "."

        for digest_bits in self.digest_bits_oid:
            h = self.BLAKE2.new(digest_bits=digest_bits)
            self.assertEqual(h.oid, prefix + str(digest_bits // 8))

            h = self.BLAKE2.new(digest_bits=digest_bits, key=b("secret"))
            self.assertRaises(AttributeError, lambda: h.oid)

        for digest_bits in (8, self.max_bits):
            if digest_bits in self.digest_bits_oid:
                continue
            self.assertRaises(AttributeError, lambda: h.oid)

class Blake2bTest(Blake2Test):
    #: Module
    BLAKE2 = BLAKE2b
    #: Max output size (in bits)
    max_bits = 512
    #: Max output size (in bytes)
    max_bytes = 64
    #: Bit size of the digests for which an ASN OID exists
    digest_bits_oid = (160, 256, 384, 512)
    # http://tools.ietf.org/html/draft-saarinen-blake2-02
    oid_variant = "1"

class Blake2sTest(Blake2Test):
    #: Module
    BLAKE2 = BLAKE2s
    #: Max output size (in bits)
    max_bits = 256
    #: Max output size (in bytes)
    max_bytes = 32
    #: Bit size of the digests for which an ASN OID exists
    digest_bits_oid = (128, 160, 224, 256)
    # http://tools.ietf.org/html/draft-saarinen-blake2-02
    oid_variant = "2"

class Blake2OfficialTestVector(unittest.TestCase):

    def setUp(self):

        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            self.name.lower() + "-test.txt")

        expected = "in"
        self.test_vectors = []
        for line_number, line in enumerate(open(test_vector_file, "rt")):

            if line.strip() == "" or line.startswith("#"):
                continue

            res = re.match("%s:\t([0-9A-Fa-f]*)" % expected, line)
            if not res:
                raise ValueError("Incorrect test vector format (line %d)"
                                 % line_number)

            if res.group(1):
                bin_value = unhexlify(tobytes(res.group(1)))
            else:
                bin_value = b("")
            if expected == "in":
                input_data = bin_value
                expected = "key"
            elif expected == "key":
                key = bin_value
                expected = "hash"
            else:
                result = bin_value
                expected = "in"
                self.test_vectors.append((input_data, key, result))

    def runTest(self):
        for (input_data, key, result) in self.test_vectors:
            mac = self.BLAKE2.new(key=key, digest_bytes=self.max_bytes)
            mac.update(input_data)
            self.assertEqual(mac.digest(), result)

class Blake2bOfficialTestVector(Blake2OfficialTestVector):
    #: Module
    BLAKE2 = BLAKE2b
    #: Hash name
    name = "BLAKE2b"
    #: Max digest size
    max_bytes = 64

class Blake2sOfficialTestVector(Blake2OfficialTestVector):
    #: Module
    BLAKE2 = BLAKE2s
    #: Hash name
    name = "BLAKE2s"
    #: Max digest size
    max_bytes = 32

class Blake2TestVector1(unittest.TestCase):

    def setUp(self):
        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            "tv1.txt")

        self.test_vectors = []
        for line_number, line in enumerate(open(test_vector_file, "rt")):
            if line.strip() == "" or line.startswith("#"):
                continue
            res = re.match("digest: ([0-9A-Fa-f]*)", line)
            if not res:
                raise ValueError("Incorrect test vector format (line %d)"
                                 % line_number)

            self.test_vectors.append(unhexlify(tobytes(res.group(1))))

    def runTest(self):

        for tv in self.test_vectors:
            digest_bytes = len(tv)
            next_data = b("")
            for _ in xrange(100):
                h = self.BLAKE2.new(digest_bytes=digest_bytes)
                h.update(next_data)
                next_data = h.digest() + next_data
            self.assertEqual(h.digest(), tv)

class Blake2bTestVector1(Blake2TestVector1):
    #: Module
    BLAKE2 = BLAKE2b
    #: Hash name
    name = "BLAKE2b"

class Blake2sTestVector1(Blake2TestVector1):
    #: Module
    BLAKE2 = BLAKE2s
    #: Hash name
    name = "BLAKE2s"

class Blake2TestVector2(unittest.TestCase):

    def setUp(self):
        test_vector_file = pycryptodome_filename(
                            ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
                            "tv2.txt")

        self.test_vectors = []
        for line_number, line in enumerate(open(test_vector_file, "rt")):
            if line.strip() == "" or line.startswith("#"):
                continue
            res = re.match("digest\(([0-9]+)\): ([0-9A-Fa-f]*)", line)
            if not res:
                raise ValueError("Incorrect test vector format (line %d)"
                                 % line_number)

            key_size = int(res.group(1))
            result = unhexlify(tobytes(res.group(2)))
            self.test_vectors.append((key_size, result))

    def runTest(self):

        for key_size, result in self.test_vectors:
            next_data = b("")
            for _ in xrange(100):
                h = self.BLAKE2.new(digest_bytes=self.max_bytes,
                                    key=b("A" * key_size))
                h.update(next_data)
                next_data = h.digest() + next_data
            self.assertEqual(h.digest(), result)

class Blake2bTestVector2(Blake2TestVector1):
    #: Module
    BLAKE2 = BLAKE2b
    #: Hash name
    name = "BLAKE2b"
    #: Max digest size in bytes
    max_bytes = 64

class Blake2sTestVector2(Blake2TestVector1):
    #: Module
    BLAKE2 = BLAKE2s
    #: Hash name
    name = "BLAKE2s"
    #: Max digest size in bytes
    max_bytes = 32

def get_tests(config={}):
    tests = []

    tests += list_test_cases(Blake2bTest)
    tests.append(Blake2bOfficialTestVector())
    tests.append(Blake2bTestVector1())
    tests.append(Blake2bTestVector2())

    tests += list_test_cases(Blake2sTest)
    tests.append(Blake2sOfficialTestVector())
    tests.append(Blake2sTestVector1())
    tests.append(Blake2sTestVector2())

    return tests

if __name__ == '__main__':
    import unittest
    suite = lambda: unittest.TestSuite(get_tests())
    unittest.main(defaultTest='suite')


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp" >

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="@string/loading"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/updatedTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:text="@string/loading" />

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
Motif.Page.include("Motif.Ui.Animations.Base.js");
Motif.Page.include("Motif.Drawing.Rectangle.js");
Motif.Page.include("Motif.Ui.Utility.js");

/**
 * Resize a HTMLElement to a target width and height within a specified amount of milliseconds.
 * @constructor
 * @base Motif.Ui.Animations.Base
 * @requires Motif.Ui.Animations.Base
 * @requires Motif.Drawing.Rectangle
 * @requires Motif.Ui.Utility
 * @author Rayraegah
 */
Motif.Ui.Animations.Inflate = function(config) {
    /** @ignore */
    Motif.Utility.extend(this, "Motif.Ui.Animations.Base");
    this.__class.push("Netxion.Ui.Animations.Inflate");

    /** Current dimension @type Object */
    this.active = {
        x: 0,
        y: 0,
        w: 0,
        h: 0
    };
    /** Starting dimension @type Object */
    this.begin = {
        x: 0,
        y: 0,
        w: 0,
        h: 0
    };
    /** End dimension @type Object */
    this.end = null;

    this.play = function() {
        var overflow = Motif.Ui.Css.getCurrentStyle(this.element, "overflow");
        if (overflow != "hidden") {
            this._oldOverflow = overflow;
            this.element.style.overflow = "hidden";
        }
        this.Motif$Ui$Animations$Base.play();
    };

    /** Move the resize animation to the next step */
    this.setCurrent = function(step) {
        this.Motif$Ui$Animations$Base.setCurrent(step);
        if (!this.end) {
            return;
        }

        var width = this.begin.w + Math.round((this.end.w - this.begin.w) / 100 * this.status);
        var height = this.begin.h + Math.round((this.end.h - this.begin.h) / 100 * this.status);

        var rect = new Motif.Drawing.Rectangle(this.begin);
        rect.inflate(width, height);

        if (rect.x != this.active.x || rect.y != this.active.y || rect.w != this.active.w || rect.h != this.active.h) {
            this.active.x = rect.x;
            this.active.y = rect.y;
            this.active.w = rect.w;
            this.active.h = rect.h;

            this.element.style.cssText += ";" + [
                "left:" + this.active.x.toString() + "px",
                "top:" + this.active.y.toString() + "px",
                "width:" + this.active.w.toString() + "px",
                "height:" + this.active.h.toString() + "px"
            ].join(";");
        }
    };

    /** Set the element and if not set the begin and end state by the element */
    this.setElement = function(element) {
        this.Motif$Ui$Animations$Base.setElement(element);
        if (this.end == null && Motif.Type.isElement(this.element)) {
            var rect = new Motif.Ui.Utility.getRectangle(this.element);
            Motif.Page.log.write("Motif.Ui.Animations.Inflate.setElement: Setting end state with element (" + rect.toString() + ").");

            this.end = {
                x: rect.x,
                y: rect.y,
                w: rect.w,
                h: rect.h
            };
            rect.inflate(1, 1);
            Motif.Page.log.write("Motif.Ui.Animations.Inflate.setElement: Setting begin state with element (" + rect.toString() + ").");
            this.begin = {
                x: rect.x,
                y: rect.y,
                w: rect.w,
                h: rect.h
            };
        }

    };

    /** Configure the resize animation */
    this.configure = function(config) {
        config = this.Motif$Ui$Animations$Base.configure(config);
        Motif.Page.log.write("Motif.Ui.Animations.Inflate.configure: Configuring inflate animation.");
        if (config.begin) {
            this.begin = config.begin;
        }
        if (config.end) {
            this.end = config.end;
        }

        if (!isNaN(config.status)) {
            this.setStatus(parseInt(config.status));
        }
    };

    /** Get the string representation from this object @type String */
    this.toString = function() {
        return this.Motif$Ui$Animations$Base.toString() + ", x=" + this.active.x + ", y=" + this.active.y + ", w=" + this.active.w + ", h=" + this.active.h;
    };

    this._completed = function() {
        if (typeof this._oldOverflow != "undefined") {
            this.element.style.overflow = this._oldOverflow;
        }
    };

    /** @ignore */
    this.main = function(config) {
        if (config) {
            this.configure(config);
        }
        this.attachEvent("oncomplete", this._completed);
    };
    this.main(config);
};


text:
module Loops
  class WorkerPool
    attr_reader :name

    def initialize(name, pm, engine, &blk)
      @name = name
      @pm = pm
      @worker_block = blk
      @engine = engine
      @workers = []
    end

    def logger
      @pm.logger
    end

    def shutdown?
      @pm.shutdown?
    end

    def start_workers(number)
      logger.info("Creating #{number} workers for #{name} loop...")
      number.times do |index|
        @workers << Worker.new(name, @pm, @engine, index, &@worker_block)
      end
    end

    def check_workers
      logger.debug("Checking loop #{name} workers...")
      @workers.each do |worker|
        next if worker.running? || worker.shutdown?
        logger.info("Worker #{worker.name} is not running. Restart!")
        worker.run
      end
    end

    def wait_workers
      running = 0
      @workers.each do |worker|
        next unless worker.running?
        running += 1
        logger.info("Worker #{name} is still running (#{worker.pid})")
      end
      return running
    end

    def stop_workers(force)
      logger.info("Stopping loop #{name} workers...")
      @workers.each do |worker|
        next unless worker.running?
        worker.stop(force)
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenopeziza mulgedii Syd.

### Remarks
null


text:
package com.aspose.words.examples.quickstart;

import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.examples.Utils;

public class AppendDocuments
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = Utils.getDataDir(AppendDocuments.class);

        // Load the destination and source documents from disk.
        Document dstDoc = new Document(dataDir + "TestFile.Destination.doc");
        Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
        // Append the source document to the destination document while keeping the original formatting of the source document.
        dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
        dstDoc.save(dataDir + "TestFile Out.docx");

        System.out.println("Documents appended successfully.");
    }
}


text:
#pragma once

#if ENABLE(WEB_TIMING)

#include "CachedResourceHandle.h"
#include <wtf/HashMap.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

class CachedResource;
class CachedResourceRequest;
class Document;
class Frame;

class ResourceTimingInformation {
public:

    void addResourceTiming(CachedResource*, Document&);
    void storeResourceTimingInitiatorInformation(const CachedResourceHandle<CachedResource>&, const CachedResourceRequest&, Frame*);

private:
    enum AlreadyAdded { NotYetAdded, Added };
    struct InitiatorInfo {
        AtomicString name;
        double startTime;
        AlreadyAdded added;
    };
    HashMap<CachedResource*, InitiatorInfo> m_initiatorMap;
};

}

#endif // ENABLE(WEB_TIMING)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Centr. Asian Univ. Stud. , N. S. 14(5): 24 (1950)

#### Original name
Cercospora trachyspermi Golovin

### Remarks
null


text:
var JSONRPCClient;
var CLIENT_UUID = generateUUID();

$(document).ready( function()
{

    function resizeEditor() {

        // get the new ratio
        var editorRatio = $('#editor-container').height()/aceWrapperHeight;

        aceWrapperHeight = window.innerHeight - $('#wrap').height() - 2;
        $('#ace-wrapper').css({height: aceWrapperHeight});

        $('#editor-container').height(aceWrapperHeight * editorRatio);

        $('#editor-container').resizable({
            containment: '#ace-wrapper',
            handles: 's',
            resize: resize
        });

        resize();

        function resize() {

            $('#console').height($('#ace-wrapper').height() -($('#editor-container').height()));
            sketchEditor.resize();
            consoleEmulator.resize();

        }
    }

    function checkVersion() {
        var releaseURL = "https://api.github.com/repos/olab-io/ofSketch/releases";

        $.getJSON(releaseURL, function(data) {

            if (data.length == 0) {
                console.log("No current releases.");
                return; // no releases
            }

            // Record the latest release.
            var latestRelease = data[0];

            // Get the cleaned semver string.
            var remoteVersion = semver.clean(latestRelease.tag_name);
            var localVersion = semver.clean(systemInfo.version.version);

            $('.local-version').text(localVersion);

            // Compare the semver number provided by the server to the remote.
            if (semver.gt(remoteVersion, localVersion))
            {
                var downloadURL = latestRelease.zipball_url;
                var htmlURL = latestRelease.html_url;
                var assets = latestRelease.assets;

                var target = systemInfo.version.target.toLowerCase();

                var binaryURL = "";

                for (var i = 0; i < assets.length; ++i) {
                    var asset = assets[i]

                    if (asset.name.indexOf(target) >= 0) {
                        // Minor hack because direct access requires header use.
                        // https://developer.github.com/v3/repos/releases/
                        binaryURL = (htmlURL + "/" + asset.name).replace("tag", "download");
                        break;
                    }
                }

                // Attempt to feed a binary url directly if one is available.
                if (binaryURL.length > 0)
                {
                    $('#remote-version-download-link').attr('href', binaryURL);
                }
                else
                {
                    $('#remote-version-download-link').attr('href', htmlURL);
                }

                $('.remote-version').text(remoteVersion);

                $('#version-alert').removeClass('hidden');

            }

        }).fail(function() {
            console.log("Unable to contact github for a version check.");
        });
    }

    function handleServerEvent(evt) {
        if (evt.method == "version")
        {
            // Add version information.
            systemInfo["version"] = evt.params;

            var versionString = "";
            versionString += systemInfo.version.version;
            versionString += " Target: " + systemInfo.version.target;
            versionString += " User-Agent: " + systemInfo.userAgent;

            $("#version").html(versionString);

            var issuePrefill = '\n\n#### User Info\n\n';
            issuePrefill += '- ofSketch ' + systemInfo.version.version + '\n';
            issuePrefill += '- Target: ' + systemInfo.version.target + '\n';
            issuePrefill += '- User-Agent: ' + systemInfo.userAgent + '\n';
            var link = $('#issue-link').attr('href');
            $('#issue-link').attr('href', link + '?body=' + encodeURIComponent(issuePrefill));

            checkVersion();
        }
        else if (evt.method == "addons")
        {
            console.log(evt.params);
        }
        else if (evt.method == "updateEditorSettings")
        {
            // check that the update didn't come from this client
            if (evt.params.clientUUID != CLIENT_UUID) {
                sketchEditor.updateSettings(evt.params.data);
            }
        }
        else if (evt.method == "updateProjectSettings")
        {

        }
        else if (evt.method == "requestProjectClosed")
        {
            if (evt.params.clientUUID != CLIENT_UUID &&
                evt.params.projectName == sketchEditor.getProject().getName()) {
                window.close();
            }
        }
        else if (evt.method == "appExit") {
            window.close();
        }

        console.log(evt);
    }

        // TODO: move this
    function handleLoggerEvent(evt) {
        // console.log(evt);
        if (evt.method == "message")
        {
            var level = evt.params.level;
            var module = evt.params.module;
            var message = evt.params.message;

            logger.log(level, module, message);
            // consoleEmulator.log(message + '\n');
        }
    }

    function handleTaskQueueEvent(evt) {

        // console.log(evt);
        // console.log(evt.params.message);

        if (evt.method == "taskList") {
            // TODO: this is a mess.
            // Needs to be filled out by someone with better HTML js skills :)

            // var li = $("
", {
            //     class: 'list-group-item',
            //     id: 'uuidaiusdiudasduidasd'
            // }).appendTo($('#task-queue-list'));

            // var progressBarContainer = $("
", {
            //     class: 'progress progress-striped active'
            // }).appendTo(li);

            // var progressBar = $("
", {
            //     class: 'progress-bar',
            //     role: 'progressbar',
            //     style: 'width: 100%'
            // }).attr('aria-valuenow','100').attr('aria-valuemin', '0').attr('aria-valuemax', '100');

            // progressBar.appendTo(progressBarContainer);

            // var progressInfo = $("", {
            //     class: 'sr-only',
            //     text: '0% Complete'
            // }).appendTo(progressBarContainer);

            // var button = $('<button/>', {
            //     type: 'button',
            //     class: 'btn btn-default btn-sm glyphicon glyphicon-remove',
            //     click: function() {
            //         console.log("Task Cancel clicked.");
            //     }
            // }).appendTo(li);

        } else if (evt.method == "taskQueued") {
            // TODO: add a task for the uuid

        } else if (evt.method == "taskStarted") {
            // TODO: add a task for the uuid

        } else if (evt.method == "taskCancelled") {
            // TODO: remove the task with the uuid

        } else if (evt.method == "taskFinished") {
            // TODO: remove the task with the uuid
            if (evt.params.uuid == sketchEditor.getCurrentRunTaskId()) {

                if (sketchEditor.isCompiling()) {

                    sketchEditor.setCompiling(false);
                    if (compileSuccess) { // this is a terrible way to do this
                        consoleEmulator.clear();
                        sketchEditor.run(function(){}, runError);
                        compileSuccess = false;
                    } else {
                        // compileError();
                    }
                }
            }

        } else if (evt.method == "taskFailed") {
            // TODO: remove the task with the uuid

        } else if (evt.method == "taskProgress") {
            // TODO: remove the task with the uuid

        } else if (evt.method == "taskMessage") {
            // TODO: remove the task with the uuid
            // update the message in the li with the message
            if (evt.params.uuid == sketchEditor.getCurrentRunTaskId()) {

                // this is a terrible hack
                if (evt.params.message.indexOf("make RunRelease") != -1) {
                    compileSuccess = true;
                }

                // if message is compilation error
                if (!_.isUndefined(evt.params.compileError)) {
                    sketchEditor.annotate(evt.params.compileError);
                }

                consoleEmulator.log(evt.params.message + '\n');
            }

        } else {

            console.log("Unknown Task Queue method.");
            console.log(evt);
        }
    }

    function onWebSocketOpen(evt) {
        console.log("on open");
        console.log(evt);
    }

    function onWebSocketMessage(evt) {
        try {
            var json = JSON.parse(evt.data);

            if (json.module == "Logger") {
                handleLoggerEvent(json);
            } else if (json.module == "TaskQueue") {
                handleTaskQueueEvent(json);
            } else if (json.module == "Server") {
                handleServerEvent(json);
            } else {
                console.log("Unknown Module: " + json.module);
                console.log(json);
            }
        } catch (e) {
            console.log("Unknown Websocket Data Type");
            console.log(e);
            console.log(evt.data);
        }
    }

    function onWebSocketClose(evt) {
        // console.log("on close");
        // console.log(evt);
        $('#server-disconnected-modal').modal();
        sketchEditor.setDisabled(true);
    }

    function onWebSocketError(evt) {
        console.log("on error");
        console.log(evt);
    }

    function saveError(err) {
        console.log("Error saving project");
        console.log(err);
        alertMessage('Save Error!', '', 'alert-danger');
    }

    function loadError(err) {
        console.log("Error loading project");
        console.log(err);
        alertMessage('Load Error!', '', 'alert-danger');
    }

    function createProjectError(err) {
        console.log('Error creating project: ');
        console.log(err);
    }

    function renameProjectError(err) {
        console.log('Error renaming project: ');
        console.log(err);
    }

    function runError(err) {
        console.log('Error running project: ');
        console.log(err);
    }

    function compileError(message, subMessage) {
        var m = message || "Error";
        var s = subMessage || '(see console for more info)';
        alertMessage(m, s, 'alert-danger');
    }

    function createClassError(err) {
        console.log("Error creating class");
        alertMessage('Error Creating Class!', '', 'alert-danger');
    }

    function saveAlert(message, subMessage) {
        // var m = message || "Project saved!";
        // var s = subMessage || '';
        // alertMessage(m, s, "alert-success");
    }

    function runAlert(message, subMessage) {
        var m = message || "Running Project...";
        var s = subMessage || '';
        alertMessage(m, s, "alert-info");
    }

    function alertMessage(message, subMessage, c) {

        clearTimeout(alertTimeout);
        alertBox.removeClass();
        alertBox.addClass('alert ' + c);
        alertBox.html('' + message + ' ' + subMessage);
        alertBox.css({
            left:$(window).width()/2 - alertBox.width()/2,
            top: $(window).height()/2 - alertBox.height()/2
        });

        alertBox.show();
        alertTimeout = setTimeout(function(){
            alertBox.hide();
        }, 2500);
    }

    function parseURLParameters()
    {
        var project = getURLParameter('project');
        if (project) {

            sketchEditor.getProjectList(function(result){
                var match = _.findWhere(result, { projectName: project });
                if (match) {
                    sketchEditor.loadProject(project, function(result) {
                        $('title').text(project);
                        if (result.alreadyOpen == true){
                            $('#project-already-open-modal').modal('show');
                            sketchEditor.setDisabled(true);
                        }
                    }, loadError);
                } else {
                    sketchEditor.loadTemplateProject(function(){
                        $('#project-not-found-modal').modal('show');
                    }, loadError);
                }
            }, function(err) {
                console.log("Error requesting project list: ");
                console.log(err);
            });

        } else {

            sketchEditor.loadTemplateProject(function(){}, loadError);
        }
    }

    function run()
    {
        if (!sketchEditor.isDisabled()) {

            if (!sketchEditor.getProject().isTemplate()) {
                sketchEditor.saveProject(function() {
                    runAlert();
                    consoleEmulator.clear();
                    sketchEditor.clearAnnotations();
                    if (sketchEditor.isRunning()) {
                        sketchEditor.stop(function(){
                            sketchEditor.compile(function(){});
                        });
                    } else {
                        sketchEditor.compile(function(){});
                    }

                }, saveError);
            } else {
                $('#name-project-modal').modal();
            }
        }
    }

    function save()
    {
        if (!sketchEditor.isDisabled()) {

            if (sketchEditor.projectLoaded()) {
                if (!sketchEditor.getProject().isTemplate()) {
                    sketchEditor.saveProject(function() {
                        saveAlert();
                    }, saveError);
                } else {
                    $('#name-project-modal').modal();
                }
            }
        }
    }

    function openProject()
    {
        sketchEditor.getProjectList(function(result) {

            var projectList = $('#project-list');
            projectList.empty();
            _.each(result, function(project) {
                var linkElement = $('' + project.projectName + '');

                linkElement.on('click', function(){
                    $('#open-project-modal').modal('hide');
                });

                projectList.append(linkElement);
            });

            $('#open-project-modal').modal();

        }, function(err) {
            console.log("Error requesting project list: ");
            console.log(err);
        });
    }

    // localization
    $('[data-localize]').localize('lang', { pathPrefix: "../../localization", skipLanguage: /^en/ });

    // prevent defaults
    $('#toolbar li a, #log-levels li a, .file-tab a, #new-class a, .action-menu li a').on('click', function(e) {
        e.preventDefault();
    });

    $(window).on('beforeunload', function(){
        sketchEditor.notifyProjectClosed();
    });

    // key bindings
    $(document).on("keydown", function(e){

        // cmd-r, ctrl-r
        if ((e.which || e.keyCode) == 116 && (e.metaKey || e.ctrlKey) ||
            (e.which || e.keyCode) == 82 && (e.metaKey || e.ctrlKey)) {

            e.preventDefault();
            run();
        }

        // cmd-s, ctrl-s
        if ((e.which || e.keyCode) == 83 && (e.metaKey || e.ctrlKey)) {

            e.preventDefault();
            save();
        }

        // cmd-o, ctrl-o
        if ((e.which || e.keyCode) == 79 && (e.metaKey || e.ctrlKey)) {

            e.preventDefault();
            openProject();
        }

    });

    $('.needs-validation').on('');

    var systemInfo = {
        userAgent:  navigator.userAgent
    }

    var alertTimeout;
    var alertBox;
    var aceWrapperHeight;
    var compileSuccess = false; // this is a terrible global var. Get it out ASAP.
    var inputRegex = /^[A-Za-z0-9_-]+$/;
    alertBox = $('#editor-messages');
    alertBox.hide();

    var logger = new Logger();

    JSONRPCClient = new $.JsonRpcClient({
            ajaxUrl: getDefaultPostURL(),
            socketUrl: getDefaultWebSocketURL(), // get a websocket for the localhost
            onmessage: onWebSocketMessage,
            onopen: onWebSocketOpen,
            onclose: onWebSocketClose,
            onerror: onWebSocketError
        });

    $('#set-log-level').addClass(logger.getLogLevelLabelClass(logger.getLogLevel()));
    $('#current-log-level').text(logger.getLogLevelName(logger.getLogLevel()));

    $('#log-levels li a').on('click', function() {

        var logLevel = parseInt($(this).data('log-level'));
        logger.setLogLevel(logLevel);

        var button = $('#set-log-level');
        button.removeClass();
        button.addClass('btn btn-xs dropdown-toggle ' + logger.getLogLevelLabelClass(logLevel));
        $('#current-log-level').text($(this).text());
    });

    var consoleEmulator = new ConsoleEmulator();

    var sketchEditor = new SketchEditor(function() {

        // editor resize stuff
        aceWrapperHeight = window.innerHeight - $('#wrap').height() - 2;
        $('#editor-container').height(aceWrapperHeight * 3/4);
        $('#console').height(aceWrapperHeight * 1/4);

        resizeEditor();

        // events
        $(window).resize(function(){
            sketchEditor.resize();
            resizeEditor();
        });

        $('#tab-bar .dropdown').on('click', function(){

            var tabName = sketchEditor.getSelectedTabName();
            if (tabName == sketchEditor.getProject().getName()) {
                $('.rename-class, .delete-class').addClass('disabled');
                $('.selected-tab-name').text('');
            } else {
                $('.rename-class, .delete-class').removeClass('disabled');
                $('.selected-tab-name').text(tabName);
            }
        });

        $('#toolbar-run').on('click', function() {
            run();
        });

        $('#toolbar-stop').on('click', function() {
            if (sketchEditor.isRunning() &&
                !$(this).hasClass('disabled')) {
                sketchEditor.stop(function(){
                    // callback
                }, runError);
            }
        });

        $('#toolbar-save').on('click', function() {
           save();
        });

        $('#toolbar-addons').on('click', function(){

            if (!sketchEditor.getProject().isTemplate()) {

                sketchEditor.getAddonList(function(globalAddons) {

                    sketchEditor.getProject().getAddonList(function(projectAddons){

                        var coreAddonsList = $('#core-addons-list');
                        var contributedAddonsList = $('#contributed-addons-list');

                        var hasContributedAddons = false;

                        // core addons at openFrameworks master.
                        // Eventually these should be seperated at the backend.
                        var coreAddons = [

                            "ofx3DModelLoader",
                            "ofxAccelerometer",
                            "ofxAndroid",
                            "ofxAssimpModelLoader",
                            "ofxEmscripten",
                            "ofxGui",
                            "ofxKinect",
                            "ofxMultiTouch",
                            "ofxNetwork",
                            "ofxOpenCv",
                            "ofxOsc",
                            "ofxSvg",
                            "ofxSynth",
                            "ofxThreadedImageLoader",
                            "ofxVectorGraphics",
                            "ofxXmlSettings",
                            "ofxiOS"
                        ];

                        coreAddonsList.empty();
                        contributedAddonsList.empty();

                        _.each(globalAddons, function(globalAddon) {

                            // if this addon is already included
                            var alreadyInProject = projectAddons.indexOf(globalAddon.name) != -1;

                            var linkElement = $(''
                                                 + globalAddon.name + ''
                                                 +'Included');

                            if (alreadyInProject) {
                                linkElement.addClass('list-group-item-info');
                                linkElement.find('.include-marker').show();
                            }

                            linkElement.on('click', function(e){

                                e.preventDefault();

                                var addon = globalAddon.name;
                                var isIncluded = $(this).data('included');

                                if (!isIncluded) {

                                    sketchEditor.getProject().addAddon(addon,
                                                                       function(){

                                                                        isIncluded = !isIncluded;
                                                                        linkElement.addClass('list-group-item-info');
                                                                        linkElement.find('.include-marker').show();
                                                                        linkElement.data('included', isIncluded);

                                                                       }, function(err){
                                                                        console.log(err);
                                                                       });
                                } else {

                                    sketchEditor.getProject().removeAddon(addon,
                                                                       function(){

                                                                        isIncluded = !isIncluded;
                                                                        linkElement.removeClass('list-group-item-info');
                                                                        linkElement.find('.include-marker').hide();
                                                                        linkElement.data('included', isIncluded);

                                                                       }, function(err){
                                                                        console.log(err);
                                                                       });
                                }

                            });

                            if (coreAddons.indexOf(globalAddon.name) != -1) coreAddonsList.append(linkElement);
                            else {

                                if (!hasContributedAddons) {
                                    hasContributedAddons = true;
                                    $('#contributed-addons-container').show();
                                }

                                contributedAddonsList.append(linkElement);

                            }
                        });
                    }, console.log);

                    $('#addons-modal').modal();

                }, function(err) {
                    console.log("Error requesting addon list: ");
                    console.log(err);
                });

            } else {
                $('#name-project-modal').modal();
            }
        });

        $('.open-project').on('click', function() {
            openProject();
        });

        $('.new-project').on('click', function() {
            window.open(window.location.protocol + '//' + window.location.host, '_blank');
        });

        $('#editor-settings').on('click', function(e){
            sketchEditor.showSettingsMenu();
        });

        // Modals
        $('.new-class').on('click', function() {
            if (!sketchEditor.getProject().isTemplate()) {
                $('#new-class-modal').modal();
            } else {
                $('#name-project-modal').modal();
            }

        });

        $('.rename-class').on('click', function() {
            if (!$(this).hasClass('disabled')) {
                $('#rename-class-modal').modal();
            }
        });

        $('.delete-class').on('click', function() {
            if (!$(this).hasClass('disabled')) {
                $('#delete-class-modal').modal();
            }
        });

        $('.delete-project').on('click', function() {
            $('#delete-project-modal').modal();
        });

        $('.rename-project').on('click', function() {
            if (!sketchEditor.getProject().isTemplate()) {
                $('#rename-project-modal').modal();
            } else {
                $('#name-project-modal').modal();
            }
        });

        $('.close-project').on('click', function(){
            if (!$(this).hasClass('disabled')) {
                window.close();
            }
        });

        $('.quit-app').on('click', function(){
            sketchEditor.requestAppQuit(function(){
                window.close();
            });
        });

        $('#create-class').on('click', function() {

            $('#new-class-modal .alert').hide();
            var className = $('#new-class-name').val();
            if (!inputRegex.test(className)) {
                $('#new-class-modal .validation-error').show();
            }
            else if (sketchEditor.getProject().isClassName(className)) {
                $('#new-class-modal .name-taken-error').show();
            }
            else {
                sketchEditor.createClass(className, function() {

                    $('#new-class-modal').modal('hide');
                    $('#new-class-name').val('');

                    sketchEditor.selectTab(className);
                    sketchEditor.saveProject(function(){}, saveError)

                }, createClassError);
            }
        });

        $('#delete-class').on('click', function() {

            var projectName = sketchEditor.getProject().getName();
            var tabName = sketchEditor.getSelectedTabName();
            if (tabName != projectName) {
                sketchEditor.deleteClass(tabName, function() {
                    sketchEditor.selectTab(projectName);
                }, function(err) {
                    console.log("Error deleting class: ");
                    console.log(err)
                });
            }
        });

        $('#rename-class').on('click', function() {

            $('#rename-class-modal .alert').hide();

            var projectName = sketchEditor.getProject().getName();
            var tabName = sketchEditor.getSelectedTabName();
            var newClassName = $('#renamed-class-name').val();

            if (tabName != projectName) {

                if (!inputRegex.test(newClassName)) {
                    $('#rename-class-modal .validation-error').show();
                }
                else if(sketchEditor.getProject().isClassName(newClassName)) {
                    $('#rename-class-modal .name-taken-error').show();
                }
                else {

                    sketchEditor.renameClass(tabName, newClassName, function() {

                       $('#rename-class-modal').modal('hide');
                       $('#renamed-class-name').val('');

                    }, function(err) {
                        console.log('Error renaming class: ');
                        console.log(err);
                    });
                }
            }
        });

        $('#name-project').on('click', function() {

            $('#name-project-modal .alert').hide();
            var projectName = $('#new-project-name').val();

            if (!inputRegex.test(projectName)) {
                $('#name-project-modal .validation-error').show();
            }
            else {

                sketchEditor.getProjectList(function(result){

                    var match = _.findWhere(result, { projectName: projectName });
                    if (match) {
                        $('#name-project-modal .name-taken-error').show();
                    } else {

                        sketchEditor.createProject(projectName, function() {
                           sketchEditor.saveProject(function(){
                                window.location.href = window.location.protocol
                                                       + "//" + window.location.host
                                                       + "/?project=" + encodeURIComponent(projectName);
                           }, saveError);
                        }, createProjectError);
                    }

                }, function(err){
                    console.log("Error getting project list:");
                    console.log(err);
                });
            }
        });

        $('#delete-project').on('click', function() {
            if (!sketchEditor.getProject().isTemplate()) {
                sketchEditor.deleteProject(function(){
                    navigateToNewProject();
                }, function(){

                });
            } else {
                navigateToNewProject();
            }

            function navigateToNewProject() {
                window.location.href = window.location.protocol
                                               + "//" + window.location.host;
            }
        });

        $('#rename-project').on('click', function() {

            $('#rename-project-modal .alert').hide();
            var newProjectName = $('#renamed-project-name').val();
            if (!sketchEditor.getProject().isTemplate()) {

                if (!inputRegex.test(newProjectName)) {
                    $('#rename-project-modal .validation-error').show();
                } else {

                    sketchEditor.getProjectList(function(result){

                        var match = _.findWhere(result, { projectName: newProjectName });
                        if (match) {
                            $('#rename-project-modal .name-taken-error').show();
                        } else {
                            sketchEditor.renameProject(newProjectName, function(){
                                sketchEditor.saveProject(function(){
                                    window.location.href = window.location.protocol
                                                           + "//" + window.location.host
                                                           + "/?project=" + encodeURIComponent(newProjectName);
                               }, saveError);
                            }, renameProjectError);
                        }
                    }, function(err){
                        console.log('Error getting project list: ');
                        console.log(err);
                    });
                }

            } else {
                // project is template
            }

        });

        $('#request-project-closed').on('click', function(){
            sketchEditor.requestProjectClosed(function(){
                $('#project-already-open-modal').modal('hide');
                sketchEditor.setDisabled(false);
            });
        });

        // Modal Events
        $('#name-project-modal').on('shown.bs.modal', function () {
            $('#new-project-name').focus();
        });

        $('#rename-project-modal').on('shown.bs.modal', function () {
            $('#renamed-project-name').focus();
        });

        $('#new-class-modal').on('shown.bs.modal', function () {
            $('#new-class-name').focus();
        });

        $('#rename-class-modal').on('shown.bs.modal', function () {
            $('#renamed-class-name').focus();
        });

        parseURLParameters();

    });
});


text:
ACCEPTED

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

#### Published in
Bull. Tokyo Sci. Mus. 6: 104 (1943)

#### Original name
Fomes setulosus Lloyd, 1915

### Remarks
null


text:
package jhttpserver.entity;

import jhttpserver.interfaces.Execution;

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

/**
 * 请求处理句柄
 */
public class Handler {
    /**
     * 处理器
     */
    private Map<String ,Execution> exes = new HashMap<String,Execution>();

    public Handler(){

    }
    /**
     * 获得对应处理器
     * @param request_method
     * @return
     */
    public Execution getExecution(String request_method){
    	return this.exes.get(request_method.toUpperCase());
    }
    /**
     * 注册对应的处理器
     * @param method
     * @param exe
     */
    public void register(String method,Execution exe){
        this.exes.put(method.toUpperCase(),exe);
    }

    /**
     * 根据请求方法调用对应的处理器
     * @param request
     * @param response
     */
    public void onExecute(Request request, Response response) {
       if(getExecution(request.getMethod()) != null){
    	   getExecution(request.getMethod()).onExecute(request,response);
       }else{
           //TODO 默认一个GET?
           //TODO 跑出一个异常 or 500?
           System.out.println("没有对应的处理器");
       }

    }
}


text:
package cn.iaicc.smgk.web.action.manage.delete;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.iaicc.smgk.business.IEmployeeInfoService;
import cn.iaicc.smgk.business.ISelectWeightInfoService;
import cn.iaicc.smgk.po.EmployeeInfo;
import cn.iaicc.smgk.po.SelectWeightInfo;
import cn.iaicc.smgk.web.conf.StatusConstants;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DeleteWeightAction extends ActionSupport {
	/**
	 *
	 */
	private static final long serialVersionUID = 453855886740013266L;
	private static Log logger = LogFactory.getLog(DeleteWeightAction.class);
	private ISelectWeightInfoService selectWeightInfoService = null;
	private IEmployeeInfoService employeeInfoService = null;

	private Long selectWeightID = null;

	@Override
	public String execute() throws Exception {

		try{
			String username = (String)ActionContext.getContext().getSession().get("LOGINUSERNAME");
			String password = (String)ActionContext.getContext().getSession().get("LOGINPASSWORD");
			if(username == null || password == null) {
				return LOGIN;
			}
			if(selectWeightID == null)return ERROR;
			SelectWeightInfo info = selectWeightInfoService.getSelectWeightInfo(selectWeightID);
			info.setStatus(StatusConstants.SHANCHU);
			selectWeightInfoService.update(info);
		}catch(Exception e) {
			logger.error(""+e.getMessage(),e.getCause());
		}

		return SUCCESS;
	}

	public void setEmployeeInfoService(IEmployeeInfoService employeeInfoService) {
		this.employeeInfoService = employeeInfoService;
	}

	public Long getSelectWeightID() {
		return selectWeightID;
	}

	public void setSelectWeightID(Long selectWeightID) {
		this.selectWeightID = selectWeightID;
	}

	public void setSelectWeightInfoService(
			ISelectWeightInfoService selectWeightInfoService) {
		this.selectWeightInfoService = selectWeightInfoService;
	}

}


text:
<title>dlib C++ Library - cross_validate_track_association_trainer_abstract.h</title>

// Copyright (C) 2014  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_CROSS_VALIDATE_TRACK_ASSOCIATION_TrAINER_ABSTRACT_Hh_
#ifdef DLIB_CROSS_VALIDATE_TRACK_ASSOCIATION_TrAINER_ABSTRACT_Hh_

#include "structural_track_association_trainer_abstract.h"
#include "svm_abstract.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    template <
        typename track_association_function,
        typename detection_type,
        typename label_type
        >
    double test_track_association_function (
        const track_association_function& assoc,
        const std::vector<std::vector<std::vector<labeled_detection<detection_type,label_type> > > >& samples
    );
    /*!
        requires
            - is_track_association_problem(samples)
            - track_association_function == an instantiation of the dlib::track_association_function
              template or an object with a compatible interface.
        ensures
            - Tests assoc against the given samples and returns the fraction of detections
              which were correctly associated to their tracks.  That is, if assoc produces
              perfect tracks when used then this function returns a value of 1.  Similarly,
              if 5% of the detections were associated to the incorrect track then the
              return value is 0.05.
    !*/

// ----------------------------------------------------------------------------------------

    template <
        typename trainer_type,
        typename detection_type,
        typename label_type
        >
    double cross_validate_track_association_trainer (
        const trainer_type& trainer,
        const std::vector<std::vector<std::vector<labeled_detection<detection_type,label_type> > > >& samples,
        const long folds
    );
    /*!
        requires
            - is_track_association_problem(samples)
            - 1 < folds <= samples.size()
            - trainer_type == dlib::structural_track_association_trainer or an object with
              a compatible interface.
        ensures
            - Performs k-fold cross validation by using the given trainer to solve the
              given track association learning problem for the given number of folds.  Each
              fold is tested using the output of the trainer and the fraction of
              mis-associated detections is returned (i.e. this function returns the same
              measure of track association quality as test_track_association_function()).
            - The number of folds used is given by the folds argument.
    !*/

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_CROSS_VALIDATE_TRACK_ASSOCIATION_TrAINER_ABSTRACT_Hh_


text:
<!DOCTYPE html>

		<title>FeaturesViewEngine with caching</title>
		<meta http-equiv="REFRESH" content="0; url=/2018/02/28/featuresviewengine-with-caching/">
		<link rel="canonical" href="/2018/02/28/featuresviewengine-with-caching/" />

		This page has moved. You will be automatically redirected to its new location. If you aren't forwarded to the new page, click here.


text:
/*-------------------------------------------------------------------*/
/* Copyright IBM Corp. 2013 All Rights Reserved                      */
/*-------------------------------------------------------------------*/

;(function(){  // IIFE begin

var ucKey    = "tia.cache.userController"
var usersKey = "tia.cache.users"

//------------------------------------------------------------------------------
Tia.loadUserControllerCache = function($scope) {
    var key = ucKey + "." + $scope.twitterSN
    loadScope($scope, key, "score")
    loadScope($scope, key, "profileImage")
}

//------------------------------------------------------------------------------
Tia.saveUserControllerCache = function($scope) {
    var key = ucKey + "." + $scope.twitterSN
    saveScope($scope, key, "score")
    saveScope($scope, key, "profileImage")
}

//------------------------------------------------------------------------------
function loadScope($scope, keyPrefix, key) {
    var val = localStorage.getItem(keyPrefix + "." + key)
    if (val == null) return

    $scope[key] = val
}

//------------------------------------------------------------------------------
function saveScope($scope, keyPrefix, key) {
    if ($scope[key] == null) return

    localStorage.setItem(keyPrefix + "." + key, $scope[key])
}

})(); // IIFE end


text:
include_recipe "build-essential"

pkgs = value_for_platform_family(
    ["rhel","fedora"] => %w{ openssl-devel gd-devel },
    "debian" => %w{ libssl-dev libgd2-xpm-dev },
    "default" => %w{ libssl-dev libgd2-xpm-dev }
  )

pkgs.each do |pkg|
  package pkg do
    action :install
  end
end

user node['nagios']['user'] do
  system true
end

group node['nagios']['group'] do
  members [ node['nagios']['user'] ]
end

plugins_version = node['nagios']['plugins']['version']

remote_file "#{Chef::Config[:file_cache_path]}/nagios-plugins-#{plugins_version}.tar.gz" do
  source "#{node['nagios']['plugins']['url']}/nagios-plugins-#{plugins_version}.tar.gz"
  checksum node['nagios']['plugins']['checksum']
  action :create_if_missing
end

bash "compile-nagios-plugins" do
  cwd Chef::Config[:file_cache_path]
  code <<-EOH
    tar zxvf nagios-plugins-#{plugins_version}.tar.gz
    cd nagios-plugins-#{plugins_version}
    ./configure --with-nagios-user=#{node['nagios']['user']} \
                --with-nagios-group=#{node['nagios']['group']} \
                --prefix=/usr \
                --libexecdir=#{node['nagios']['plugin_dir']}
    make -s
    make install
  EOH
  creates "#{node['nagios']['plugin_dir']}/check_users"
end

nrpe_version = node['nagios']['nrpe']['version']

remote_file "#{Chef::Config[:file_cache_path]}/nrpe-#{nrpe_version}.tar.gz" do
  source "#{node['nagios']['nrpe']['url']}/nrpe-#{nrpe_version}.tar.gz"
  checksum node['nagios']['nrpe']['checksum']
  action :create_if_missing
end

bash "compile-nagios-nrpe" do
  cwd Chef::Config[:file_cache_path]
  code <<-EOH
    tar zxvf nrpe-#{nrpe_version}.tar.gz
    cd nrpe-#{nrpe_version}
    ./configure --prefix=/usr \
                --sysconfdir=/etc \
                --localstatedir=/var \
                --libexecdir=#{node['nagios']['plugin_dir']} \
                --libdir=#{node['nagios']['nrpe']['home']} \
                --enable-command-args
    make -s
    make install
  EOH
  creates "#{node['nagios']['plugin_dir']}/check_nrpe"
end

template "/etc/init.d/nagios-nrpe-server" do
  source "nagios-nrpe-server.erb"
  owner "root"
  group "root"
  mode  00755
end

directory node['nagios']['nrpe']['conf_dir'] do
  owner "root"
  group "root"
  mode  00755
end


text:
<!DOCTYPE html>

    <meta name="google-site-verification" content="UrrBw_Ttm8j8WLCK_S5GBLU0pB5EPyZawb_vXaPFfvc" />
    <meta charset="utf-8" />
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <title>FAQs: NZ BODY MECHANIC</title>

    <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

    <meta name="author" content="NZ Body Mechanic" />
    <meta name="description" content="">

    <link rel="stylesheet" type="text/css" href="/skeleton/css/normalize.css" />
    <link rel="stylesheet" type="text/css" href="/skeleton/css/skeleton.css" />
    <link rel="stylesheet" type="text/css" href="/skeleton/css/custom.css" />

    <link rel="alternate" type="application/rss+xml" title="NZ Body Mechanic - For musculoskeletal maintenance and theraputic tune ups" href="/feed.xml" />

    <link rel="icon" type="image/png" href="/images/favicon.png">

Call Isaac on 021 0230 7287 or book online

About

Clients

FAQs

Stretching Videos

Contact

FAQs

"Get answers to your questions about how massage can help you."

Q.  Why is massage good for me?

The short answer is, it makes you feel better!

The scientific answer is a bit longer... Whenever a person spends any length of time in a sustained posture or performing similar movements, muscular tone is increased and with increased muscular tone comes decreased blood flow and drainage of lymph (fluid that is not blood). As a result pain signals can be triggered causing the aches and pains we all experience from time to time. With injury this increase in tone is far greater, widespread and longer lasting.

Massage and manual manipulation attempts to restore healthy fluid dynamics to the tissues. When the fluid dynamics are improved so are the supply of nutrients and oxygen as well as the movement of metabolic waste products that can build up in the tissues.

Stimulation of tissues = improved fluid dynamics = healthy tissues and restored functionality, or massage = body feels good.

Q.  Will just one massage be enough?

It always depends on the person and how long the condition has been there.  The longer standing the condition the more treatments may be necessary, but most of my clients see me once a month or more.

Q.  Do your treatments hurt?

It is necessary for best results to apply a certain amount of pressure to the tissues. If you are excessively tight or restricted in movement a small to medium level of discomfort is to be expected at various stages of the treatment, but I will ask you how it is feeling and adjust as necessary.

Q.  Do I have to take off all my clothes to get a massage?

In most cases you are required to remove all clothing down to your underwear. However you will be covered by a towel the whole time.  If you do not feel comfortable removing clothing, it is usually possible to treat using pressure through the clothing.

Q.  Is there anything special I need to do before a massage?  Or after?

It is important to keep your water intake up before and after a massage. The reason is that we are usually dealing with a dysfunctional fluid flow and the intention of a treatment is to restore fluid dynamics therefore drinking water before and after a treatment is an essential part of the treatment process.
It is also important to avoid alcohol, coffee, and energy drinks after a treatment as these are diuretics and will encourage your body to get rid of the much needed water in the tissues.
It's a good idea to drink lots of water for the rest of the day to help flush the toxins out of the system too.  When you come and see me, I'll also give you some self help tips, which include things like stretches and specific exercises to work on your particular trouble area.  You will be feeling better in no time!

Q.  I've got sensitive skin.  Will your massage oil irritate my skin?

The oil I use is high quality and does not cause a reaction for most people. However I can do most of the techniques without oil, using pressure and gentle stretching.

Got another question? Just ask.

Next: Check out some stretching videos for use after your treatment.

About

Contact

Facebook

LinkedIn

Words and pictures © NZ Body Mechanic 2013-2015


text:
package slack

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/url"
)

// API chat.postMessage: Sends a message to a channel.
func (sl *Slack) ChatPostMessage(channelId string, text string, opt *ChatPostMessageOpt) error {
	uv, err := sl.buildChatPostMessageUrlValues(opt)
	if err != nil {
		return err
	}
	uv.Add("channel", channelId)

	body, err := sl.PostRequest(chatPostMessageApiEndpoint, uv, sl.buildRequestBodyForm(text))
	if err != nil {
		return err
	}
	res := new(ChatPostMessageAPIResponse)
	err = json.Unmarshal(body, res)
	if err != nil {
		return err
	}
	if !res.Ok {
		return errors.New(res.Error)
	}
	return nil
}

// option type for `chat.postMessage` api
type ChatPostMessageOpt struct {
	AsUser      bool
	Username    string
	Parse       string
	LinkNames   string
	Attachments []*Attachment
	UnfurlLinks string
	UnfurlMedia string
	IconUrl     string
	IconEmoji   string
}

// response type for `chat.postMessage` api
type ChatPostMessageAPIResponse struct {
	BaseAPIResponse
	Channel string `json:"channel"`
	Ts      string `json:"ts"`
}

func (sl *Slack) buildRequestBodyForm(text string) (*bytes.Buffer) {
    return bytes.NewBuffer([]byte("text=" + text))
}

func (sl *Slack) buildChatPostMessageUrlValues(opt *ChatPostMessageOpt) (*url.Values, error) {
	uv := sl.urlValues()
	if opt == nil {
		return uv, nil
	}
	if opt.AsUser {
		uv.Add("as_user", "true")
	} else if opt.Username != "" {
		uv.Add("username", opt.Username)
	}
	if opt.Parse != "" {
		uv.Add("parse", opt.Parse)
	}
	if opt.LinkNames != "" {
		uv.Add("link_names", opt.LinkNames)
	}
	if opt.UnfurlLinks != "" {
		uv.Add("unfurl_links", opt.UnfurlLinks)
	}
	if opt.UnfurlMedia != "" {
		uv.Add("unfurl_media", opt.UnfurlMedia)
	}
	if opt.IconUrl != "" {
		uv.Add("icon_url", opt.IconUrl)
	}
	if opt.IconEmoji != "" {
		uv.Add("icon_emoji", opt.IconEmoji)
	}
	if opt.Attachments != nil && len(opt.Attachments) > 0 {
		ats, err := json.Marshal(opt.Attachments)
		if err != nil {
			return nil, err
		}
		uv.Add("attachments", string(ats))
	}
	return uv, nil
}


text:
package core

import akka.actor.{Props, ActorSystem}
import scala.annotation.tailrec
import core.TweetReaderActor.{FindAll, CountAll}

object Main extends App with ConfigCassandraCluster {
  import Commands._
  import akka.actor.ActorDSL._

  def twitterSearchProxy(query: String) = s"http://twitter-search-proxy.herokuapp.com/search/tweets?q=$query"

  implicit lazy val system = ActorSystem()
  val write = system.actorOf(Props(new TweetWriterActor(cluster)))
  val read = system.actorOf(Props(new TweetReaderActor(cluster)))
  val scan = system.actorOf(Props(new TweetScannerActor(write, twitterSearchProxy)))
  implicit val _ = actor(new Act {
    become {
      case x => println(">>> " + x)
    }
  })

  @tailrec
  private def commandLoop(): Unit = {
    Console.readLine() match {
      case QuitCommand                => return

      case ScanCommand(query)         => scan ! query

      case ListCommand(count)         => read ! FindAll(count.toInt)
      case CountCommand               => read ! CountAll

      case _                          => println("WTF??!!")
    }

    commandLoop()
  }

  // start processing the commands
  commandLoop()

  system.shutdown()
}

/**
 * Various regexes for the ``Shell`` to use
 */
object Commands {

  val ListCommand  = "list (\\d+)".r
  val CountCommand = "count"
  val QuitCommand  = "quit"
  val ScanCommand  = "scan (.*)".r

}


text:
declare module 'assert' {
    function assert(value: any, message?: string | Error): asserts value;
    namespace assert {
        class AssertionError implements Error {
            name: string;
            message: string;
            actual: any;
            expected: any;
            operator: string;
            generatedMessage: boolean;
            code: 'ERR_ASSERTION';

            constructor(options?: {
                message?: string;
                actual?: any;
                expected?: any;
                operator?: string;
                stackStartFn?: Function;
            });
        }

        type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error;

        function fail(message?: string | Error): never;
        /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
        function fail(
            actual: any,
            expected: any,
            message?: string | Error,
            operator?: string,
            stackStartFn?: Function,
        ): never;
        function ok(value: any, message?: string | Error): asserts value;
        /** @deprecated since v9.9.0 - use strictEqual() instead. */
        function equal(actual: any, expected: any, message?: string | Error): void;
        /** @deprecated since v9.9.0 - use notStrictEqual() instead. */
        function notEqual(actual: any, expected: any, message?: string | Error): void;
        /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */
        function deepEqual(actual: any, expected: any, message?: string | Error): void;
        /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */
        function notDeepEqual(actual: any, expected: any, message?: string | Error): void;
        function strictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
        function notStrictEqual(actual: any, expected: any, message?: string | Error): void;
        function deepStrictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
        function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void;

        function throws(block: () => any, message?: string | Error): void;
        function throws(block: () => any, error: AssertPredicate, message?: string | Error): void;
        function doesNotThrow(block: () => any, message?: string | Error): void;
        function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void;

        function ifError(value: any): asserts value is null | undefined;

        function rejects(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
        function rejects(
            block: (() => Promise<any>) | Promise<any>,
            error: AssertPredicate,
            message?: string | Error,
        ): Promise<void>;
        function doesNotReject(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
        function doesNotReject(
            block: (() => Promise<any>) | Promise<any>,
            error: RegExp | Function,
            message?: string | Error,
        ): Promise<void>;

        function match(value: string, regExp: RegExp, message?: string | Error): void;
        function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;

        const strict: Omit<
            typeof assert,
            | 'strict'
            | 'deepEqual'
            | 'notDeepEqual'
            | 'equal'
            | 'notEqual'
            | 'ok'
            | 'strictEqual'
            | 'deepStrictEqual'
            | 'ifError'
        > & {
            (value: any, message?: string | Error): asserts value;
            strict: typeof strict;
            deepEqual: typeof deepStrictEqual;
            notDeepEqual: typeof notDeepStrictEqual;
            equal: typeof strictEqual;
            notEqual: typeof notStrictEqual;
            ok(value: any, message?: string | Error): asserts value;
            strictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
            deepStrictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
            ifError(value: any): asserts value is null | undefined;
        };
    }

    export = assert;
}


text:
package io.datalayer.data.queue;

import io.datalayer.data.comparator.Comparator;
import io.datalayer.data.queue.HeapOrderedListPriorityQueue;
import io.datalayer.data.queue.Queue;

/**
 * Concrete tests for {@link io.datalayer.data.queue.HeapOrderedListPriorityQueue}.
 *
 */
public class HeapOrderedListPriorityQueueTest extends AbstractPriorityQueueTestCase {
    protected Queue createQueue(Comparator comparator) {
        return new HeapOrderedListPriorityQueue(comparator);
    }
}


text:
use clone::Clone;
use cmp::PartialEq;
use std::fmt::Show;
use slice;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use option::{None, Option, Some};

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
///
/// See the [`std::result`](index.html) module documentation for details.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
#[must_use]
#[stable]
pub enum Result<T, E> {
    /// Contains the success value
    Ok(T),

    /// Contains the error value
    Err(E)
}

/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

impl<T, E> Result<T, E> {
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////

    /// Returns true if the result is `Ok`
    ///
    /// # Example
    ///
    /// ~~~
    /// use std::io::{File, Open, Write};
    ///
    /// # fn do_not_run_example() { // creates a file
    /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
    /// assert!(file.write_line("it's cold in here").is_ok());
    /// # }
    /// ~~~
    #[inline]
    #[stable]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `Err`
    ///
    /// # Example
    ///
    /// ~~~
    /// use std::io::{File, Open, Read};
    ///
    /// // When opening with `Read` access, if the file does not exist
    /// // then `open_mode` returns an error.
    /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
    /// assert!(bogus.is_err());
    /// ~~~
    #[inline]
    #[stable]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for each variant
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Option<T>`
    ///
    /// Converts `self` into an `Option<T>`, consuming `self`,
    /// and discarding the error, if any.
    ///
    /// To convert to an `Option` without discarding the error value,
    /// use `as_ref` to first convert the `Result<T, E>` into a
    /// `Result<&T, &E>`.
    ///
    /// # Examples
    ///
    /// ~~~{.should_fail}
    /// use std::io::{File, IoResult};
    ///
    /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
    /// let bdays: File = bdays.ok().expect("unable to open birthday file");
    /// ~~~
    #[inline]
    #[stable]
    pub fn ok(self) -> Option<T> {
        match self {
            Ok(x)  => Some(x),
            Err(_) => None,
        }
    }

    /// Convert from `Result<T, E>` to `Option<E>`
    ///
    /// Converts `self` into an `Option<T>`, consuming `self`,
    /// and discarding the value, if any.
    #[inline]
    #[stable]
    pub fn err(self) -> Option<E> {
        match self {
            Ok(_)  => None,
            Err(x) => Some(x),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Result<&T, &E>`
    ///
    /// Produces a new `Result`, containing a reference
    /// into the original, leaving the original in place.
    #[inline]
    #[stable]
    pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
        }
    }

    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
    #[inline]
    #[unstable = "waiting for mut conventions"]
    pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
        }
    }

    /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
    #[inline]
    #[unstable = "waiting for mut conventions"]
    pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
        match *self {
            Ok(ref mut x) => slice::mut_ref_slice(x),
            Err(_) => {
                // work around lack of implicit coercion from fixed-size array to slice
                let emp: &mut [_] = &mut [];
                emp
            }
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
    /// contained `Ok` value, leaving an `Err` value untouched.
    ///
    /// This function can be used to compose the results of two functions.
    ///
    /// # Examples
    ///
    /// Sum the lines of a buffer by mapping strings to numbers,
    /// ignoring I/O and parse errors:
    ///
    /// ~~~
    /// use std::io::{BufReader, IoResult};
    ///
    /// let buffer = "1\n2\n3\n4\n";
    /// let mut reader = BufReader::new(buffer.as_bytes());
    ///
    /// let mut sum = 0;
    ///
    /// while !reader.eof() {
    ///     let line: IoResult<String> = reader.read_line();
    ///     // Convert the string line to a number using `map` and `from_str`
    ///     let val: IoResult<int> = line.map(|line| {
    ///         from_str::<int>(line.as_slice().trim_right()).unwrap_or(0)
    ///     });
    ///     // Add the value if there were no errors, otherwise add 0
    ///     sum += val.ok().unwrap_or(0);
    /// }
    ///
    /// assert!(sum == 10);
    /// ~~~
    #[inline]
    #[unstable = "waiting for unboxed closures"]
    pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
        match self {
          Ok(t) => Ok(op(t)),
          Err(e) => Err(e)
        }
    }

    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
    /// contained `Err` value, leaving an `Ok` value untouched.
    ///
    /// This function can be used to pass through a successful result while handling
    /// an error.
    #[inline]
    #[unstable = "waiting for unboxed closures"]
    pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
        match self {
          Ok(t) => Ok(t),
          Err(e) => Err(op(e))
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////

    /// Returns an iterator over the possibly contained value.
    #[inline]
    #[unstable = "waiting for iterator conventions"]
    pub fn iter<'r>(&'r self) -> Item<&'r T> {
        Item{opt: self.as_ref().ok()}
    }

    /// Returns a mutable iterator over the possibly contained value.
    #[inline]
    #[unstable = "waiting for iterator conventions"]
    pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
        Item{opt: self.as_mut().ok()}
    }

    /// Returns a consuming iterator over the possibly contained value.
    #[inline]
    #[unstable = "waiting for iterator conventions"]
    pub fn move_iter(self) -> Item<T> {
        Item{opt: self.ok()}
    }

    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////

    /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    #[inline]
    #[stable]
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
        match self {
            Ok(_) => res,
            Err(e) => Err(e),
        }
    }

    /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    #[unstable = "waiting for unboxed closures"]
    pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
    }

    /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    #[inline]
    #[stable]
    pub fn or(self, res: Result<T, E>) -> Result<T, E> {
        match self {
            Ok(_) => self,
            Err(_) => res,
        }
    }

    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    #[unstable = "waiting for unboxed closures"]
    pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }

    /// Unwraps a result, yielding the content of an `Ok`.
    /// Else it returns `optb`.
    #[inline]
    #[unstable = "waiting for conventions"]
    pub fn unwrap_or(self, optb: T) -> T {
        match self {
            Ok(t) => t,
            Err(_) => optb
        }
    }

    /// Unwraps a result, yielding the content of an `Ok`.
    /// If the value is an `Err` then it calls `op` with its value.
    #[inline]
    #[unstable = "waiting for conventions"]
    pub fn unwrap_or_else(self, op: |E| -> T) -> T {
        match self {
            Ok(t) => t,
            Err(e) => op(e)
        }
    }

    /// Deprecated name for `unwrap_or_else()`.
    #[deprecated = "replaced by .unwrap_or_else()"]
    #[inline]
    pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
        self.unwrap_or_else(op)
    }
}

impl<T, E: Show> Result<T, E> {
    /// Unwraps a result, yielding the content of an `Ok`.
    ///
    /// # Failure
    ///
    /// Fails if the value is an `Err`, with a custom failure message provided
    /// by the `Err`'s value.
    #[inline]
    #[unstable = "waiting for conventions"]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(e) =>
                fail!("called `Result::unwrap()` on an `Err` value: {}", e)
        }
    }
}

impl<T: Show, E> Result<T, E> {
    /// Unwraps a result, yielding the content of an `Err`.
    ///
    /// # Failure
    ///
    /// Fails if the value is an `Ok`, with a custom failure message provided
    /// by the `Ok`'s value.
    #[inline]
    #[unstable = "waiting for conventions"]
    pub fn unwrap_err(self) -> E {
        match self {
            Ok(t) =>
                fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
            Err(e) => e
        }
    }
}

/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

impl<T, E> Slice<T> for Result<T, E> {
    /// Convert from `Result<T, E>` to `&[T]` (without copying)
    #[inline]
    #[stable]
    fn as_slice<'a>(&'a self) -> &'a [T] {
        match *self {
            Ok(ref x) => slice::ref_slice(x),
            Err(_) => {
                // work around lack of implicit coercion from fixed-size array to slice
                let emp: &[_] = &[];
                emp
            }
        }
    }
}

/////////////////////////////////////////////////////////////////////////////
// The Result Iterator
/////////////////////////////////////////////////////////////////////////////

/// A `Result` iterator that yields either one or zero elements
///
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
/// methods on `Result`.
#[deriving(Clone)]
#[unstable = "waiting for iterator conventions"]
pub struct Item<T> {
    opt: Option<T>
}

impl<T> Iterator<T> for Item<T> {
    #[inline]
    fn next(&mut self) -> Option<T> {
        self.opt.take()
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        match self.opt {
            Some(_) => (1, Some(1)),
            None => (0, Some(0)),
        }
    }
}

impl<A> DoubleEndedIterator<A> for Item<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        self.opt.take()
    }
}

impl<A> ExactSize<A> for Item<A> {}

/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////

/// Deprecated: use `Iterator::collect`.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(mut iter: Iter)
                                                                       -> Result<V, E> {
    iter.collect()
}

impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
    /// Takes each element in the `Iterator`: if it is an `Err`, no further
    /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
    /// container with the values of each `Result` is returned.
    ///
    /// Here is an example which increments every integer in a vector,
    /// checking for overflow:
    ///
    /// ```rust
    /// use std::uint;
    ///
    /// let v = vec!(1u, 2u);
    /// let res: Result<Vec<uint>, &'static str> = v.iter().map(|x: &uint|
    ///     if *x == uint::MAX { Err("Overflow!") }
    ///     else { Ok(x + 1) }
    /// ).collect();
    /// assert!(res == Ok(vec!(2u, 3u)));
    /// ```
    #[inline]
    fn from_iter<I: Iterator<Result<A, E>>>(iter: I) -> Result<V, E> {
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.

        struct Adapter<Iter, E> {
            iter: Iter,
            err: Option<E>,
        }

        impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> {
            #[inline]
            fn next(&mut self) -> Option<T> {
                match self.iter.next() {
                    Some(Ok(value)) => Some(value),
                    Some(Err(err)) => {
                        self.err = Some(err);
                        None
                    }
                    None => None,
                }
            }
        }

        let mut adapter = Adapter { iter: iter, err: None };
        let v: V = FromIterator::from_iter(adapter.by_ref());

        match adapter.err {
            Some(err) => Err(err),
            None => Ok(v),
        }
    }
}

/// Perform a fold operation over the result values from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, the folded value is returned.
#[inline]
#[experimental]
pub fn fold<T,
            V,
            E,
            Iter: Iterator<Result<T, E>>>(
            mut iterator: Iter,
            mut init: V,
            f: |V, T| -> V)
            -> Result<V, E> {
    for t in iterator {
        match t {
            Ok(v) => init = f(init, v),
            Err(u) => return Err(u)
        }
    }
    Ok(init)
}

/// Deprecated.
///
/// Perform a trivial fold operation over the result values
/// from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, a simple `Ok(())` is returned.
#[inline]
#[deprecated = "use fold instead"]
pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
    fold(iterator, (), |_, _| ())
}


text:
module AttrAccessorWithInit
  VERSION = "0.0.1"
end


text:
package org.drools.verifier.core.index.query;

import org.drools.verifier.core.index.matchers.ExactMatcher;
import org.drools.verifier.core.index.matchers.KeyMatcher;
import org.drools.verifier.core.index.matchers.Matcher;
import org.drools.verifier.core.maps.KeyDefinition;

public class Matchers
        extends KeyMatcher {

    public Matchers(final KeyDefinition keyDefinition) {
        super(keyDefinition);
    }

    public ExactMatcher is(final Comparable comparable) {
        return new ExactMatcher(keyDefinition,
                                comparable);
    }

    public Matcher any() {
        return new Matcher(keyDefinition);
    }

    public Matcher isNot(final Comparable comparable) {
        return new ExactMatcher(keyDefinition,
                                comparable,
                                true);
    }
}


text:
if (process.platform === 'linux' && process.type === 'renderer') {
  // On Linux we could not access clipboard in renderer process.
  module.exports = require('electron').remote.clipboard
} else {
  module.exports = process.atomBinding('clipboard')
}