text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Rapid Innovations</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">
    <link href="css/donut.css" rel="stylesheet">
    <link href="css/donut-responsive.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Rapid Innovations

                        Services

                        Why Rapid

                        About Us

                        Forum

                        Contact

                            Login

                            <form role="form" action="./login?to=" method="post">

                                    <input type="text" class="form-control" id="qa-userid" name="emailhandle" placeholder="Email or Username" />

                                    <input type="password" class="form-control" id="qa-password" name="password" placeholder="Password" />

                                        <input type="checkbox" name="remember" id="qa-rememberme" value="1"> Remember

                                    <input type="hidden" name="code" value="0-1442862020-7fd2d454274a2db6f45240e8b2f28e96305afac9" />

                                    <button type="submit" value="" id="qa-login" name="dologin" class="btn btn-primary btn-block">
                                        Login
                                    </button>

                                        Register

                                        I forgot my password

                            </form>

Grooming Professionals of Tomorrow

                Tell Me More

Services

Lorem ipsum dolor sit amet consectetur.

Extended Curriculum

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Expert Talks

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Career Guidance

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Why RAPID

Lorem ipsum dolor sit amet consectetur.

About Us

Lorem ipsum dolor sit amet consectetur.

Welcome to RAPID Innovations – You are at the right place if you have high career aspirations and want to increase your employability.

 "Increase my employability!!! What do you mean? I'm already into a good college and quite strong in my academics, then why do I need you!?" If you are thinking the same – then let us elaborate on that...

To get placed in a company of your choice, it's not just sufficient to be strong on fundamentals of your field of study. It's equally important to have good aptitude skills and soft skills. The employers want to know how trainable you are, whether or not you are fit to work in a team and if you have that right attitude for the job.

So... We at RAPID Innovations develop those required skill sets which will help you make an impression on the interviewer and increase your chances of getting that dream job of yours. We have an exhaustive plan which covers all the scenarios that you will face while sitting for placements.

 And well, yeah... it's not just about taking you through boring classroom sessions giving you tips and tricks, we also work on improving your overall personality by engaging you in various activities, fun learning and competitions.

BTW, RAPID is actually an abbreviation – Ruchir, Abhishek, Prasoon and Deepak – the 4 founding members, all having work experience in diversified technology MNCs. Thinking about what that "I" is doing in between? Well, we thought of using it for Innovations so that the name makes some sense.

 That's all folks... Just have a look at Why RAPID to know about what differentiates us.

Our Amazing Team

Lorem ipsum dolor sit amet consectetur.

Name 1

Designation 1

Name 2

Designation 2

Name 3

Designation 3

Name 4

Designation 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.

Contact Us

Send us a message

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Rapid Innovation 2015

Privacy Policy

Terms of Use


text:
package net.geocentral.geometria.util;

public class GUndefinedJoinException extends Exception {

    public Object[] joinMatches;

    public GUndefinedJoinException() {
    }

    public GUndefinedJoinException(Object[] joinMatches) {
        super("Look up message in code");
        this.joinMatches = joinMatches;
    }

    private static final long serialVersionUID = 1L;
}

redpajama_set_name: RedPajamaGithub


text:
import script_chdir
from evaluation.eval_script import evaluate_models_xval, print_results, EvalModel
from hybrid_model.dataset import get_dataset

# Get dataset
dataset = get_dataset('ml100k')
# dataset = get_dataset('ml1m')

models = []

# Hybrid Model
from hybrid_model.hybrid import HybridModel
from hybrid_model.config import hybrid_config

model_type = HybridModel
config = hybrid_config
models.append(EvalModel(model_type.__name__, model_type, config))

results = evaluate_models_xval(dataset, models, coldstart=False, n_fold=10)
print('Normal 10-fold')
print_results(results)

"""
Normal 10-fold
------- HybridModel
=== Part full
rmse: 0.8908 ± 0.0044  prec@5: 0.8756 ± 0.0035

------- HybridModel_SVDpp
=== Part full
rmse: 0.8953 ± 0.0048  prec@5: 0.8747 ± 0.0031

------- HybridModel_AttributeBiasExperimental
=== Part full
rmse: 0.9235 ± 0.0041  prec@5: 0.8633 ± 0.0043
"""


text:
'use strict';

require('should');

describe('utility.mailer | Private API', function () {
  var mailer, plz;

  // Mock configuration
  plz = {
    config: {
      mailer: {
        default: {
          service: 'fake',
          address: 'name@example.com',
          password: 'fakePassword'
        },
        other: {
          service: 'fake',
          address: 'name2@example.com',
          password: 'fakePassword'
        }
      }
    }
  };

  describe('getMailer()', function () {
    mailer = require('../app/utility.mailer')(plz);

    it('should throw an error when undefined mailer is used', function() {
      (function () {
        mailer.getMailer(function () {}, 'banana');
      }).should.throw();
    });

    it('should get a defined non-default mailer', function(done) {
      mailer.getMailer(function (error, transporter) {
        error.should.be.false;
        transporter.should.be.type('object');
        done();
      }, 'other');
    });

    it('should get the default mailer', function(done) {
      mailer.getMailer(function (error, transporter) {
        error.should.be.false;
        transporter.should.be.type('object');
        done();
      });
    });

  });

  describe('sendMail()', function () {
    var nodeMailer = require('nodemailer');

    it('should be able to reference mailer and fail', function(done) {
      nodeMailer.createTransport = function () {
        function sendMail(options, callback) {
          callback(true, 'mocked failure');
        }

        return {
          sendMail: sendMail
        };
      };

      mailer = require('../app/utility.mailer')(plz, nodeMailer);

      var options = {
        name: 'other'
      };

      mailer.sendMail(options, function (error, result) {
        error.should.be.true;
        result.should.be.type('string');
        done();
      });
    });

    it('should be able to reference non-default mailer and send', function(done) {
      nodeMailer.createTransport = function () {
        function sendMail(options, callback) {
          callback(false, 'mocked success');
        }

        return {
          sendMail: sendMail
        };
      };

      mailer = require('../app/utility.mailer')(plz, nodeMailer);

      var options = {
        name: 'other'
      };

      mailer.sendMail(options, function (error, result) {
        error.should.be.false;
        result.should.be.type('string');
        result.should.equal('mocked success');
        done();
      });
    });

    it('should be able to reference default mailer and send', function(done) {
      nodeMailer.createTransport = function () {
        function sendMail(options, callback) {
          callback(false, 'mocked success');
        }

        return {
          sendMail: sendMail
        };
      };

      mailer = require('../app/utility.mailer')(plz, nodeMailer);

      mailer.sendMail({}, function (error, result) {
        error.should.be.false;
        result.should.be.type('string');
        result.should.equal('mocked success');
        done();
      });
    });

  });

});


text:
#ifndef _mem_h
#define _mem_h

#include "m3rt/bootloader/m3_bootloader.h"
#include "m3rt/base/m3ec_def.h>

class mem_cMemRow
{
public:

	enum eType
	{
		Program,
		EEProm,
		Configuration
	};
	mem_cMemRow(eType Type, unsigned int StartAddr, int RowNumber, eFamily Family);
	bool InsertData(unsigned int Address, char * pData);
	void FormatData(void);
	void SendData  (M3EcSlaveShm * slave_shm);
	void SendConfigData(M3EcSlaveShm * slave_shm);
	void PrintData();
private:
	char           * m_pBuffer;
	unsigned int     m_Address;
	bool             m_bEmpty;
	eType            m_eType;
	unsigned short   m_Data[PM33F_ROW_SIZE*2];
	int              m_RowNumber;
	eFamily          m_eFamily;
	int		m_RowSize;
};

#endif


text:
layout: post
title:  How I hacked a bandcamp user account (JK)
date:   2019-03-10
tags: [javascript]
---

Just sharing a fun write up about figuring out how to apply for a
Senior Fraud/Risk Engineer posting (I did not apply FYI). If I have an
opportunity to write a job posting myself, I will definitely try to make
it just as fun as this one.

1. Checking cookies

> To apply, gather the crumbs (starting with your cookies).

I found:

fraud_job_url: Over+here%3A+bandcamp.com%2Fectotherm%2Fsnakeoil_requests%3Fsnakeoil_param%3Dfrog

Decode the URL:

```ruby
URI.decode('Over+here%3A+bandcamp.com%2Fectotherm%2Fsnakeoil_requests%3Fsnakeoil_param%3Dfrog')
=>
"Over+here:+bandcamp.com/ectotherm/snakeoil_requests?snakeoil_param=frog"
```

Cool, let's check it out.

> Applying is not a quick win,
> To do so you must first log in.
> Take over the account
> Whose details lie about -
> найти необычный IP-адрес to begin.

There was a request log table with three columns: ip address, a bandcamp
URL, and user agent. I got lucky with this part, the requests with a
SnakeOil agent looked fishy. Running a `whois`, the ip address turned
out to be Russian, coincidental joke maybe?

https://en.wikipedia.org/wiki/Snake_oil_(cryptography)

The suspect bandcamp user: https://bandcamp.com/gilamonster

Cool, there's a function Launder, some character shifting, and a
character lookup dump. Reading comprehension being my weakness, I got
hung up looking for what to call `it()` on haha.

```ruby
lookup = %w(f y d s v k e i n p a t l r j u z o g w c q m h x b)
legend = ('a'..'z').to_a.reverse.zip(lookup).to_h
'dirty'.chars.map { |char| legend[char] }
=> ["m", "o", "n", "e", "y"]
```

Calling `Launder('money')` prompted a window alert with another URL to
follow showing an HTTP POST request with a user agent detail and body
params missing.

Cool, pieced together the missing information, fired the complete
request, and got this response:

> gilamonster uses the dumbest password you can think of - log in with
> it at [REDACTED]

Zang logged in, got redirected to the job posting page but with a
contact email to send info to.

Thus completes this little adventure. Most enjoyable job application
I've done ever.


text:
package be.c4j.demo.view;

import be.c4j.demo.model.Person;
import be.c4j.demo.service.PersonService;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;

/**
 *
 */
@Named
@ViewScoped
public class PersonListBean implements Serializable {

    @Inject
    private PersonService personService;

    private List<Person> persons;

    @PostConstruct
    public void init() {
        persons = personService.getAllPersons();
    }

    public List<Person> getPersons() {
        return persons;
    }

}


text:
package sessions

// Options stores configuration for a session or session store.
//
// Fields are a subset of http.Cookie fields.
type Options struct {
	Path   string
	Domain string
	// MaxAge=0 means no Max-Age attribute specified and the cookie will be
	// deleted after the browser session ends.
	// MaxAge<0 means delete cookie immediately.
	// MaxAge>0 means Max-Age attribute present and given in seconds.
	MaxAge   int
	Secure   bool
	HttpOnly bool
}


text:
// tclUnix.h --
//
//	This file reads in UNIX-related header files and sets up UNIX-related macros for Tcl's UNIX core.  It should be the
//	only file that contains #ifdefs to handle different flavors of UNIX.  This file sets up the union of all UNIX-related
//	things needed by any of the Tcl core files.  This file depends on configuration #defines in tclConfig.h
//
// Copyright 1991 Regents of the University of California
// Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without
// fee is hereby granted, provided that this copyright notice appears in all copies.  The University of California
// makes no representations about the suitability of this software for any purpose.  It is provided "as is" without
// express or implied warranty.

#ifndef __TCL_UNIX_H__
#define __TCL_UNIX_H__

// The following #defines are used to distinguish between different UNIX systems.  These #defines are normally set by the "config" script
// based on information it gets by looking in the include and library areas.  The defaults below are for BSD-based systems like SunOS or Ultrix.
//
#define TCL_GETTOD		0 // 1 means there exists a library procedure "gettimeofday" (e.g. BSD systems).  0 means have to use "times" instead.
#define TCL_GETWD		0 // 1 means there exists a library procedure "getwd" (e.g. BSD systems).  0 means have to use "getcwd" instead.
#define TCL_SYS_ERRLIST 0 // 1 means that the array sys_errlist is defined as part of the C library.
#define TCL_SYS_TIME_H	0 // 1 means there exists an include file <sys/time.h> (e.g. BSD derivatives).
#define TCL_SYS_WAIT_H	0 // 1 means there exists an include file <sys/wait.h> that defines constants related to the results of "wait".
#define TCL_UNION_WAIT	0 // 1 means that the "wait" system call returns a structure of type "union wait" (e.g. BSD systems).  0 means "wait" returns an int (e.g. System V and POSIX).
#define TCL_PID_T		0 // 1 means that <sys/types> defines the type pid_t.  0 means that it doesn't.
#define TCL_UID_T		0 // 1 means that <sys/types> defines the type uid_t.  0 means that it doesn't.

//#define HAVE_MKSTEMP
//#define HAVE_GETHOSTNAME

#include <RuntimeOS.h>
#include <sys/types.h>
#include <sys/stat.h>

// On systems without symbolic links (i.e. S_IFLNK isn't defined) define "lstat" to use "stat" instead.
#ifndef S_IFLNK
#define lstat stat
#endif

// Define macros to query file type bits, if they're not already defined.
#ifndef S_ISREG
# ifdef S_IFREG
# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
# else
# define S_ISREG(m) 0
# endif
#endif
#ifndef S_ISDIR
# ifdef S_IFDIR
# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
# else
# define S_ISDIR(m) 0
# endif
#endif
#ifndef S_ISCHR
# ifdef S_IFCHR
# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
# else
# define S_ISCHR(m) 0
# endif
#endif
#ifndef S_ISBLK
# ifdef S_IFBLK
# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
# else
# define S_ISBLK(m) 0
# endif
#endif
#ifndef S_ISFIFO
# ifdef S_IFIFO
# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
# else
# define S_ISFIFO(m) 0
# endif
#endif
#ifndef S_ISLNK
# ifdef S_IFLNK
# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
# else
# define S_ISLNK(m) 0
# endif
#endif
#ifndef S_ISSOCK
# ifdef S_IFSOCK
# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
# else
# define S_ISSOCK(m) 0
# endif
#endif

// Make sure that MAXPATHLEN is defined.
#ifndef MAXPATHLEN
#ifdef PATH_MAX
# define MAXPATHLEN PATH_MAX
#else
# define MAXPATHLEN 2048
#endif
#endif

// Define pid_t and uid_t if they're not already defined.
#if !TCL_PID_T
#define pid_t int
#endif
#if !TCL_UID_T
#define uid_t int
#endif

//// Variables provided by the C library:
//#if defined(_sgi) || defined(__sgi)
//#define environ _environ
//#endif
//extern char **environ;

// uClinux can't do fork(), only vfork()
#define NO_FORK

//// Library procedures used by Tcl but not declared in a header file:
//#ifndef _CRAY
//extern int access(const char *path, int mode);
//extern int chdir(const char *path);
//extern int close(int fd);
//extern int dup2(int src, int dst);
//extern void endpwent();
//// extern int execvp(const char *name, char **argv);
//extern void _exit(int status);
//// extern pid_t fork();
//// extern uid_t geteuid();
//// extern pid_t getpid();
//// extern char *getcwd(char *buffer, int size);
//extern char * getwd(char *buffer);
//// extern int kill(pid_t pid, int sig);
//// extern long lseek(int fd, int offset, int whence);
//extern char *mktemp(char *template_);
//#if !(defined(sparc) || defined(_IBMR2))
//extern int open(const char *path, int flags, ...);
//#endif
//extern int pipe(int *fdPtr);
//// extern int read(int fd, char *buf, int numBytes);
//// extern int readlink(const char *path, char *buf, int size);
//extern int unlink(const char *path);
//// extern int write(int fd, char *buf, int numBytes);
//#endif /* _CRAY */

#endif /* _TCLUNIX */


text:
using System.Diagnostics;
using System.IO;
using System.Xml.Xsl.Runtime;

namespace System.Xml.Xsl.Qil
{
    /// <summary>
    /// Data structure for storing whitespace rules generated by xsl:strip-space and xsl:preserve-space
    /// </summary>
    internal class WhitespaceRule
    {
        private string _localName;
        private string _namespaceName;
        private bool _preserveSpace;

        /// <summary>
        /// Allow derived classes to construct empty whitespace rule.
        /// </summary>
        protected WhitespaceRule()
        {
        }

        /// <summary>
        /// Construct new whitespace rule.
        /// </summary>
        public WhitespaceRule(string localName, string namespaceName, bool preserveSpace)
        {
            Init(localName, namespaceName, preserveSpace);
        }

        /// <summary>
        /// Initialize whitespace rule after it's been constructed.
        /// </summary>
        protected void Init(string localName, string namespaceName, bool preserveSpace)
        {
            _localName = localName;
            _namespaceName = namespaceName;
            _preserveSpace = preserveSpace;
        }

        /// <summary>
        /// Local name of the element.
        /// </summary>
        public string LocalName
        {
            get { return _localName; }
            set { _localName = value; }
        }

        /// <summary>
        /// Namespace name (uri) of the element.
        /// </summary>
        public string NamespaceName
        {
            get { return _namespaceName; }
            set { _namespaceName = value; }
        }

        /// <summary>
        /// True, if this element is whitespace-preserving.
        /// False, if this element is whitespace-stripping.
        /// </summary>
        public bool PreserveSpace
        {
            get { return _preserveSpace; }
        }

        /// <summary>
        /// Serialize the object to BinaryWriter.
        /// </summary>
        public void GetObjectData(XmlQueryDataWriter writer)
        {
            Debug.Assert(this.GetType() == typeof(WhitespaceRule), "Serialization of WhitespaceRule subclasses is not implemented");
            // string localName;
            writer.WriteStringQ(_localName);
            // string namespaceName;
            writer.WriteStringQ(_namespaceName);
            // bool preserveSpace;
            writer.Write(_preserveSpace);
        }

        /// <summary>
        /// Deserialize the object from BinaryReader.
        /// </summary>
        public WhitespaceRule(XmlQueryDataReader reader)
        {
            // string localName;
            _localName = reader.ReadStringQ();
            // string namespaceName;
            _namespaceName = reader.ReadStringQ();
            // bool preserveSpace;
            _preserveSpace = reader.ReadBoolean();
        }
    }
}


text:
package lnwire

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"encoding/binary"
	"fmt"
	"io"

	"github.com/davecgh/go-spew/spew"
	"github.com/go-errors/errors"
	"github.com/lightningnetwork/lnd/tlv"
)

// FailureMessage represents the onion failure object identified by its unique
// failure code.
type FailureMessage interface {
	// Code returns a failure code describing the exact nature of the
	// error.
	Code() FailCode

	// Error returns a human readable string describing the error. With
	// this method, the FailureMessage interface meets the built-in error
	// interface.
	Error() string
}

// FailureMessageLength is the size of the failure message plus the size of
// padding. The FailureMessage message should always be EXACTLY this size.
const FailureMessageLength = 256

const (
	// FlagBadOnion error flag describes an unparsable, encrypted by
	// previous node.
	FlagBadOnion FailCode = 0x8000

	// FlagPerm error flag indicates a permanent failure.
	FlagPerm FailCode = 0x4000

	// FlagNode error flag indicates a node failure.
	FlagNode FailCode = 0x2000

	// FlagUpdate error flag indicates a new channel update is enclosed
	// within the error.
	FlagUpdate FailCode = 0x1000
)

// FailCode specifies the precise reason that an upstream HTLC was canceled.
// Each UpdateFailHTLC message carries a FailCode which is to be passed
// backwards, encrypted at each step back to the source of the HTLC within the
// route.
type FailCode uint16

// The currently defined onion failure types within this current version of the
// Lightning protocol.
const (
	CodeNone                             FailCode = 0
	CodeInvalidRealm                              = FlagBadOnion | 1
	CodeTemporaryNodeFailure                      = FlagNode | 2
	CodePermanentNodeFailure                      = FlagPerm | FlagNode | 2
	CodeRequiredNodeFeatureMissing                = FlagPerm | FlagNode | 3
	CodeInvalidOnionVersion                       = FlagBadOnion | FlagPerm | 4
	CodeInvalidOnionHmac                          = FlagBadOnion | FlagPerm | 5
	CodeInvalidOnionKey                           = FlagBadOnion | FlagPerm | 6
	CodeTemporaryChannelFailure                   = FlagUpdate | 7
	CodePermanentChannelFailure                   = FlagPerm | 8
	CodeRequiredChannelFeatureMissing             = FlagPerm | 9
	CodeUnknownNextPeer                           = FlagPerm | 10
	CodeAmountBelowMinimum                        = FlagUpdate | 11
	CodeFeeInsufficient                           = FlagUpdate | 12
	CodeIncorrectCltvExpiry                       = FlagUpdate | 13
	CodeExpiryTooSoon                             = FlagUpdate | 14
	CodeChannelDisabled                           = FlagUpdate | 20
	CodeIncorrectOrUnknownPaymentDetails          = FlagPerm | 15
	CodeIncorrectPaymentAmount                    = FlagPerm | 16
	CodeFinalExpiryTooSoon               FailCode = 17
	CodeFinalIncorrectCltvExpiry         FailCode = 18
	CodeFinalIncorrectHtlcAmount         FailCode = 19
	CodeExpiryTooFar                     FailCode = 21
	CodeInvalidOnionPayload                       = FlagPerm | 22
	CodeMPPTimeout                       FailCode = 23
)

// String returns the string representation of the failure code.
func (c FailCode) String() string {
	switch c {
	case CodeInvalidRealm:
		return "InvalidRealm"

	case CodeTemporaryNodeFailure:
		return "TemporaryNodeFailure"

	case CodePermanentNodeFailure:
		return "PermanentNodeFailure"

	case CodeRequiredNodeFeatureMissing:
		return "RequiredNodeFeatureMissing"

	case CodeInvalidOnionVersion:
		return "InvalidOnionVersion"

	case CodeInvalidOnionHmac:
		return "InvalidOnionHmac"

	case CodeInvalidOnionKey:
		return "InvalidOnionKey"

	case CodeTemporaryChannelFailure:
		return "TemporaryChannelFailure"

	case CodePermanentChannelFailure:
		return "PermanentChannelFailure"

	case CodeRequiredChannelFeatureMissing:
		return "RequiredChannelFeatureMissing"

	case CodeUnknownNextPeer:
		return "UnknownNextPeer"

	case CodeAmountBelowMinimum:
		return "AmountBelowMinimum"

	case CodeFeeInsufficient:
		return "FeeInsufficient"

	case CodeIncorrectCltvExpiry:
		return "IncorrectCltvExpiry"

	case CodeIncorrectPaymentAmount:
		return "IncorrectPaymentAmount"

	case CodeExpiryTooSoon:
		return "ExpiryTooSoon"

	case CodeChannelDisabled:
		return "ChannelDisabled"

	case CodeIncorrectOrUnknownPaymentDetails:
		return "IncorrectOrUnknownPaymentDetails"

	case CodeFinalExpiryTooSoon:
		return "FinalExpiryTooSoon"

	case CodeFinalIncorrectCltvExpiry:
		return "FinalIncorrectCltvExpiry"

	case CodeFinalIncorrectHtlcAmount:
		return "FinalIncorrectHtlcAmount"

	case CodeExpiryTooFar:
		return "ExpiryTooFar"

	case CodeInvalidOnionPayload:
		return "InvalidOnionPayload"

	case CodeMPPTimeout:
		return "MPPTimeout"

	default:
		return "<unknown>"
	}
}

// FailInvalidRealm is returned if the realm byte is unknown.
//
// NOTE: May be returned by any node in the payment route.
type FailInvalidRealm struct{}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailInvalidRealm) Error() string {
	return f.Code().String()
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailInvalidRealm) Code() FailCode {
	return CodeInvalidRealm
}

// FailTemporaryNodeFailure is returned if an otherwise unspecified transient
// error occurs for the entire node.
//
// NOTE: May be returned by any node in the payment route.
type FailTemporaryNodeFailure struct{}

// Code returns the failure unique code.
// NOTE: Part of the FailureMessage interface.
func (f *FailTemporaryNodeFailure) Code() FailCode {
	return CodeTemporaryNodeFailure
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailTemporaryNodeFailure) Error() string {
	return f.Code().String()
}

// FailPermanentNodeFailure is returned if an otherwise unspecified permanent
// error occurs for the entire node.
//
// NOTE: May be returned by any node in the payment route.
type FailPermanentNodeFailure struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailPermanentNodeFailure) Code() FailCode {
	return CodePermanentNodeFailure
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailPermanentNodeFailure) Error() string {
	return f.Code().String()
}

// FailRequiredNodeFeatureMissing is returned if a node has requirement
// advertised in its node_announcement features which were not present in the
// onion.
//
// NOTE: May be returned by any node in the payment route.
type FailRequiredNodeFeatureMissing struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailRequiredNodeFeatureMissing) Code() FailCode {
	return CodeRequiredNodeFeatureMissing
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailRequiredNodeFeatureMissing) Error() string {
	return f.Code().String()
}

// FailPermanentChannelFailure is return if an otherwise unspecified permanent
// error occurs for the outgoing channel (eg. channel (recently).
//
// NOTE: May be returned by any node in the payment route.
type FailPermanentChannelFailure struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailPermanentChannelFailure) Code() FailCode {
	return CodePermanentChannelFailure
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailPermanentChannelFailure) Error() string {
	return f.Code().String()
}

// FailRequiredChannelFeatureMissing is returned if the outgoing channel has a
// requirement advertised in its channel announcement features which were not
// present in the onion.
//
// NOTE: May only be returned by intermediate nodes.
type FailRequiredChannelFeatureMissing struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailRequiredChannelFeatureMissing) Code() FailCode {
	return CodeRequiredChannelFeatureMissing
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailRequiredChannelFeatureMissing) Error() string {
	return f.Code().String()
}

// FailUnknownNextPeer is returned if the next peer specified by the onion is
// not known.
//
// NOTE: May only be returned by intermediate nodes.
type FailUnknownNextPeer struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailUnknownNextPeer) Code() FailCode {
	return CodeUnknownNextPeer
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailUnknownNextPeer) Error() string {
	return f.Code().String()
}

// FailIncorrectPaymentAmount is returned if the amount paid is less than the
// amount expected, the final node MUST fail the HTLC. If the amount paid is
// more than twice the amount expected, the final node SHOULD fail the HTLC.
// This allows the sender to reduce information leakage by altering the amount,
// without allowing accidental gross overpayment.
//
// NOTE: May only be returned by the final node in the path.
type FailIncorrectPaymentAmount struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailIncorrectPaymentAmount) Code() FailCode {
	return CodeIncorrectPaymentAmount
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailIncorrectPaymentAmount) Error() string {
	return f.Code().String()
}

// FailIncorrectDetails is returned for two reasons:
//
// 1) if the payment hash has already been paid, the final node MAY treat the
// payment hash as unknown, or may succeed in accepting the HTLC. If the
// payment hash is unknown, the final node MUST fail the HTLC.
//
// 2) if the amount paid is less than the amount expected, the final node MUST
// fail the HTLC. If the amount paid is more than twice the amount expected,
// the final node SHOULD fail the HTLC. This allows the sender to reduce
// information leakage by altering the amount, without allowing accidental
// gross overpayment.
//
// NOTE: May only be returned by the final node in the path.
type FailIncorrectDetails struct {
	// amount is the value of the extended HTLC.
	amount MilliSatoshi

	// height is the block height when the htlc was received.
	height uint32
}

// NewFailIncorrectDetails makes a new instance of the FailIncorrectDetails
// error bound to the specified HTLC amount and acceptance height.
func NewFailIncorrectDetails(amt MilliSatoshi,
	height uint32) *FailIncorrectDetails {

	return &FailIncorrectDetails{
		amount: amt,
		height: height,
	}
}

// Amount is the value of the extended HTLC.
func (f *FailIncorrectDetails) Amount() MilliSatoshi {
	return f.amount
}

// Height is the block height when the htlc was received.
func (f *FailIncorrectDetails) Height() uint32 {
	return f.height
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailIncorrectDetails) Code() FailCode {
	return CodeIncorrectOrUnknownPaymentDetails
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailIncorrectDetails) Error() string {
	return fmt.Sprintf(
		"%v(amt=%v, height=%v)", CodeIncorrectOrUnknownPaymentDetails,
		f.amount, f.height,
	)
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailIncorrectDetails) Decode(r io.Reader, pver uint32) error {
	err := ReadElement(r, &f.amount)
	switch {
	// This is an optional tack on that was added later in the protocol. As
	// a result, older nodes may not include this value. We'll account for
	// this by checking for io.EOF here which means that no bytes were read
	// at all.
	case err == io.EOF:
		return nil

	case err != nil:
		return err
	}

	// At a later stage, the height field was also tacked on. We need to
	// check for io.EOF here as well.
	err = ReadElement(r, &f.height)
	switch {
	case err == io.EOF:
		return nil

	case err != nil:
		return err
	}

	return nil
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailIncorrectDetails) Encode(w *bytes.Buffer, pver uint32) error {
	if err := WriteMilliSatoshi(w, f.amount); err != nil {
		return err
	}

	return WriteUint32(w, f.height)
}

// FailFinalExpiryTooSoon is returned if the cltv_expiry is too low, the final
// node MUST fail the HTLC.
//
// NOTE: May only be returned by the final node in the path.
type FailFinalExpiryTooSoon struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailFinalExpiryTooSoon) Code() FailCode {
	return CodeFinalExpiryTooSoon
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailFinalExpiryTooSoon) Error() string {
	return f.Code().String()
}

// NewFinalExpiryTooSoon creates new instance of the FailFinalExpiryTooSoon.
func NewFinalExpiryTooSoon() *FailFinalExpiryTooSoon {
	return &FailFinalExpiryTooSoon{}
}

// FailInvalidOnionVersion is returned if the onion version byte is unknown.
//
// NOTE: May be returned only by intermediate nodes.
type FailInvalidOnionVersion struct {
	// OnionSHA256 hash of the onion blob which haven't been proceeded.
	OnionSHA256 [sha256.Size]byte
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailInvalidOnionVersion) Error() string {
	return fmt.Sprintf("InvalidOnionVersion(onion_sha=%x)", f.OnionSHA256[:])
}

// NewInvalidOnionVersion creates new instance of the FailInvalidOnionVersion.
func NewInvalidOnionVersion(onion []byte) *FailInvalidOnionVersion {
	return &FailInvalidOnionVersion{OnionSHA256: sha256.Sum256(onion)}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailInvalidOnionVersion) Code() FailCode {
	return CodeInvalidOnionVersion
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionVersion) Decode(r io.Reader, pver uint32) error {
	return ReadElement(r, f.OnionSHA256[:])
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionVersion) Encode(w *bytes.Buffer, pver uint32) error {
	return WriteBytes(w, f.OnionSHA256[:])
}

// FailInvalidOnionHmac is return if the onion HMAC is incorrect.
//
// NOTE: May only be returned by intermediate nodes.
type FailInvalidOnionHmac struct {
	// OnionSHA256 hash of the onion blob which haven't been proceeded.
	OnionSHA256 [sha256.Size]byte
}

// NewInvalidOnionHmac creates new instance of the FailInvalidOnionHmac.
func NewInvalidOnionHmac(onion []byte) *FailInvalidOnionHmac {
	return &FailInvalidOnionHmac{OnionSHA256: sha256.Sum256(onion)}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailInvalidOnionHmac) Code() FailCode {
	return CodeInvalidOnionHmac
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionHmac) Decode(r io.Reader, pver uint32) error {
	return ReadElement(r, f.OnionSHA256[:])
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionHmac) Encode(w *bytes.Buffer, pver uint32) error {
	return WriteBytes(w, f.OnionSHA256[:])
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailInvalidOnionHmac) Error() string {
	return fmt.Sprintf("InvalidOnionHMAC(onion_sha=%x)", f.OnionSHA256[:])
}

// FailInvalidOnionKey is return if the ephemeral key in the onion is
// unparsable.
//
// NOTE: May only be returned by intermediate nodes.
type FailInvalidOnionKey struct {
	// OnionSHA256 hash of the onion blob which haven't been proceeded.
	OnionSHA256 [sha256.Size]byte
}

// NewInvalidOnionKey creates new instance of the FailInvalidOnionKey.
func NewInvalidOnionKey(onion []byte) *FailInvalidOnionKey {
	return &FailInvalidOnionKey{OnionSHA256: sha256.Sum256(onion)}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailInvalidOnionKey) Code() FailCode {
	return CodeInvalidOnionKey
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionKey) Decode(r io.Reader, pver uint32) error {
	return ReadElement(r, f.OnionSHA256[:])
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailInvalidOnionKey) Encode(w *bytes.Buffer, pver uint32) error {
	return WriteBytes(w, f.OnionSHA256[:])
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailInvalidOnionKey) Error() string {
	return fmt.Sprintf("InvalidOnionKey(onion_sha=%x)", f.OnionSHA256[:])
}

// parseChannelUpdateCompatabilityMode will attempt to parse a channel updated
// encoded into an onion error payload in two ways. First, we'll try the
// compatibility oriented version wherein we'll _skip_ the length prefixing on
// the channel update message. Older versions of c-lighting do this so we'll
// attempt to parse these messages in order to retain compatibility. If we're
// unable to pull out a fully valid version, then we'll fall back to the
// regular parsing mechanism which includes the length prefix an NO type byte.
func parseChannelUpdateCompatabilityMode(r *bufio.Reader,
	chanUpdate *ChannelUpdate, pver uint32) error {

	// We'll peek out two bytes from the buffer without advancing the
	// buffer so we can decide how to parse the remainder of it.
	maybeTypeBytes, err := r.Peek(2)
	if err != nil {
		return err
	}

	// Some nodes well prefix an additional set of bytes in front of their
	// channel updates. These bytes will _almost_ always be 258 or the type
	// of the ChannelUpdate message.
	typeInt := binary.BigEndian.Uint16(maybeTypeBytes)
	if typeInt == MsgChannelUpdate {
		// At this point it's likely the case that this is a channel
		// update message with its type prefixed, so we'll snip off the
		// first two bytes and parse it as normal.
		var throwAwayTypeBytes [2]byte
		_, err := r.Read(throwAwayTypeBytes[:])
		if err != nil {
			return err
		}
	}

	// At this pint, we've either decided to keep the entire thing, or snip
	// off the first two bytes. In either case, we can just read it as
	// normal.
	return chanUpdate.Decode(r, pver)
}

// FailTemporaryChannelFailure is if an otherwise unspecified transient error
// occurs for the outgoing channel (eg. channel capacity reached, too many
// in-flight htlcs)
//
// NOTE: May only be returned by intermediate nodes.
type FailTemporaryChannelFailure struct {
	// Update is used to update information about state of the channel
	// which caused the failure.
	//
	// NOTE: This field is optional.
	Update *ChannelUpdate
}

// NewTemporaryChannelFailure creates new instance of the FailTemporaryChannelFailure.
func NewTemporaryChannelFailure(update *ChannelUpdate) *FailTemporaryChannelFailure {
	return &FailTemporaryChannelFailure{Update: update}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailTemporaryChannelFailure) Code() FailCode {
	return CodeTemporaryChannelFailure
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailTemporaryChannelFailure) Error() string {
	if f.Update == nil {
		return f.Code().String()
	}

	return fmt.Sprintf("TemporaryChannelFailure(update=%v)",
		spew.Sdump(f.Update))
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailTemporaryChannelFailure) Decode(r io.Reader, pver uint32) error {
	var length uint16
	err := ReadElement(r, &length)
	if err != nil {
		return err
	}

	if length != 0 {
		f.Update = &ChannelUpdate{}
		return parseChannelUpdateCompatabilityMode(
			bufio.NewReader(r), f.Update, pver,
		)
	}

	return nil
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailTemporaryChannelFailure) Encode(w *bytes.Buffer,
	pver uint32) error {

	var payload []byte
	if f.Update != nil {
		var bw bytes.Buffer
		if err := f.Update.Encode(&bw, pver); err != nil {
			return err
		}
		payload = bw.Bytes()
	}

	if err := WriteUint16(w, uint16(len(payload))); err != nil {
		return err
	}

	_, err := w.Write(payload)
	return err
}

// FailAmountBelowMinimum is returned if the HTLC does not reach the current
// minimum amount, we tell them the amount of the incoming HTLC and the current
// channel setting for the outgoing channel.
//
// NOTE: May only be returned by the intermediate nodes in the path.
type FailAmountBelowMinimum struct {
	// HtlcMsat is the wrong amount of the incoming HTLC.
	HtlcMsat MilliSatoshi

	// Update is used to update information about state of the channel
	// which caused the failure.
	Update ChannelUpdate
}

// NewAmountBelowMinimum creates new instance of the FailAmountBelowMinimum.
func NewAmountBelowMinimum(htlcMsat MilliSatoshi,
	update ChannelUpdate) *FailAmountBelowMinimum {

	return &FailAmountBelowMinimum{
		HtlcMsat: htlcMsat,
		Update:   update,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailAmountBelowMinimum) Code() FailCode {
	return CodeAmountBelowMinimum
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailAmountBelowMinimum) Error() string {
	return fmt.Sprintf("AmountBelowMinimum(amt=%v, update=%v", f.HtlcMsat,
		spew.Sdump(f.Update))
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailAmountBelowMinimum) Decode(r io.Reader, pver uint32) error {
	if err := ReadElement(r, &f.HtlcMsat); err != nil {
		return err
	}

	var length uint16
	if err := ReadElement(r, &length); err != nil {
		return err
	}

	f.Update = ChannelUpdate{}
	return parseChannelUpdateCompatabilityMode(
		bufio.NewReader(r), &f.Update, pver,
	)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailAmountBelowMinimum) Encode(w *bytes.Buffer, pver uint32) error {
	if err := WriteMilliSatoshi(w, f.HtlcMsat); err != nil {
		return err
	}

	return writeOnionErrorChanUpdate(w, &f.Update, pver)
}

// FailFeeInsufficient is returned if the HTLC does not pay sufficient fee, we
// tell them the amount of the incoming HTLC and the current channel setting
// for the outgoing channel.
//
// NOTE: May only be returned by intermediate nodes.
type FailFeeInsufficient struct {
	// HtlcMsat is the wrong amount of the incoming HTLC.
	HtlcMsat MilliSatoshi

	// Update is used to update information about state of the channel
	// which caused the failure.
	Update ChannelUpdate
}

// NewFeeInsufficient creates new instance of the FailFeeInsufficient.
func NewFeeInsufficient(htlcMsat MilliSatoshi,
	update ChannelUpdate) *FailFeeInsufficient {
	return &FailFeeInsufficient{
		HtlcMsat: htlcMsat,
		Update:   update,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailFeeInsufficient) Code() FailCode {
	return CodeFeeInsufficient
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailFeeInsufficient) Error() string {
	return fmt.Sprintf("FeeInsufficient(htlc_amt==%v, update=%v", f.HtlcMsat,
		spew.Sdump(f.Update))
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFeeInsufficient) Decode(r io.Reader, pver uint32) error {
	if err := ReadElement(r, &f.HtlcMsat); err != nil {
		return err
	}

	var length uint16
	if err := ReadElement(r, &length); err != nil {
		return err
	}

	f.Update = ChannelUpdate{}
	return parseChannelUpdateCompatabilityMode(
		bufio.NewReader(r), &f.Update, pver,
	)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFeeInsufficient) Encode(w *bytes.Buffer, pver uint32) error {
	if err := WriteMilliSatoshi(w, f.HtlcMsat); err != nil {
		return err
	}

	return writeOnionErrorChanUpdate(w, &f.Update, pver)
}

// FailIncorrectCltvExpiry is returned if outgoing cltv value does not match
// the update add htlc's cltv expiry minus cltv expiry delta for the outgoing
// channel, we tell them the cltv expiry and the current channel setting for
// the outgoing channel.
//
// NOTE: May only be returned by intermediate nodes.
type FailIncorrectCltvExpiry struct {
	// CltvExpiry is the wrong absolute timeout in blocks, after which
	// outgoing HTLC expires.
	CltvExpiry uint32

	// Update is used to update information about state of the channel
	// which caused the failure.
	Update ChannelUpdate
}

// NewIncorrectCltvExpiry creates new instance of the FailIncorrectCltvExpiry.
func NewIncorrectCltvExpiry(cltvExpiry uint32,
	update ChannelUpdate) *FailIncorrectCltvExpiry {

	return &FailIncorrectCltvExpiry{
		CltvExpiry: cltvExpiry,
		Update:     update,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailIncorrectCltvExpiry) Code() FailCode {
	return CodeIncorrectCltvExpiry
}

func (f *FailIncorrectCltvExpiry) Error() string {
	return fmt.Sprintf("IncorrectCltvExpiry(expiry=%v, update=%v",
		f.CltvExpiry, spew.Sdump(f.Update))
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailIncorrectCltvExpiry) Decode(r io.Reader, pver uint32) error {
	if err := ReadElement(r, &f.CltvExpiry); err != nil {
		return err
	}

	var length uint16
	if err := ReadElement(r, &length); err != nil {
		return err
	}

	f.Update = ChannelUpdate{}
	return parseChannelUpdateCompatabilityMode(
		bufio.NewReader(r), &f.Update, pver,
	)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailIncorrectCltvExpiry) Encode(w *bytes.Buffer, pver uint32) error {
	if err := WriteUint32(w, f.CltvExpiry); err != nil {
		return err
	}

	return writeOnionErrorChanUpdate(w, &f.Update, pver)
}

// FailExpiryTooSoon is returned if the ctlv-expiry is too near, we tell them
// the current channel setting for the outgoing channel.
//
// NOTE: May only be returned by intermediate nodes.
type FailExpiryTooSoon struct {
	// Update is used to update information about state of the channel
	// which caused the failure.
	Update ChannelUpdate
}

// NewExpiryTooSoon creates new instance of the FailExpiryTooSoon.
func NewExpiryTooSoon(update ChannelUpdate) *FailExpiryTooSoon {
	return &FailExpiryTooSoon{
		Update: update,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailExpiryTooSoon) Code() FailCode {
	return CodeExpiryTooSoon
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailExpiryTooSoon) Error() string {
	return fmt.Sprintf("ExpiryTooSoon(update=%v", spew.Sdump(f.Update))
}

// Decode decodes the failure from l stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailExpiryTooSoon) Decode(r io.Reader, pver uint32) error {
	var length uint16
	if err := ReadElement(r, &length); err != nil {
		return err
	}

	f.Update = ChannelUpdate{}
	return parseChannelUpdateCompatabilityMode(
		bufio.NewReader(r), &f.Update, pver,
	)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailExpiryTooSoon) Encode(w *bytes.Buffer, pver uint32) error {
	return writeOnionErrorChanUpdate(w, &f.Update, pver)
}

// FailChannelDisabled is returned if the channel is disabled, we tell them the
// current channel setting for the outgoing channel.
//
// NOTE: May only be returned by intermediate nodes.
type FailChannelDisabled struct {
	// Flags least-significant bit must be set to 0 if the creating node
	// corresponds to the first node in the previously sent channel
	// announcement and 1 otherwise.
	Flags uint16

	// Update is used to update information about state of the channel
	// which caused the failure.
	Update ChannelUpdate
}

// NewChannelDisabled creates new instance of the FailChannelDisabled.
func NewChannelDisabled(flags uint16, update ChannelUpdate) *FailChannelDisabled {
	return &FailChannelDisabled{
		Flags:  flags,
		Update: update,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailChannelDisabled) Code() FailCode {
	return CodeChannelDisabled
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailChannelDisabled) Error() string {
	return fmt.Sprintf("ChannelDisabled(flags=%v, update=%v", f.Flags,
		spew.Sdump(f.Update))
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailChannelDisabled) Decode(r io.Reader, pver uint32) error {
	if err := ReadElement(r, &f.Flags); err != nil {
		return err
	}

	var length uint16
	if err := ReadElement(r, &length); err != nil {
		return err
	}

	f.Update = ChannelUpdate{}
	return parseChannelUpdateCompatabilityMode(
		bufio.NewReader(r), &f.Update, pver,
	)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailChannelDisabled) Encode(w *bytes.Buffer, pver uint32) error {
	if err := WriteUint16(w, f.Flags); err != nil {
		return err
	}

	return writeOnionErrorChanUpdate(w, &f.Update, pver)
}

// FailFinalIncorrectCltvExpiry is returned if the outgoing_cltv_value does not
// match the ctlv_expiry of the HTLC at the final hop.
//
// NOTE: might be returned by final node only.
type FailFinalIncorrectCltvExpiry struct {
	// CltvExpiry is the wrong absolute timeout in blocks, after which
	// outgoing HTLC expires.
	CltvExpiry uint32
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailFinalIncorrectCltvExpiry) Error() string {
	return fmt.Sprintf("FinalIncorrectCltvExpiry(expiry=%v)", f.CltvExpiry)
}

// NewFinalIncorrectCltvExpiry creates new instance of the
// FailFinalIncorrectCltvExpiry.
func NewFinalIncorrectCltvExpiry(cltvExpiry uint32) *FailFinalIncorrectCltvExpiry {
	return &FailFinalIncorrectCltvExpiry{
		CltvExpiry: cltvExpiry,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailFinalIncorrectCltvExpiry) Code() FailCode {
	return CodeFinalIncorrectCltvExpiry
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFinalIncorrectCltvExpiry) Decode(r io.Reader, pver uint32) error {
	return ReadElement(r, &f.CltvExpiry)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFinalIncorrectCltvExpiry) Encode(w *bytes.Buffer,
	pver uint32) error {

	return WriteUint32(w, f.CltvExpiry)
}

// FailFinalIncorrectHtlcAmount is returned if the amt_to_forward is higher
// than incoming_htlc_amt of the HTLC at the final hop.
//
// NOTE: May only be returned by the final node.
type FailFinalIncorrectHtlcAmount struct {
	// IncomingHTLCAmount is the wrong forwarded htlc amount.
	IncomingHTLCAmount MilliSatoshi
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailFinalIncorrectHtlcAmount) Error() string {
	return fmt.Sprintf("FinalIncorrectHtlcAmount(amt=%v)",
		f.IncomingHTLCAmount)
}

// NewFinalIncorrectHtlcAmount creates new instance of the
// FailFinalIncorrectHtlcAmount.
func NewFinalIncorrectHtlcAmount(amount MilliSatoshi) *FailFinalIncorrectHtlcAmount {
	return &FailFinalIncorrectHtlcAmount{
		IncomingHTLCAmount: amount,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailFinalIncorrectHtlcAmount) Code() FailCode {
	return CodeFinalIncorrectHtlcAmount
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFinalIncorrectHtlcAmount) Decode(r io.Reader, pver uint32) error {
	return ReadElement(r, &f.IncomingHTLCAmount)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *FailFinalIncorrectHtlcAmount) Encode(w *bytes.Buffer,
	pver uint32) error {

	return WriteMilliSatoshi(w, f.IncomingHTLCAmount)
}

// FailExpiryTooFar is returned if the CLTV expiry in the HTLC is too far in the
// future.
//
// NOTE: May be returned by any node in the payment route.
type FailExpiryTooFar struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailExpiryTooFar) Code() FailCode {
	return CodeExpiryTooFar
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailExpiryTooFar) Error() string {
	return f.Code().String()
}

// InvalidOnionPayload is returned if the hop could not process the TLV payload
// enclosed in the onion.
type InvalidOnionPayload struct {
	// Type is the TLV type that caused the specific failure.
	Type uint64

	// Offset is the byte offset within the payload where the failure
	// occurred.
	Offset uint16
}

// NewInvalidOnionPayload initializes a new InvalidOnionPayload failure.
func NewInvalidOnionPayload(typ uint64, offset uint16) *InvalidOnionPayload {
	return &InvalidOnionPayload{
		Type:   typ,
		Offset: offset,
	}
}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *InvalidOnionPayload) Code() FailCode {
	return CodeInvalidOnionPayload
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *InvalidOnionPayload) Error() string {
	return fmt.Sprintf("%v(type=%v, offset=%d)",
		f.Code(), f.Type, f.Offset)
}

// Decode decodes the failure from bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *InvalidOnionPayload) Decode(r io.Reader, pver uint32) error {
	var buf [8]byte
	typ, err := tlv.ReadVarInt(r, &buf)
	if err != nil {
		return err
	}
	f.Type = typ

	return ReadElements(r, &f.Offset)
}

// Encode writes the failure in bytes stream.
//
// NOTE: Part of the Serializable interface.
func (f *InvalidOnionPayload) Encode(w *bytes.Buffer, pver uint32) error {
	var buf [8]byte
	if err := tlv.WriteVarInt(w, f.Type, &buf); err != nil {
		return err
	}

	return WriteUint16(w, f.Offset)
}

// FailMPPTimeout is returned if the complete amount for a multi part payment
// was not received within a reasonable time.
//
// NOTE: May only be returned by the final node in the path.
type FailMPPTimeout struct{}

// Code returns the failure unique code.
//
// NOTE: Part of the FailureMessage interface.
func (f *FailMPPTimeout) Code() FailCode {
	return CodeMPPTimeout
}

// Returns a human readable string describing the target FailureMessage.
//
// NOTE: Implements the error interface.
func (f *FailMPPTimeout) Error() string {
	return f.Code().String()
}

// DecodeFailure decodes, validates, and parses the lnwire onion failure, for
// the provided protocol version.
func DecodeFailure(r io.Reader, pver uint32) (FailureMessage, error) {
	// First, we'll parse out the encapsulated failure message itself. This
	// is a 2 byte length followed by the payload itself.
	var failureLength uint16
	if err := ReadElement(r, &failureLength); err != nil {
		return nil, fmt.Errorf("unable to read error len: %v", err)
	}
	if failureLength > FailureMessageLength {
		return nil, fmt.Errorf("failure message is too "+
			"long: %v", failureLength)
	}
	failureData := make([]byte, failureLength)
	if _, err := io.ReadFull(r, failureData); err != nil {
		return nil, fmt.Errorf("unable to full read payload of "+
			"%v: %v", failureLength, err)
	}

	dataReader := bytes.NewReader(failureData)

	return DecodeFailureMessage(dataReader, pver)
}

// DecodeFailureMessage decodes just the failure message, ignoring any padding
// that may be present at the end.
func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
	// Once we have the failure data, we can obtain the failure code from
	// the first two bytes of the buffer.
	var codeBytes [2]byte
	if _, err := io.ReadFull(r, codeBytes[:]); err != nil {
		return nil, fmt.Errorf("unable to read failure code: %v", err)
	}
	failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:]))

	// Create the empty failure by given code and populate the failure with
	// additional data if needed.
	failure, err := makeEmptyOnionError(failCode)
	if err != nil {
		return nil, fmt.Errorf("unable to make empty error: %v", err)
	}

	// Finally, if this failure has a payload, then we'll read that now as
	// well.
	switch f := failure.(type) {
	case Serializable:
		if err := f.Decode(r, pver); err != nil {
			return nil, fmt.Errorf("unable to decode error "+
				"update (type=%T): %v", failure, err)
		}
	}

	return failure, nil
}

// EncodeFailure encodes, including the necessary onion failure header
// information.
func EncodeFailure(w *bytes.Buffer, failure FailureMessage, pver uint32) error {
	var failureMessageBuffer bytes.Buffer

	err := EncodeFailureMessage(&failureMessageBuffer, failure, pver)
	if err != nil {
		return err
	}

	// The combined size of this message must be below the max allowed
	// failure message length.
	failureMessage := failureMessageBuffer.Bytes()
	if len(failureMessage) > FailureMessageLength {
		return fmt.Errorf("failure message exceed max "+
			"available size: %v", len(failureMessage))
	}

	// Finally, we'll add some padding in order to ensure that all failure
	// messages are fixed size.
	pad := make([]byte, FailureMessageLength-len(failureMessage))

	if err := WriteUint16(w, uint16(len(failureMessage))); err != nil {
		return err
	}

	if err := WriteBytes(w, failureMessage); err != nil {
		return err
	}
	if err := WriteUint16(w, uint16(len(pad))); err != nil {
		return err
	}

	return WriteBytes(w, pad)
}

// EncodeFailureMessage encodes just the failure message without adding a length
// and padding the message for the onion protocol.
func EncodeFailureMessage(w *bytes.Buffer,
	failure FailureMessage, pver uint32) error {

	// First, we'll write out the error code itself into the failure
	// buffer.
	var codeBytes [2]byte
	code := uint16(failure.Code())
	binary.BigEndian.PutUint16(codeBytes[:], code)
	_, err := w.Write(codeBytes[:])
	if err != nil {
		return err
	}

	// Next, some message have an additional message payload, if this is
	// one of those types, then we'll also encode the error payload as
	// well.
	switch failure := failure.(type) {
	case Serializable:
		if err := failure.Encode(w, pver); err != nil {
			return err
		}
	}

	return nil
}

// makeEmptyOnionError creates a new empty onion error  of the proper concrete
// type based on the passed failure code.
func makeEmptyOnionError(code FailCode) (FailureMessage, error) {
	switch code {
	case CodeInvalidRealm:
		return &FailInvalidRealm{}, nil

	case CodeTemporaryNodeFailure:
		return &FailTemporaryNodeFailure{}, nil

	case CodePermanentNodeFailure:
		return &FailPermanentNodeFailure{}, nil

	case CodeRequiredNodeFeatureMissing:
		return &FailRequiredNodeFeatureMissing{}, nil

	case CodePermanentChannelFailure:
		return &FailPermanentChannelFailure{}, nil

	case CodeRequiredChannelFeatureMissing:
		return &FailRequiredChannelFeatureMissing{}, nil

	case CodeUnknownNextPeer:
		return &FailUnknownNextPeer{}, nil

	case CodeIncorrectOrUnknownPaymentDetails:
		return &FailIncorrectDetails{}, nil

	case CodeIncorrectPaymentAmount:
		return &FailIncorrectPaymentAmount{}, nil

	case CodeFinalExpiryTooSoon:
		return &FailFinalExpiryTooSoon{}, nil

	case CodeInvalidOnionVersion:
		return &FailInvalidOnionVersion{}, nil

	case CodeInvalidOnionHmac:
		return &FailInvalidOnionHmac{}, nil

	case CodeInvalidOnionKey:
		return &FailInvalidOnionKey{}, nil

	case CodeTemporaryChannelFailure:
		return &FailTemporaryChannelFailure{}, nil

	case CodeAmountBelowMinimum:
		return &FailAmountBelowMinimum{}, nil

	case CodeFeeInsufficient:
		return &FailFeeInsufficient{}, nil

	case CodeIncorrectCltvExpiry:
		return &FailIncorrectCltvExpiry{}, nil

	case CodeExpiryTooSoon:
		return &FailExpiryTooSoon{}, nil

	case CodeChannelDisabled:
		return &FailChannelDisabled{}, nil

	case CodeFinalIncorrectCltvExpiry:
		return &FailFinalIncorrectCltvExpiry{}, nil

	case CodeFinalIncorrectHtlcAmount:
		return &FailFinalIncorrectHtlcAmount{}, nil

	case CodeExpiryTooFar:
		return &FailExpiryTooFar{}, nil

	case CodeInvalidOnionPayload:
		return &InvalidOnionPayload{}, nil

	case CodeMPPTimeout:
		return &FailMPPTimeout{}, nil

	default:
		return nil, errors.Errorf("unknown error code: %v", code)
	}
}

// writeOnionErrorChanUpdate writes out a ChannelUpdate using the onion error
// format. The format is that we first write out the true serialized length of
// the channel update, followed by the serialized channel update itself.
func writeOnionErrorChanUpdate(w *bytes.Buffer, chanUpdate *ChannelUpdate,
	pver uint32) error {

	// First, we encode the channel update in a temporary buffer in order
	// to get the exact serialized size.
	var b bytes.Buffer
	if err := chanUpdate.Encode(&b, pver); err != nil {
		return err
	}

	// Now that we know the size, we can write the length out in the main
	// writer.
	updateLen := b.Len()
	if err := WriteUint16(w, uint16(updateLen)); err != nil {
		return err
	}

	// With the length written, we'll then write out the serialized channel
	// update.
	if _, err := w.Write(b.Bytes()); err != nil {
		return err
	}

	return nil
}


text:
org 0

; Use Code segment as Data segment
push cs
pop ds

mov si, textError
call DisplayMessageZ

mov si, textNewline
call DisplayMessageZ

mov si, textError
mov cx, 4
call DisplayMessageX

HANG:
jmp HANG

; Message is at DS:SI, read up to NUL char
DisplayMessageZ:
     lodsb										; load next character
     or		al, al								; test for NUL character
     jz		.DONE
     mov	ah, 0x0E							; BIOS teletype
     mov	bh, 0x00							; display page 0
     mov	bl, 0x07							; text attribute
     int	0x10								; invoke BIOS
     jmp	DisplayMessageZ
.DONE:
     ret

; Message is at DS:SI, read CX chars
DisplayMessageX:
     lodsb										; load next character
     or		al, al								; test for NUL character
     jz		.DONE
     mov	ah, 0x0E							; BIOS teletype
     mov	bh, 0x00							; display page 0
     mov	bl, 0x07							; text attribute
     int	0x10								; invoke BIOS
     loop	DisplayMessageX
.DONE:
     ret

textError db "Boot stage 2 - Hello!", 0x00
textNewline db 0x0D, 0x0A, 0x00

TIMES 512-($-$$) DB 0


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">

    <title>Transition · Formstone</title>

    <link rel="stylesheet" href="../css/site.css?v=1.4.0">

 Formstone

Transition Demo

View Documentation

Basic

                            <button class="button trigger">Start</button>

<div class="transition_target"></div>

$(".transition_target").transition({
  always: true
}, function() {
  // Tranition complete...
}).addClass("active");

.transition_target {
  background: black;
  transition: background 0.25s;
}

.transition_target.active {
  background: blue;
}

Delegation

                            <button class="button trigger">Start</button>

<div class="transition_target">
	<div class="transition_child"></div>
</div>

$(".transition_target").transition({
  always: true,
  target: ".transition_child"
}, function() {
  // Tranition complete...
}).addClass("active");

.transition_target .transition_child {
  background: black;
  transition: background 0.25s;
}

.transition_target.active .transition_child {
  background: blue;
}

Property

                            <button class="button trigger">Start</button>

<div class="transition_target"></div>

$(".transition_target").transition({
  always: true,
  property: "height"
}, function() {
  // Tranition complete...
}).addClass("active");

.transition_target {
  background: black;
  height: 10px;
  transition:
    background 0.25s linear 0s,
    height 0.25s linear 1s;
}

.transition_target.active {
  background: blue;
  height: 30px;
}

© 2017 Formstone


text:
class BillingInfo < ActiveRecord::Base
    self.table_name = 'billing_info'
    self.primary_key = :B_SEQ

end


text:
package system

import (
	"fmt"
	"runtime"
)

func CloseFdsFrom(minFd int) error {
	return fmt.Errorf("CloseFdsFrom is unsupported on this platform (%s/%s)", runtime.GOOS, runtime.GOARCH)
}


text:
#define LOG_TAG "Reference_JNI"
#include "openvx_jni.h"

namespace android
{
    //**************************************************************************
    // LOCAL VARIABLES
    //**************************************************************************

    //**************************************************************************
    // EXPORTED FUNCTIONS
    //**************************************************************************

    static jint getType(JNIEnv *env, jobject obj)
    {
        vx_reference r = (vx_reference)GetHandle(env, obj, ReferenceClass, handleName);
        vx_enum e;
        vxQueryReference(r, VX_REF_ATTRIBUTE_TYPE, &e, sizeof(e));
        return (jint)e;
    }

    static jint getCount(JNIEnv *env, jobject obj)
    {
        vx_reference r = (vx_reference)GetHandle(env, obj, ReferenceClass, handleName);
        vx_uint32 c;
        vxQueryReference(r, VX_REF_ATTRIBUTE_COUNT, &c, sizeof(c));
        return (jint)c;
    }

    static JNINativeMethod method_table[] = {
        // { name,                         signature,                 function_pointer }
        { "getType",                       "()I",                   (void *)getType },
        { "getCount",                      "()I",                   (void *)getCount },
    };

    int register_org_khronos_OpenVX_Reference(JNIEnv *env)
    {
        PrintJNITable(LOG_TAG, ReferenceClass, method_table, NELEM(method_table));
        return jniRegisterNativeMethods(env, ReferenceClass, method_table, NELEM(method_table));
    }
};


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- select based on default-theme -->
    @if ($theme !== config('app.default_theme'))
    	<link href="{{ asset('/css/light.css') }}" rel="stylesheet">
	@else
        {{--<link href="{{ asset('/css/'.$theme.'.css') }}" rel="stylesheet">--}}
		<link href="{{ asset('/css/dark.css') }}" rel="stylesheet">
    @endif
	<link href="{{ asset('/css/select2.css') }}" rel="stylesheet">
	<link href="{{ asset('/css/select2-bootstrap.min.css') }}" rel="stylesheet">
	<!-- Material Icons -->
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=swap" rel="stylesheet">
	<!-- Fonts -->
	<link href="//fonts.googleapis.com/css?family=Roboto:400,300&display=swap" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Rubik&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body id="email-body" class="bg-light">

	@yield('content')

</body>
</html>


text:
using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Autofac;
using Autofac.Core;
using Orchard.Environment;
using Orchard.Environment.Configuration;
using Orchard.Environment.ShellBuilders;

namespace Orchard.Wcf {
    public class OrchardServiceHostFactory : ServiceHostFactory, IShim {
        public OrchardServiceHostFactory() {
            OrchardHostContainerRegistry.RegisterShim(this);
        }

        public IOrchardHostContainer HostContainer { get; set; }

        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses) {
            IComponentRegistration registration;
            if (constructorString == null) {
                throw new ArgumentNullException("constructorString");
            }

            if (constructorString == string.Empty) {
                throw new ArgumentOutOfRangeException("constructorString");
            }

            if (HostContainer == null) {
                throw new InvalidOperationException();
            }

            // Create work context
            IRunningShellTable runningShellTable = HostContainer.Resolve<IRunningShellTable>();
            ShellSettings shellSettings = runningShellTable.Match(baseAddresses.First().Host, baseAddresses.First().LocalPath);

            IOrchardHost orchardHost = HostContainer.Resolve<IOrchardHost>();
            ShellContext shellContext = orchardHost.GetShellContext(shellSettings);
            IWorkContextAccessor workContextAccessor = shellContext.LifetimeScope.Resolve<IWorkContextAccessor>();
            WorkContext workContext = workContextAccessor.GetContext();
            if (workContext == null) {
                using (IWorkContextScope workContextScope = workContextAccessor.CreateWorkContextScope()) {
                    ILifetimeScope lifetimeScope = workContextScope.Resolve<ILifetimeScope>();
                    registration =  GetRegistration(lifetimeScope, constructorString);
                }
            }
            else {
                ILifetimeScope lifetimeScope = workContext.Resolve<ILifetimeScope>();
                registration = GetRegistration(lifetimeScope, constructorString);
            }

            if (registration == null) {
                throw new InvalidOperationException();
            }

            if (!registration.Activator.LimitType.IsClass) {
                throw new InvalidOperationException();
            }

            return CreateServiceHost(workContextAccessor, registration, registration.Activator.LimitType, baseAddresses);
        }

        private ServiceHost CreateServiceHost(IWorkContextAccessor workContextAccessor, IComponentRegistration registration, Type implementationType, Uri[] baseAddresses) {
            ServiceHost host = CreateServiceHost(implementationType, baseAddresses);

            host.Opening += delegate {
                host.Description.Behaviors.Add(new OrchardDependencyInjectionServiceBehavior(workContextAccessor, implementationType, registration));
            };

            return host;
        }

        private IComponentRegistration GetRegistration(ILifetimeScope lifetimeScope, string constructorString) {
            IComponentRegistration registration;
            if (!lifetimeScope.ComponentRegistry.TryGetRegistration(new KeyedService(constructorString, typeof(object)), out registration)) {
                Type serviceType = Type.GetType(constructorString, false);
                if (serviceType != null) {
                    lifetimeScope.ComponentRegistry.TryGetRegistration(new TypedService(serviceType), out registration);
                }
            }

            return registration;
        }
    }
}


text:
using System;
using System.Linq.Expressions;

namespace IFramework.Specifications
{
    /// <summary>
    ///     Represents the specification which performs AND assertion
    ///     on the two given specifications.
    /// </summary>
    /// <typeparam name="T">The type of the entity.</typeparam>
    [Semantics(Semantics.And)]
    public class AndSpecification<T> : CompositeSpecification<T>
        //  where T : class, IEntity
    {
        #region Ctor

        /// <summary>
        ///     Constructs a new instance of AndSpecification.
        /// </summary>
        /// <param name="left">The left side of the combined specification.</param>
        /// <param name="right">The right side of the combined specification.</param>
        public AndSpecification(ISpecification<T> left, ISpecification<T> right) : base(left, right) { }

        #endregion

        #region Public Methods

        /// <summary>
        ///     Returns a LINQ expression which represents the semantics
        ///     of the specification.
        /// </summary>
        /// <returns>The LINQ expression.</returns>
        public override Expression<Func<T, bool>> GetExpression()
        {
            //var body = Expression.AndAlso(Left.GetExpression().Body, Right.GetExpression().Body);
            var body = Left.GetExpression().And(Right.GetExpression());
            return body;
            //return Expression.Lambda<Func<T, bool>>(body, Left.GetExpression().Parameters);
        }

        #endregion
    }
}


text:
class CreateBillingPayments < ActiveRecord::Migration
  def change
    create_table :billing_payments do |t|
      t.belongs_to :account, index: true
      t.money :value

      t.timestamps
    end
  end
end


text:
require 'faker'

FactoryGirl.define do
	factory :index_info do |p|
		p.content { Faker::Lorem.paragraph }
		p.title { Faker::Name.name }
		p.display { true }
	end
end


text:
"""Tests for the VMDK image resolver helper implementation."""

import unittest

from dfvfs.resolver import vmdk_resolver_helper
from tests.resolver import test_lib

class VmdkResolverHelperTest(test_lib.ResolverHelperTestCase):
  """Tests for the VMDK image resolver helper implementation."""

  def testNewFileObject(self):
    """Tests the NewFileObject function."""
    resolver_helper_object = vmdk_resolver_helper.VmdkResolverHelper()
    self._TestNewFileObject(resolver_helper_object)

  def testNewFileSystem(self):
    """Tests the NewFileSystem function."""
    resolver_helper_object = vmdk_resolver_helper.VmdkResolverHelper()
    self._TestNewFileSystemRaisesRuntimeError(resolver_helper_object)

if __name__ == '__main__':
  unittest.main()


text:
class java::io::InputStream : public ::java::lang::Object
{

public:
  InputStream();
  virtual jint available();
  virtual void close();
  virtual void mark(jint);
  virtual jboolean markSupported();
  virtual jint read() = 0;
  virtual jint read(JArray< jbyte > *);
  virtual jint read(JArray< jbyte > *, jint, jint);
  virtual void reset();
  virtual jlong skip(jlong);
  static ::java::lang::Class class$;
};

#endif // __java_io_InputStream__


text:
template <typename T>
class SkewHeap : Queue<T>
{
private:
    int _size = 0;
    BinaryNode<T> *_root = nullptr;

    BinaryNode<T>* merge(BinaryNode<T> *left, BinaryNode<T> *right)
    {
        if (left == nullptr)
        {
            return right;
        }
        if (right == nullptr)
        {
            return left;
        }

        //default assumptions
        BinaryNode<T> *smaller = left;
        BinaryNode<T> *larger = right;
        BinaryNode<T> *to_recursive_call = left->getRightChild();

        //are these assumptions violated?
        if (left->getValue() > right->getValue())
        {
            smaller = right;
            larger = left;
            to_recursive_call = right->getRightChild();
        }

        //swap smaller's right child with left child
        BinaryNode<T> *left_child = smaller->getLeftChild();
        BinaryNode<T> *right_child = smaller->getRightChild();
        smaller->setRightChild(left_child);

        //recursively determine smaller's new left child
        BinaryNode<T> *new_left = merge(right_child, larger);

        //set left child
        smaller->setLeftChild(new_left);

        //return smaller
        return smaller;
    }

public:
    SkewHeap()
    {

    }

    virtual T &getFirst()
    {
        return _root->getValue();
    }
    virtual const T &getFirst() const
    {
        return _root->getValue();
    }
    virtual void enqueue(const T &item)
    {
        BinaryNode<T> *new_value = new BinaryNode<T>{ item };
        _root = merge(_root, new_value);
        _size++;
    }
    virtual T dequeue()
    {
        T first = _root->getValue();
        _root = merge(_root->getLeftChild(), _root->getRightChild());
        _size--;
        return first;
    }
    virtual int getSize() const
    {
        return _size;
    }
};

#endif // !SKEW_HEAP_H


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

package org.chromium.cronet_sample_apk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.chromium.base.Log;
import org.chromium.net.CronetUrlRequestContext;
import org.chromium.net.ExtendedResponseInfo;
import org.chromium.net.ResponseInfo;
import org.chromium.net.UploadDataProvider;
import org.chromium.net.UploadDataSink;
import org.chromium.net.UrlRequest;
import org.chromium.net.UrlRequestContextConfig;
import org.chromium.net.UrlRequestException;
import org.chromium.net.UrlRequestListener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Activity for managing the Cronet Sample.
 */
public class CronetSampleActivity extends Activity {
    private static final String TAG = "cr.CronetSample";

    private CronetUrlRequestContext mRequestContext;

    private String mUrl;
    private boolean mLoading = false;
    private int mHttpStatusCode = 0;
    private TextView mResultText;
    private TextView mReceiveDataText;

    class SimpleUrlRequestListener implements UrlRequestListener {
        private ByteArrayOutputStream mBytesReceived = new ByteArrayOutputStream();
        private WritableByteChannel mReceiveChannel = Channels.newChannel(mBytesReceived);

        @Override
        public void onReceivedRedirect(
                UrlRequest request, ResponseInfo info, String newLocationUrl) {
            Log.i(TAG, "****** onReceivedRedirect ******");
            request.followRedirect();
        }

        @Override
        public void onResponseStarted(UrlRequest request, ResponseInfo info) {
            Log.i(TAG, "****** Response Started ******");
            Log.i(TAG, "*** Headers Are *** " + info.getAllHeaders());

            request.read(ByteBuffer.allocateDirect(32 * 1024));
        }

        @Override
        public void onReadCompleted(UrlRequest request, ResponseInfo info, ByteBuffer byteBuffer) {
            Log.i(TAG, "****** onReadCompleted ******" + byteBuffer);

            try {
                mReceiveChannel.write(byteBuffer);
            } catch (IOException e) {
                Log.i(TAG, "IOException during ByteBuffer read. Details: ", e);
            }
            byteBuffer.position(0);
            request.read(byteBuffer);
        }

        @Override
        public void onSucceeded(UrlRequest request, ExtendedResponseInfo info) {
            ResponseInfo responseInfo = info.getResponseInfo();
            mHttpStatusCode = responseInfo.getHttpStatusCode();
            Log.i(TAG, "****** Request Completed, status code is " + mHttpStatusCode
                            + ", total received bytes is " + info.getTotalReceivedBytes());

            final String receivedData = mBytesReceived.toString();
            final String url = responseInfo.getUrl();
            final String text = "Completed " + url + " (" + mHttpStatusCode + ")";
            CronetSampleActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    mLoading = false;
                    mResultText.setText(text);
                    mReceiveDataText.setText(receivedData);
                    promptForURL(url);
                }
            });
        }

        @Override
        public void onFailed(UrlRequest request, ResponseInfo info, UrlRequestException error) {
            Log.i(TAG, "****** onFailed, error is: " + error.getMessage());

            final String url = mUrl;
            final String text = "Failed " + mUrl + " (" + error.getMessage() + ")";
            CronetSampleActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    mLoading = false;
                    mResultText.setText(text);
                    promptForURL(url);
                }
            });
        }
    }

    static class SimpleUploadDataProvider implements UploadDataProvider {
        private byte[] mUploadData;
        private int mOffset;

        SimpleUploadDataProvider(byte[] uploadData) {
            mUploadData = uploadData;
            mOffset = 0;
        }

        @Override
        public long getLength() {
            return mUploadData.length;
        }

        @Override
        public void read(final UploadDataSink uploadDataSink, final ByteBuffer byteBuffer)
                throws IOException {
            if (byteBuffer.remaining() >= mUploadData.length - mOffset) {
                byteBuffer.put(mUploadData, mOffset, mUploadData.length - mOffset);
                mOffset = mUploadData.length;
            } else {
                int length = byteBuffer.remaining();
                byteBuffer.put(mUploadData, mOffset, length);
                mOffset += length;
            }
            uploadDataSink.onReadSucceeded(false);
        }

        @Override
        public void rewind(final UploadDataSink uploadDataSink) throws IOException {
            mOffset = 0;
            uploadDataSink.onRewindSucceeded();
        }
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResultText = (TextView) findViewById(R.id.resultView);
        mReceiveDataText = (TextView) findViewById(R.id.dataView);

        UrlRequestContextConfig myConfig = new UrlRequestContextConfig();
        myConfig.enableHttpCache(UrlRequestContextConfig.HttpCache.IN_MEMORY, 100 * 1024)
                .enableSPDY(true)
                .enableQUIC(true);

        mRequestContext = new CronetUrlRequestContext(this, myConfig);

        String appUrl = (getIntent() != null ? getIntent().getDataString() : null);
        if (appUrl == null) {
            promptForURL("https://");
        } else {
            startWithURL(appUrl);
        }
    }

    private void promptForURL(String url) {
        Log.i(TAG, "No URL provided via intent, prompting user...");
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Enter a URL");
        LayoutInflater inflater = getLayoutInflater();
        View alertView = inflater.inflate(R.layout.dialog_url, null);
        final EditText urlInput = (EditText) alertView.findViewById(R.id.urlText);
        urlInput.setText(url);
        final EditText postInput = (EditText) alertView.findViewById(R.id.postText);
        alert.setView(alertView);

        alert.setPositiveButton("Load", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int button) {
                String url = urlInput.getText().toString();
                String postData = postInput.getText().toString();
                startWithURL(url, postData);
            }
        });
        alert.show();
    }

    private void applyPostDataToUrlRequest(UrlRequest request, Executor executor, String postData) {
        if (postData != null && postData.length() > 0) {
            UploadDataProvider uploadDataProvider =
                    new SimpleUploadDataProvider(postData.getBytes());
            request.setHttpMethod("POST");
            request.addHeader("Content-Type", "application/x-www-form-urlencoded");
            request.setUploadDataProvider(uploadDataProvider, executor);
        }
    }

    private void startWithURL(String url) {
        startWithURL(url, null);
    }

    private void startWithURL(String url, String postData) {
        Log.i(TAG, "Cronet started: " + url);
        mUrl = url;
        mLoading = false;

        Executor executor = Executors.newSingleThreadExecutor();
        UrlRequestListener listener = new SimpleUrlRequestListener();
        UrlRequest request = mRequestContext.createRequest(url, listener, executor);
        applyPostDataToUrlRequest(request, executor, postData);
        request.start();
    }

    /**
     * This method is used in testing.
     */
    public String getUrl() {
        return mUrl;
    }

    /**
     * This method is used in testing.
     */
    public boolean isLoading() {
        return mLoading;
    }

    /**
     * This method is used in testing.
     */
    public int getHttpStatusCode() {
        return mHttpStatusCode;
    }

    private void startNetLog() {
        mRequestContext.startNetLogToFile(
                Environment.getExternalStorageDirectory().getPath() + "/cronet_sample_netlog.json",
                false);
    }

    private void stopNetLog() {
        mRequestContext.stopNetLog();
    }
}


text:
/*
 * auth.h
 *
 * common interface to authentication functions
 *
 * David A. McGrew
 * Cisco Systems, Inc.
 */

/*
 *
 * Copyright (c) 2001-2006, Cisco Systems, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 *   Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
 *
 *   Neither the name of the Cisco Systems, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifndef AUTH_H
#define AUTH_H

#include "datatypes.h"
#include "err.h"                /* error codes    */

typedef struct auth_type_t *auth_type_pointer;
typedef struct auth_t      *auth_pointer_t;

typedef err_status_t (*auth_alloc_func)
     (auth_pointer_t *ap, int key_len, int out_len);

typedef err_status_t (*auth_init_func)
     (void *state, const uint8_t *key, int key_len);

typedef err_status_t (*auth_dealloc_func)(auth_pointer_t ap);

typedef err_status_t (*auth_compute_func)
     (void *state, uint8_t *buffer, int octets_to_auth,
      int tag_len, uint8_t *tag);

typedef err_status_t (*auth_update_func)
     (void *state, uint8_t *buffer, int octets_to_auth);

typedef err_status_t (*auth_start_func)(void *state);

/* some syntactic sugar on these function types */

#define auth_type_alloc(at, a, klen, outlen)                        \
                 ((at)->alloc((a), (klen), (outlen)))

#define auth_init(a, key)                                           \
                 (((a)->type)->init((a)->state, (key), ((a)->key_len)))

#define auth_compute(a, buf, len, res)                              \
       (((a)->type)->compute((a)->state, (buf), (len), (a)->out_len, (res)))

#define auth_update(a, buf, len)                                    \
       (((a)->type)->update((a)->state, (buf), (len)))

#define auth_start(a)(((a)->type)->start((a)->state))

#define auth_dealloc(c) (((c)->type)->dealloc(c))

/* functions to get information about a particular auth_t */

int
auth_get_key_length(const struct auth_t *a);

int
auth_get_tag_length(const struct auth_t *a);

int
auth_get_prefix_length(const struct auth_t *a);

/*
 * auth_test_case_t is a (list of) key/message/tag values that are
 * known to be correct for a particular cipher.  this data can be used
 * to test an implementation in an on-the-fly self test of the
 * correcness of the implementation.  (see the auth_type_self_test()
 * function below)
 */

typedef struct auth_test_case_t {
  int key_length_octets;                    /* octets in key            */
  uint8_t *key;                             /* key                      */
  int data_length_octets;                   /* octets in data           */
  uint8_t *data;                            /* data                     */
  int tag_length_octets;                    /* octets in tag            */
  uint8_t *tag;                             /* tag                      */
  struct auth_test_case_t *next_test_case;  /* pointer to next testcase */
} auth_test_case_t;

/* auth_type_t */

typedef struct auth_type_t {
  auth_alloc_func      alloc;
  auth_dealloc_func    dealloc;
  auth_init_func       init;
  auth_compute_func    compute;
  auth_update_func     update;
  auth_start_func      start;
  char                *description;
  int                  ref_count;
  auth_test_case_t    *test_data;
  debug_module_t      *debug;
} auth_type_t;

typedef struct auth_t {
  auth_type_t *type;
  void        *state;
  int          out_len;           /* length of output tag in octets */
  int          key_len;           /* length of key in octets        */
  int          prefix_len;        /* length of keystream prefix     */
} auth_t;

/*
 * auth_type_self_test() tests an auth_type against test cases
 * provided in an array of values of key/message/tag that is known to
 * be good
 */

err_status_t
auth_type_self_test(const auth_type_t *at);

/*
 * auth_type_get_ref_count(at) returns the reference count (the number
 * of instantiations) of the auth_type_t at
 */

int
auth_type_get_ref_count(const auth_type_t *at);

#endif /* AUTH_H */


text:
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
 *
 *  (C) 2003 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include "mpitest.h"

/*
static char MTEST_Descrip[] = "Simple intercomm barrier test";
*/

/* This only checks that the Barrier operation accepts intercommunicators.
   It does not check for the semantics of a intercomm barrier (all processes
   in the local group can exit when (but not before) all processes in the
   remote group enter the barrier */
int main( int argc, char *argv[] )
{
    int errs = 0, err;
    int leftGroup;
    MPI_Comm comm;
    MPI_Datatype datatype;

    MTest_Init( &argc, &argv );

    datatype = MPI_INT;
    /* Get an intercommunicator */
    while (MTestGetIntercomm( &comm, &leftGroup, 4 )) {
        if (comm == MPI_COMM_NULL)
            continue;

	/* To improve reporting of problems about operations, we
	   change the error handler to errors return */
	MPI_Comm_set_errhandler( comm, MPI_ERRORS_RETURN );
	if (leftGroup) {
	    err = MPI_Barrier( comm );
	    if (err) {
		errs++;
		MTestPrintError( err );
	    }
	}
	else {
	    /* In the right group */
	    err = MPI_Barrier( comm );
	    if (err) {
		errs++;
		MTestPrintError( err );
	    }
	}
	MTestFreeComm( &comm );
    }

    MTest_Finalize( errs );
    MPI_Finalize();
    return 0;
}


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>obl:subj</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

obl:subj: NP-related subject

The relation obl:subj is used for the NP related to the subject core-argument in a head-marking language.
In Tupinambá, a strictly head-marking language, the core arguments are indexed on the predicate, but the NPs related to the core-arguments
are in free-order in relation to the head.

Aβá kuɲã o-s-epjak
man woman 3S-3O-see
The man sees the woman / the woman saw the man

Aβá kuɲã osepjak . \n the man sees the woman .
obl:subj(osepjak, aβá)
obl:subj(3-3-see, man)

obl:subj in other languages:

[gn]

[gub]

[tpn]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package org.isisaddons.module.security.dom.role;

import javax.inject.Inject;
import org.apache.isis.applib.DomainObjectContainer;

/**
 * Optional hook so that alternative implementations of {@link org.isisaddons.module.security.dom.role.ApplicationRole}.
 *
 *

 *     To use, simply implement the interface and annotate that implementation with {@link org.apache.isis.applib.annotation.DomainService},
 *     for example:
 *

 *

 *     @DomainService
 *     public class MyApplicationRoleFactory implements ApplicationRoleFactory {
 *         public ApplicationRole newApplicationRole() {
 *             return container.newTransientInstance(MyApplicationRole.class);
 *         }
 *
 *         @Inject
 *         DomainObjectContainer container;
 *     }
 *

 *

 *     where:
 *

 *

 *     public class MyApplicationRole extends ApplicationRole { ... }
 *

 */
public interface ApplicationRoleFactory {

    public ApplicationRole newApplicationRole();

    public static class Default implements ApplicationRoleFactory {

        public Default() {
            this(null);
        }
        Default(final DomainObjectContainer container) {
            this.container = container;
        }
        public ApplicationRole newApplicationRole() {
            return container.newTransientInstance(ApplicationRole.class);
        }

        @Inject
        DomainObjectContainer container;

    }

}


text:
CREATE TABLE ren_cms_Content_Types (
		actionpath VARCHAR (350) NOT NULL
		, controller VARCHAR (250) NOT NULL
		, createPartial VARCHAR (250) NULL DEFAULT ('default')
		, editPartial VARCHAR (250) NULL DEFAULT ('default')
		, name VARCHAR (250) NOT NULL
)