text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import javax.annotation.Nullable;

/**
 * GWT emulated version of {@link ImmutableCollection}.
 *
 * @author Jesse Wilson
 */
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableCollection<E> extends AbstractCollection<E>
    implements Serializable {

  static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION
      = new ForwardingImmutableCollection<Object>(Collections.emptyList());

  ImmutableCollection() {}

  public abstract UnmodifiableIterator<E> iterator();

  public boolean contains(@Nullable Object object) {
    return object != null && super.contains(object);
  }

  public final boolean add(E e) {
    throw new UnsupportedOperationException();
  }

  public final boolean remove(Object object) {
    throw new UnsupportedOperationException();
  }

  public final boolean addAll(Collection<? extends E> newElements) {
    throw new UnsupportedOperationException();
  }

  public final boolean removeAll(Collection<?> oldElements) {
    throw new UnsupportedOperationException();
  }

  public final boolean retainAll(Collection<?> elementsToKeep) {
    throw new UnsupportedOperationException();
  }

  public final void clear() {
    throw new UnsupportedOperationException();
  }

  private transient ImmutableList<E> asList;

  public ImmutableList<E> asList() {
    ImmutableList<E> list = asList;
    return (list == null) ? (asList = createAsList()) : list;
  }

  ImmutableList<E> createAsList() {
    switch (size()) {
      case 0:
        return ImmutableList.of();
      case 1:
        return ImmutableList.of(iterator().next());
      default:
        return new RegularImmutableAsList<E>(this, toArray());
    }
  }
  static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) {
    return new ForwardingImmutableCollection<E>(delegate);
  }

  boolean isPartialView() {
    return false;
  }

  /**
   * GWT emulated version of {@link ImmutableCollection.Builder}.
   */
  public abstract static class Builder<E> {

    Builder() {}

    public abstract Builder<E> add(E element);

    public Builder<E> add(E... elements) {
      checkNotNull(elements); // for GWT
      for (E element : elements) {
        add(checkNotNull(element));
      }
      return this;
    }

    public Builder<E> addAll(Iterable<? extends E> elements) {
      checkNotNull(elements); // for GWT
      for (E element : elements) {
        add(checkNotNull(element));
      }
      return this;
    }

    public Builder<E> addAll(Iterator<? extends E> elements) {
      checkNotNull(elements); // for GWT
      while (elements.hasNext()) {
        add(checkNotNull(elements.next()));
      }
      return this;
    }

    public abstract ImmutableCollection<E> build();
  }
}

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Authorization;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Security;

namespace Umbraco.Cms.Web.BackOffice.Authorization;

/// <summary>
///     Used to authorize if the user has the correct permission access to the content for the <see cref="IContent" />
///     specified.
/// </summary>
public class MediaPermissionsResourceHandler : MustSatisfyRequirementAuthorizationHandler<
    MediaPermissionsResourceRequirement, MediaPermissionsResource>
{
    private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor;
    private readonly MediaPermissions _mediaPermissions;

    /// <summary>
    ///     Initializes a new instance of the <see cref="MediaPermissionsResourceHandler" /> class.
    /// </summary>
    /// <param name="backOfficeSecurityAccessor">Accessor for back-office security.</param>
    /// <param name="mediaPermissions">Helper for media authorization checks.</param>
    public MediaPermissionsResourceHandler(
        IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
        MediaPermissions mediaPermissions)
    {
        _backOfficeSecurityAccessor = backOfficeSecurityAccessor;
        _mediaPermissions = mediaPermissions;
    }

    /// <inheritdoc />
    protected override Task<bool> IsAuthorized(AuthorizationHandlerContext context,
        MediaPermissionsResourceRequirement requirement, MediaPermissionsResource resource)
    {
        MediaPermissions.MediaAccess permissionResult = resource.NodeId.HasValue
            ? _mediaPermissions.CheckPermissions(
                _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser,
                resource.NodeId.Value,
                out _)
            : _mediaPermissions.CheckPermissions(
                resource.Media,
                _backOfficeSecurityAccessor.BackOfficeSecurity?.CurrentUser);

        return Task.FromResult(permissionResult != MediaPermissions.MediaAccess.Denied);
    }
}


text:
import test from 'ava'
import expect from 'expect.js'
import {Url} from '../src'

test('Url.parse & Url.stringify', () => {
  let item, val, orig
  item = 'https://username:password@www.test.com:8080/path/index.html?this=that&some=thing#content'
  expect(val = Url.parse(item)).to.eql({
    anchor: 'content',
    query: 'this=that&some=thing',
    file: 'index.html',
    directory: '/path/',
    path: '/path/index.html',
    relative: '/path/index.html?this=that&some=thing#content',
    port: '8080',
    host: 'www.test.com',
    password: 'password',
    user: 'username',
    userInfo: 'username:password',
    authority: 'username:password@www.test.com:8080',
    protocol: 'https',
    source: 'https://username:password@www.test.com:8080/path/index.html?this=that&some=thing#content'
  })
  expect(Url.stringify(val)).to.be(item)

  item = ''
  expect(val = Url.parse(item)).to.eql(orig = {
    anchor: '',
    query: '',
    file: '',
    directory: '',
    path: '',
    relative: '',
    port: '',
    host: '',
    password: '',
    user: '',
    userInfo: '',
    authority: '',
    protocol: '',
    source: ''
  })
  expect(Url.stringify(val)).to.be(item)

  orig.protocol = 'http'
  expect(Url.stringify(orig)).to.be(item)

  orig.protocol = ''
  orig.host = 'www.google.com'
  expect(Url.stringify(orig)).to.be(item = '//www.google.com')
  val = Url.parse(item)
  expect(val.authority).to.eql(orig.host); val.authority = ''
  expect(val.source).to.eql(item); val.source = ''
  expect(val).to.eql(orig)

  orig.protocol = 'https'
  expect(Url.stringify(orig)).to.be(item = 'https://www.google.com')
  val = Url.parse(item)
  expect(val.authority).to.eql(orig.host); val.authority = ''
  expect(val.source).to.eql(item); val.source = ''
  expect(val).to.eql(orig)

  orig.user = 'jetiny'
  orig.password = 'password'
  orig.userInfo = 'jetiny:password'
  orig.authority = 'jetiny:password@www.google.com'
  orig.source = 'https://jetiny:password@www.google.com'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)

  orig.port = '80'
  orig.authority += ':80'
  orig.source = 'https://jetiny:password@www.google.com:80'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)

  orig.path = '/'
  orig.directory = '/'
  orig.relative = '/'
  orig.source = 'https://jetiny:password@www.google.com:80/'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)

  orig.path = '/index.html'
  orig.file = 'index.html'
  orig.relative = orig.directory + orig.file
  orig.source = 'https://jetiny:password@www.google.com:80/index.html'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)

  orig.query = 'a=b'
  orig.relative = orig.directory + orig.file + '?' + orig.query
  orig.source = 'https://jetiny:password@www.google.com:80/index.html?a=b'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)

  orig.anchor = 'c'
  orig.relative = orig.directory + orig.file + '?' + orig.query + '#' + orig.anchor
  orig.source = 'https://jetiny:password@www.google.com:80/index.html?a=b#c'
  expect(item = Url.stringify(orig)).to.be(orig.source)
  expect(Url.parse(item)).to.eql(orig)
})


text:
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var jwt = require('jwt-simple');
var Q = require('q');

var findUser = Q.nbind(User.findOne, User);
var createUser = Q.nbind(User.create, User);

module.exports = {
  register: function (req, res, next) {
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;

    if (!email || !username || !password) {
      res.status(400).json({
        message: "All fields required."
      });
    } else {
      findUser({ email: email })
        .then(function (user) {
          if (user) {
            res.status(400).json({
              message: 'User already exists.'
            });
            return null;
          } else {
            return createUser({
              email: email,
              username: username,
              password: password
            });
          }
        })
        .then(function (user) {
          if (user) {
            var token = jwt.encode(user, process.env.JWT_SECRET || 'ancient dev secret');
            res.json({"token": token});
          }
        })
        .fail(function (error) {
          next(error);
        });
    }

  },
  login: function (req, res, next) {
    var email = req.body.email;
    var password = req.body.password;

    // console.log(req.body);
    if (!email || !password) {
      res.status(400).json({
        message: 'All fields required.'
      });
    } else {
      passport.authenticate('local', function (err, user, info) {
        var token;
        if (err) {
          res.status(400).json({
            message: "Incorrect username or password"
          });
        }
        if (user) {
          token = jwt.encode(user, process.env.JWT_SECRET || 'ancient dev secret');
          res.json({token: token});
        } else {
          res.status(400).json({
            message: "Incorrect username or password."
          });
        }
      })(req, res);
    }
  }
};


text:
package org.kaazing.mina.netty.socket;

import java.net.InetSocketAddress;

import org.apache.mina.core.service.DefaultTransportMetadata;
import org.apache.mina.core.service.TransportMetadata;
import org.apache.mina.transport.socket.DatagramConnector;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.jboss.netty.channel.socket.DatagramChannelFactory;

import org.kaazing.mina.netty.ChannelIoConnector;
import org.kaazing.mina.netty.DefaultIoConnectorChannelHandlerFactory;
import org.kaazing.mina.netty.IoConnectorChannelHandlerFactory;
import org.kaazing.mina.netty.bootstrap.ClientBootstrapFactory;

public abstract class DatagramChannelIoConnector
    extends ChannelIoConnector<DatagramChannelIoSessionConfig, DatagramChannelFactory, InetSocketAddress>
    implements DatagramConnector {

    private static final TransportMetadata CONNECTIONLESS_TRANSPORT_METADATA = new DefaultTransportMetadata(
            "Kaazing", "DatagramChannel", true, true, InetSocketAddress.class,
            DatagramSessionConfig.class, Object.class);

    public DatagramChannelIoConnector(DatagramChannelIoSessionConfig sessionConfig,
            DatagramChannelFactory channelFactory) {
        this(sessionConfig, channelFactory, new DefaultIoConnectorChannelHandlerFactory());
    }

    protected DatagramChannelIoConnector(DatagramChannelIoSessionConfig sessionConfig,
            DatagramChannelFactory channelFactory, IoConnectorChannelHandlerFactory handlerFactory) {
        super(sessionConfig, channelFactory, handlerFactory, ClientBootstrapFactory.CONNECTIONLESS);
    }

    @Override
    public void setDefaultRemoteAddress(InetSocketAddress remoteAddress) {
        super.setDefaultRemoteAddress(remoteAddress);
    }

    @Override
    public TransportMetadata getTransportMetadata() {
        return CONNECTIONLESS_TRANSPORT_METADATA;
    }
}


text:
Posts.views.add("category", function (terms) {
  var category = Categories.findOne({slug: terms.category});
  var childCategories = category.getChildren(category);
  var categoriesIds = [category._id].concat(_.pluck(childCategories, "_id"));
  return {
    find: {'categories': {$in: categoriesIds}} ,
    options: {sort: {sticky: -1, score: -1}} // for now categories views default to the "top" view
  };
});


text:
from modod import dre
from modod import dre_extended as ext

def rewritePlus(rho):
    old, new = None, rho
    while old != new:
        old, new = new, ruleP4(ruleP2(ruleP1(new).toPNF()).toPNF()).toPNF()
    return new

def ruleP1(rho):
    if isinstance(rho, dre.Concatenation):
        c = rho.children
        i = len(c) - 1
        while i > 0:
            # Look for a* expression...
            if isStar(c[i]):
                a = c[i].child.child
                # preceded by a' equivalent to a.
                # (a' must precede a* because of determinism)
                for j in range(i - 1, -1, -1):
                    if conc(c[j:i]).equivalentTo(a):
                        # Replace (...a'a*...) with (...a+...)
                        c = c[:j] + [dre.Plus(a)] + c[i+1:]
                        i = j
                        break
            i -= 1

        return conc([ruleP1(x) for x in c])

    elif isinstance(rho, dre.Nary):
        return rho.__class__([ruleP1(x) for x in rho.children])
    elif isinstance(rho, dre.Unary):
        return rho.__class__(ruleP1(rho.child))
    else:
        return rho

def ruleP2(rho):
    if isinstance(rho, dre.Concatenation):
        c = rho.children
        i = len(c) - 1
        while i > 0:
            # Look for w* expression...
            if isStar(c[i]):
                a = c[i].child.child
                if isinstance(c[i-1], dre.Optional) and isinstance(c[i-1].child, dre.Concatenation):
                    b = c[i-1].child.children
                    for j in range(len(b) - 1, -1, -1):
                        if conc(b[j:]).equivalentTo(a):
                            d = conc([dre.Optional(conc(b[:j])), dre.Plus(a)])
                            c = c[:i-1] + [dre.Optional(d)] + c[i+1:]
                            i -= 1
                            break
            i -= 1
        return conc([ruleP2(x) for x in c])

    elif isinstance(rho, dre.Nary):
        return rho.__class__([ruleP2(x) for x in rho.children])
    elif isinstance(rho, dre.Unary):
        return rho.__class__(ruleP2(rho.child))
    else:
        return rho

def ruleP4(rho, nullable = False):
    if isinstance(rho, dre.Terminal):
        return rho
    elif isinstance(rho, dre.Optional):
        return dre.Optional(ruleP4(rho.child, True))
    elif isinstance(rho, dre.Plus):
        return dre.Plus(ruleP4(rho.child))
    elif isinstance(rho, dre.Choice):
        n = nullable or rho.nullable()
        return choice([ruleP4(x, n) for x in rho.children])
    else:
        if nullable and isStar(rho.children[-1]):
            a = rho.children[-1].child
            b = conc(rho.children[:-1])
            A = a.first()
            bA = pf(A, b)
            if bA.equivalentTo(a.child):
                An = rho.terminals() - A
                bAn = pf(An, b)
                a = dre.Optional(ruleP4(a))
                return dre.Concatenation([dre.Optional(ruleP4(bAn)), a]) if bAn else a
        return conc([ruleP4(x) for x in rho.children])

def conc(children):
    return dre.Concatenation(children) if len(children) > 1 else children[0]

def choice(children):
    return dre.Choice(children) if len(children) > 1 else children[0]

# Returns a DRE with fully eliminated empty symbols.
def pf(a, rho):
    if isinstance(rho, dre.Optional):
        return ext.eliminateEmptySymbol(dre.Optional(pf(a, rho.child)))

    elif isinstance(rho, dre.Concatenation):
        b, c = rho.children[0], conc(rho.children[1:])
        if b.nullable():
            d = pf(a, c)
            # If b is nullable and c projects to the empty set, then
            # remove the leftmost option from b to make it not-nullable.
            if isinstance(d, ext.EmptySet):
                e = conc([pf(a, rlo(b)), c])
            else:
                e = conc([pf(a, b), d])
        else:
            e = conc([pf(a, b), c])

    elif isinstance(rho, dre.Choice):
        e = dre.Choice([pf(a, x) for x in rho.children])

    else:
        # Plus and Terminal:
        return rho if rho.first() <= a else ext.EmptySet()

    return ext.eliminateEmptySymbol(e)

def rlo(rho):
    if isinstance(rho, dre.Optional):
        return rho.child
    elif isinstance(rho, dre.Choice):
        return dre.Choice([rlo(x) for x in rho.children])
    elif isinstance(rho, dre.Concatenation):
        return dre.Concatenation([rlo(rho.children[0])] + rho.children[1:])
    else:
        return rho

def isStar(rho):
    return isinstance(rho, dre.Optional) and isinstance(rho.child, dre.Plus)


text:
package opennlp.fieldspring.tr.text.io;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;
import java.util.*;

import opennlp.fieldspring.tr.text.*;
import opennlp.fieldspring.tr.text.prep.*;
import opennlp.fieldspring.tr.util.*;
import opennlp.fieldspring.tr.topo.*;

public class CorpusXMLSource extends DocumentSource {
  private final XMLStreamReader in;
  private final Tokenizer tokenizer;

  public CorpusXMLSource(Reader reader, Tokenizer tokenizer) throws XMLStreamException {
    this.tokenizer = tokenizer;

    XMLInputFactory factory = XMLInputFactory.newInstance();
    this.in = factory.createXMLStreamReader(reader);

    while (this.in.hasNext() && this.in.next() != XMLStreamReader.START_ELEMENT) {}
    if (this.in.getLocalName().equals("corpus")) {
      this.in.nextTag();
    }
  }

  private void nextTag() {
    try {
      this.in.nextTag();
    } catch (XMLStreamException e) {
      System.err.println("Error while advancing TR-XML file.");
    }
  }

  public void close() {
    try {
      this.in.close();
    } catch (XMLStreamException e) {
      System.err.println("Error while closing TR-XML file.");
    }
  }

  public boolean hasNext() {
    return this.in.isStartElement() && this.in.getLocalName().equals("doc");
  }

  public Document<Token> next() {
    assert this.in.isStartElement() && this.in.getLocalName().equals("doc");
    String id = CorpusXMLSource.this.in.getAttributeValue(null, "id");
    String goldLatS = CorpusXMLSource.this.in.getAttributeValue(null, "goldLat");
    String goldLngS = CorpusXMLSource.this.in.getAttributeValue(null, "goldLng");
    Coordinate goldCoord = null;
    if(goldLatS != null && goldLngS != null)
        goldCoord = Coordinate.fromDegrees(Double.parseDouble(goldLatS), Double.parseDouble(goldLngS));
    String systemLatS = CorpusXMLSource.this.in.getAttributeValue(null, "systemLat");
    String systemLngS = CorpusXMLSource.this.in.getAttributeValue(null, "systemLng");
    Coordinate systemCoord = null;
    if(systemLatS != null && systemLngS != null)
        systemCoord = Coordinate.fromDegrees(Double.parseDouble(systemLatS), Double.parseDouble(systemLngS));
    String timestamp = CorpusXMLSource.this.in.getAttributeValue(null, "timestamp");

    CorpusXMLSource.this.nextTag();

    return new Document(id, timestamp, goldCoord, systemCoord) {
      private static final long serialVersionUID = 42L;
      public Iterator<Sentence<Token>> iterator() {
        return new SentenceIterator() {
          public boolean hasNext() {
            if (CorpusXMLSource.this.in.isStartElement() &&
                CorpusXMLSource.this.in.getLocalName().equals("s")) {
              return true;
            } else {
              return false;
            }
          }

          public Sentence<Token> next() {
            String id = CorpusXMLSource.this.in.getAttributeValue(null, "id");
            List<Token> tokens = new ArrayList<Token>();
            List<Span<Toponym>> toponymSpans = new ArrayList<Span<Toponym>>();

            try {
              while (CorpusXMLSource.this.in.nextTag() == XMLStreamReader.START_ELEMENT &&
                    (CorpusXMLSource.this.in.getLocalName().equals("w") ||
                     CorpusXMLSource.this.in.getLocalName().equals("toponym"))) {
                String name = CorpusXMLSource.this.in.getLocalName();

                if (name.equals("w")) {
                  tokens.add(new SimpleToken(CorpusXMLSource.this.in.getAttributeValue(null, "tok")));
                } else {
                  int spanStart = tokens.size();
                  String form = CorpusXMLSource.this.in.getAttributeValue(null, "term");
                  List<String> formTokens = CorpusXMLSource.this.tokenizer.tokenize(form);

                  for (String formToken : CorpusXMLSource.this.tokenizer.tokenize(form)) {
                    tokens.add(new SimpleToken(formToken));
                  }

                  ArrayList<Location> locations = new ArrayList<Location>();
                  int goldIdx = -1;
                  int selectedIdx = -1;

                  if (CorpusXMLSource.this.in.nextTag() == XMLStreamReader.START_ELEMENT &&
                      CorpusXMLSource.this.in.getLocalName().equals("candidates")) {
                    while (CorpusXMLSource.this.in.nextTag() == XMLStreamReader.START_ELEMENT &&
                           CorpusXMLSource.this.in.getLocalName().equals("cand")) {
                      String gold = CorpusXMLSource.this.in.getAttributeValue(null, "gold");
                      String selected = CorpusXMLSource.this.in.getAttributeValue(null, "selected");
                      if (selected != null && (selected.equals("yes") || selected.equals("true"))) {
                        selectedIdx = locations.size();
                      }
                      if (gold != null && (gold.equals("yes") || selected.equals("true"))) {
                        goldIdx = locations.size();
                      }

                      String locId = CorpusXMLSource.this.in.getAttributeValue(null, "id");
                      String type = CorpusXMLSource.this.in.getAttributeValue(null, "type");
                      String popString = CorpusXMLSource.this.in.getAttributeValue(null, "population");
                      Integer population = null;
                      if(popString != null)
                          population = Integer.parseInt(popString);
                      String admin1code = CorpusXMLSource.this.in.getAttributeValue(null, "admin1code");

                      ArrayList<Coordinate> representatives = new ArrayList<Coordinate>();
                      if(CorpusXMLSource.this.in.nextTag() == XMLStreamReader.START_ELEMENT &&
                         CorpusXMLSource.this.in.getLocalName().equals("representatives")) {
                          while(CorpusXMLSource.this.in.nextTag() == XMLStreamReader.START_ELEMENT &&
                                CorpusXMLSource.this.in.getLocalName().equals("rep")) {
                              double lat = Double.parseDouble(CorpusXMLSource.this.in.getAttributeValue(null, "lat"));
                              double lng = Double.parseDouble(CorpusXMLSource.this.in.getAttributeValue(null, "long"));
                              representatives.add(Coordinate.fromDegrees(lat, lng));
                              CorpusXMLSource.this.nextTag();
                              assert CorpusXMLSource.this.in.isEndElement() &&
                                     CorpusXMLSource.this.in.getLocalName().equals("rep");
                          }
                      }

                      Region region = new PointSetRegion(representatives);
                      Location loc = new Location(locId, form, region, type, population, admin1code);
                      locations.add(loc);
                      CorpusXMLSource.this.nextTag();
                      assert CorpusXMLSource.this.in.isEndElement() &&
                             CorpusXMLSource.this.in.getLocalName().equals("cand");
                    }
                  }

                  if (locations.size() > 0 /*&& goldIdx > -1*/) {
                    Toponym toponym = new SimpleToponym(form, locations, goldIdx, selectedIdx);
                    toponymSpans.add(new Span<Toponym>(spanStart, tokens.size(), toponym));
                  }
                }
                CorpusXMLSource.this.nextTag();
                assert CorpusXMLSource.this.in.isStartElement() &&
                    (CorpusXMLSource.this.in.getLocalName().equals("w") ||
                     CorpusXMLSource.this.in.getLocalName().equals("toponym"));
              }
            } catch (XMLStreamException e) {
              System.err.println("Error while reading TR-XML file.");
            }

            CorpusXMLSource.this.nextTag();
            if(CorpusXMLSource.this.in.getLocalName().equals("doc")
               && CorpusXMLSource.this.in.isEndElement())
                CorpusXMLSource.this.nextTag();
            return new SimpleSentence(id, tokens, toponymSpans);
          }
        };
      }
    };
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ParameterizedClass (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.config

Class ParameterizedClass

java.lang.Object

org.apache.cassandra.config.ParameterizedClass

public class ParameterizedClass
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

java.lang.String
class_name

java.util.Map<java.lang.String,java.lang.String>
parameters

Constructor Summary

Constructors

Constructor and Description

ParameterizedClass(java.util.LinkedHashMap<java.lang.String,?> p)

ParameterizedClass(java.lang.String class_name,
                  java.util.Map<java.lang.String,java.lang.String> parameters)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object that)

boolean
equals(ParameterizedClass that)

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

class_name

public java.lang.String class_name

parameters

public java.util.Map<java.lang.String,java.lang.String> parameters

Constructor Detail

ParameterizedClass

public ParameterizedClass(java.lang.String class_name,
                          java.util.Map<java.lang.String,java.lang.String> parameters)

ParameterizedClass

public ParameterizedClass(java.util.LinkedHashMap<java.lang.String,?> p)

Method Detail

equals

public boolean equals(java.lang.Object that)

Overrides:

equals in class java.lang.Object

equals

public boolean equals(ParameterizedClass that)

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015 The Apache Software Foundation


text:
package it.av.youeat.web.security;

import it.av.youeat.ocm.model.Eater;
import it.av.youeat.service.EaterService;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author Alessandro Vincelli
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private EaterService service;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        Eater user;
        user = service.getByEmail(username);
        if (user != null) {
            return new UserDetailsImpl(user);
        } else {
            throw new UsernameNotFoundException("Eater not valid");
        }

    }

    public void setService(EaterService service) {
        this.service = service;
    }
}


text:
module Azure::Compute::Mgmt::V2018_10_01
  module Models
    #
    # Response after calling a manual recovery walk
    #
    class RecoveryWalkResponse

      include MsRestAzure

      # @return [Boolean] Whether the recovery walk was performed
      attr_accessor :walk_performed

      # @return [Integer] The next update domain that needs to be walked. Null
      # means walk spanning all update domains has been completed
      attr_accessor :next_platform_update_domain

      #
      # Mapper for RecoveryWalkResponse class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'RecoveryWalkResponse',
          type: {
            name: 'Composite',
            class_name: 'RecoveryWalkResponse',
            model_properties: {
              walk_performed: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'walkPerformed',
                type: {
                  name: 'Boolean'
                }
              },
              next_platform_update_domain: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'nextPlatformUpdateDomain',
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php namespace Arinstar\Theme;

use Closure;
use ReflectionClass;
use Illuminate\Http\Response;
use Illuminate\View\Factory;
use Illuminate\Config\Repository;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Arinstar\Theme\Compilers\TwigCompiler;
use Illuminate\View\Compilers\BladeCompiler;
use Symfony\Component\HttpFoundation\Cookie;
use Arinstar\Theme\Contracts\Theme as ThemeContract;

class Theme implements ThemeContract
{
    /**
     * Theme namespace.
     */
    public static $namespace = 'theme';

    /**
     * Repository config.
     *
     * @var \Illuminate\Config\Repository
     */
    protected $config;

    /**
     * Event dispatcher.
     *
     * @var \Illuminate\Events\Dispatcher
     */
    protected $events;

    /**
     * Theme configuration.
     *
     * @var mixed
     */
    protected $themeConfig;

    /**
     * View.
     *
     * @var \Illuminate\View\Factory
     */
    protected $view;

    /**
     * Asset.
     *
     * @var \Arinstar\Assets
     */
    protected $asset;

    /**
     * Filesystem.
     *
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;

    /**
     * Breadcrumb.
     *
     * @var \Arinstar\Breadcrumb
     */
    protected $breadcrumb;

    /**
     * The name of theme.
     *
     * @var string
     */
    protected $theme;

    /**
     * The name of layout.
     *
     * @var string
     */
    protected $layout;

    /**
     * Content dot path.
     *
     * @var string
     */
    protected $content;

    /**
     * Regions in the theme.
     *
     * @var array
     */
    protected $regions = array();

    /**
     * Content arguments.
     *
     * @var array
     */
    protected $arguments = array();

    /**
     * Data bindings.
     *
     * @var array
     */
    protected $bindings = array();

    /**
     * Cookie var.
     *
     * @var Cookie
     */
    protected $cookie;

    /**
     * Engine compiler.
     *
     * @var array
     */
    protected $compilers = array();

    /**
     * Create a new theme instance.
     *
     * @param  \Illuminate\Config\Repository $config
     * @param  \Illuminate\Events\Dispatcher $events
     * @param  \Illuminate\View\Factory $view |
     * @param  \Arinstar\Theme\asset $asset
     * @param  \Illuminate\Filesystem\Filesystem $files
     * @param  \Arinstar\Breadcrumb|\Arinstar\Theme\Breadcrumb $breadcrumb
     *
     * @return \Arinstar\Theme\Theme
     */
    public function __construct(Repository $config,
                                Dispatcher $events,
                                Factory $view,
                                Asset $asset,
                                Filesystem $files,
                                Breadcrumb $breadcrumb)
    {

        $this->config = $config;

        $this->events = $events;

        $this->view = $view;

        $this->asset = $asset;

        $this->files = $files;

        $this->breadcrumb = $breadcrumb;

        // // Default theme.
        // $this->theme  = $this->getConfig('themeDefault');

        // // Default layout.
        // $this->layout = $this->getConfig('layoutDefault');

        // Blade compiler.
        $this->compilers['blade'] = new BladeCompiler($files, 'theme');

        // Twig compiler.
        $this->compilers['twig'] = new TwigCompiler($config, $view);
    }

    /**
     * Get current theme name.
     *
     * @return string
     */
    public function getThemeName()
    {
        return $this->theme;
    }

    /**
     * Get current layout name.
     *
     * @return string
     */
    public function getLayoutName()
    {
        return $this->layout;
    }

    /**
     * Get theme namespace.
     *
     * @param string $path
     *
     * @return string
     */
    public function getThemeNamespace($path = '')
    {
        // Namespace relate with the theme name.
        $namespace = static::$namespace.'.'.$this->getThemeName();

        if ($path != false) {
            return $namespace.'::'.$path;
        }

        return $namespace;
    }

    /**
     * Check theme exists.
     *
     * @param  string  $theme
     * @return boolean
     */
    public function exists($theme)
    {
        $path = app('path.public').'/'.$this->path($theme).'/';

        return is_dir($path);
    }

    /**
     * Link to another view.
     *
     * <code>
     *      // Look up view from another view in the same place.
     *      Theme::symlink('another')
     * </code>
     *
     * @param  string $theme
     * @return string
     */
    public function symlink($theme)
    {
        $trace = debug_backtrace();

        if (! isset($trace[1])) return;

        $link = str_replace($this->getThemeName(), $theme, array_get($trace[1], 'file'));

        extract($this->arguments);
        extract($this->view->getShared());

        return require($link);
    }

    /**
     * Symlink with inherit.
     *
     * This method is the same symlink, but try to find inherit,
     * from config.
     *
     * @param  string $theme
     * @return string
     */
    public function symlinkWithFindInherit($theme)
    {
        $trace = debug_backtrace();

        if (! isset($trace[1])) return;

        // change backslash to forward slash (for windows file system)
        $path = str_replace("\\", "/", array_get($trace[1], 'file'));

        $config = $this->getConfig();

        $link = preg_replace("#(public/{$config['themeDir']}/)[^/]+#", "$1{$theme}", $path);

        extract($this->arguments);
        extract($this->view->getShared());

        return require($link);
    }

    /**
     * Get theme config.
     *
     * @param  string $key
     * @return mixed
     */
    public function getConfig($key = null)
    {
        // Main package config.
        if (! $this->themeConfig) {
            $this->themeConfig = $this->config->get('theme');
        }

        // Config inside a public theme.
        // This config having buffer by array object.
        if ($this->theme and ! isset($this->themeConfig['themes'][$this->theme])) {
            $this->themeConfig['themes'][$this->theme] = array();

            try {
                // Require public theme config.
                $minorConfigPath = public_path($this->themeConfig['themeDir'].'/'.$this->theme.'/config.php');

                $this->themeConfig['themes'][$this->theme] = $this->files->getRequire($minorConfigPath);
            } catch (\Illuminate\Filesystem\FileNotFoundException $e) {
                //var_dump($e->getMessage());
            }
        }

        // Evaluate theme config.
        $this->themeConfig = $this->evaluateConfig($this->themeConfig);

        return is_null($key) ? $this->themeConfig : array_get($this->themeConfig, $key);
    }

    /**
     * Evaluate config.
     *
     * Config minor is at public folder [theme]/config.php,
     * thet can be override package config.
     *
     * @param  mixed $config
     * @return mixed
     */
    protected function evaluateConfig($config)
    {
        if (! isset($config['themes'][$this->theme])) {
            return $config;
        }

        // Config inside a public theme.
        $minorConfig = $config['themes'][$this->theme];

        // Before event is special case, It's combination.
        if (isset($minorConfig['events']['before'])) {
            $minorConfig['events']['appendBefore'] = $minorConfig['events']['before'];
            unset($minorConfig['events']['before']);
        }

        // Merge two config into one.
        $config = array_replace_recursive($config, $minorConfig);

        // Reset theme config.
        $config['themes'][$this->theme] = array();

        return $config;
    }

    /**
     * Add location path to look up.
     *
     * @param string $location
     */
    protected function addPathLocation($location)
    {
        // First path is in the selected theme.
        $hints[] = public_path($location);

        // This is nice feature to use inherit from another.
        if ($this->getConfig('inherit')) {
            // Inherit from theme name.
            $inherit = $this->getConfig('inherit');

            // Inherit theme path.
            $inheritPath = public_path($this->path($inherit));

            if ($this->files->isDirectory($inheritPath)) {
                array_push($hints, $inheritPath);
            }
        }

        // Add namespace with hinting paths.
        $this->view->addNamespace($this->getThemeNamespace(), $hints);
    }

    /**
     * Fire event to config listener.
     *
     * @param  string $event
     * @param  mixed  $args
     * @return void
     */
    public function fire($event, $args)
    {
        $onEvent = $this->getConfig('events.'.$event);

        if ($onEvent instanceof Closure) {
            $onEvent($args);
        }
    }

    /**
     * Set up a theme name.
     *
     * @param  string $theme
     * @throws UnknownThemeException
     * @return Theme
     */
    public function theme($theme = null)
    {
        // If theme name is not set, so use default from config.
        if ($theme != false) {
            $this->theme = $theme;
        }

        // Is theme ready?
        if (! $this->exists($theme)) {
            throw new UnknownThemeException("Theme [$theme] not found.");
        }

        // Add location to look up view.
        $this->addPathLocation($this->path());

        // Fire event before set up a theme.
        $this->fire('before', $this);

        // Before from a public theme config.
        $this->fire('appendBefore', $this);

        // Add asset path to asset container.
        $this->asset->addPath($this->path().'/'.$this->getConfig('containerDir.asset'));

        return $this;
    }

    /**
     * Alias of theme method.
     *
     * @param  string $theme
     * @return Theme
     */
    public function uses($theme = null)
    {
        return $this->theme($theme);
    }

    /**
     * Set up a layout name.
     *
     * @param  string $layout
     * @return Theme
     */
    public function layout($layout)
    {
        // If layout name is not set, so use default from config.
        if ($layout != false) {
            $this->layout = $layout;
        }

        return $this;
    }

    /**
     * Get theme path.
     *
     * @param  string $forceThemeName
     * @return string
     */
    public function path($forceThemeName = null)
    {
        $themeDir = $this->getConfig('themeDir');

        $theme = $this->theme;

        if ($forceThemeName != false) {
            $theme = $forceThemeName;
        }

        return $themeDir.'/'.$theme;
    }

    /**
     * Set a place to regions.
     *
     * @param  string $region
     * @param  string $value
     * @return Theme
     */
    public function set($region, $value)
    {
        // Content is reserve region for render sub-view.
        if ($region == 'content') return;

        $this->regions[$region] = $value;

        return $this;
    }

    /**
     * Append a place to existing region.
     *
     * @param  string $region
     * @param  string $value
     * @return Theme
     */
    public function append($region, $value)
    {
        return $this->appendOrPrepend($region, $value, 'append');
    }

    /**
     * Prepend a place to existing region.
     *
     * @param  string $region
     * @param  string $value
     * @return Theme
     */
    public function prepend($region, $value)
    {
        return $this->appendOrPrepend($region, $value, 'prepend');
    }

    /**
     * Append or prepend existing region.
     *
     * @param  string $region
     * @param  string $value
     * @param  string $type
     * @return Theme
     */
    protected function appendOrPrepend($region, $value, $type = 'append')
    {
        // If region not found, create a new region.
        if (isset($this->regions[$region])) {
            switch ($type) {
                case 'prepend' :
                    $this->regions[$region] = $value.$this->regions[$region];
                    break;
                case 'append' :
                    $this->regions[$region] .= $value;
                    break;
            }
        } else {
            $this->set($region, $value);
        }

        return $this;
    }

    /**
     * Binding data to view.
     *
     * @param  string $variable
     * @param  mixed  $callback
     * @return mixed
     */
    public function bind($variable, $callback = null)
    {
        $name = 'bind.'.$variable;

        // If callback pass, so put in a queue.
        if (! empty($callback)) {
            // Preparing callback in to queues.
            $this->events->listen($name, function() use ($callback, $variable) {
                return ($callback instanceof Closure) ? $callback() : $callback;
            });
        }

        // Passing variable to closure.
        $_events   =& $this->events;
        $_bindings =& $this->bindings;

        // Buffer processes to save request.
        return array_get($this->bindings, $name, function() use (&$_events, &$_bindings, $name) {
            $response = current($_events->fire($name));
            array_set($_bindings, $name, $response);
            return $response;
        });
    }

    /**
     * Check having binded data.
     *
     * @param  string $variable
     * @return boolean
     */
    public function binded($variable)
    {
        $name = 'bind.'.$variable;

        return $this->events->hasListeners($name);
    }

    /**
     * Assign data across all views.
     *
     * @param  mixed $key
     * @param  mixed $value
     * @return mixed
     */
    public function share($key, $value)
    {
        return $this->view->share($key, $value);
    }

    /**
     * Set up a partial.
     *
     * @param  string $view
     * @param  array $args
     * @throws UnknownPartialFileException
     * @return mixed
     */
    public function partial($view, $args = array())
    {
        $partialDir = $this->getThemeNamespace($this->getConfig('containerDir.partial'));

        return $this->loadPartial($view, $partialDir, $args);
    }

    /**
     * The same as "partial", but having prefix layout.
     *
     * @param  string $view
     * @param  array $args
     * @throws UnknownPartialFileException
     * @return mixed
     */
    public function partialWithLayout($view, $args = array())
    {
        $view = $this->getLayoutName().'.'.$view;

        return $this->partial($view, $args);
    }

    /**
     * Load a partial
     *
     * @param  string $view
     * @param  string $partialDir
     * @param  array  $args
     * @throws UnknownPartialFileException
     * @return mixed
     */
    public function loadPartial($view, $partialDir, $args)
    {
        $path = $partialDir.'.'.$view;

        if (! $this->view->exists($path)) {
            throw new UnknownPartialFileException("Partial view [$view] not found.");
        }

        $partial = $this->view->make($path, $args)->render();
        $this->regions[$view] = $partial;

        return $this->regions[$view];
    }

    /**
     * Watch and set up a partial from anywhere.
     *
     * This method will first try to load the partial from current theme. If partial
     * is not found in theme then it loads it from app (i.e. app/views/partials)
     *
     * @param  string $view
     * @param  array $args
     * @throws UnknownPartialFileException
     * @return mixed
     */
    public function watchPartial($view, $args = array())
    {
        try {
            return $this->partial($view, $args);
        } catch (UnknownPartialFileException $e) {
            $partialDir = $this->getConfig('containerDir.partial');
            return $this->loadPartial($view, $partialDir, $args);
        }
    }

    /**
     * Widget instance.
     *
     * @param  string $className
     * @param  array $attributes
     * @throws UnknownWidgetClassException
     * @return Arinstar\Theme\Widget
     */
    public function widget($className, $attributes = array())
    {
        static $widgets = array();

        // If the class name is not lead with upper case add prefix "Widget".
        if (! preg_match('|^[A-Z]|', $className)) {
            $className = ucfirst($className);
        }

        $widgetNamespace = $this->getConfig('namespaces.widget');

        $className = $widgetNamespace.'\\'.$className;

        if (! $instance = array_get($widgets, $className)) {
            $reflector = new ReflectionClass($className);

            if (! $reflector->isInstantiable()) {
                throw new UnknownWidgetClassException("Widget target [$className] is not instantiable.");
            }

            $instance = $reflector->newInstance($this, $this->config, $this->view);
            array_set($widgets, $className, $instance);
        }

        $instance->setAttributes($attributes);
        $instance->beginWidget();
        $instance->endWidget();

        return $instance;
    }

    /**
     * Hook a partial before rendering.
     *
     * @param  mixed   $view
     * @param  closure $callback
     * @return void
     */
    public function partialComposer($view, $callback, $layout = null)
    {
        $partialDir = $this->getConfig('containerDir.partial');

        if (! is_array($view)) {
            $view = array($view);
        }

        // Partial path with namespace.
        $path = $this->getThemeNamespace($partialDir);

        // This code support partialWithLayout.
        if (! is_null($layout)) {
            $path = $path.'.'.$layout;
        }

        $view = array_map(function($v) use ($path) {
            return $path.'.'.$v;
        }, $view);

        $this->view->composer($view, $callback);
    }

    /**
     * Get compiler.
     *
     * @param  string $compiler
     * @return object
     */
    public function getCompiler($compiler)
    {
        if (isset($this->compilers[$compiler])) {
            return $this->compilers[$compiler];
        }
    }

    /**
     * Parses and compiles strings by using blade template system.
     *
     * @param  string $str
     * @param  array $data
     * @param  boolean $phpCompile
     * @throws \Exception
     * @return string
     */
    public function blader($str, $data = array(), $phpCompile = true)
    {
        if ($phpCompile == false) {
            $patterns = array('|<\?|', '|<\?php|', '|<\%|', '|\?>|', '|\%>|');
            $replacements = array('<?', '<php', '<%', '?>', '%>');

            $str = preg_replace($patterns, $replacements, $str);
        }

        // Get blade compiler.
        $parsed = $this->getCompiler('blade')->compileString($str);

        ob_start() and extract($data, EXTR_SKIP);

        try {
            eval('?>'.$parsed);
        } catch (\Exception $e) {
            ob_end_clean(); throw $e;
        }

        $str = ob_get_contents();
        ob_end_clean();

        return $str;
    }

    /**
     * Compile blade without PHP.
     *
     * @param  string $str
     * @param  array  $data
     * @return string
     */
    public function bladerWithOutServerScript($str, $data = array())
    {
        return $this->blader($str, $data, false);
    }

    /**
     * Compile twig.
     *
     * @param  string $str
     * @param  array  $data
     * @return string
     */
    public function twigy($str, $data = array())
    {
        return $this->getCompiler('twig')->setData($data)->compileString($str);
    }

    /**
     * Check region exists.
     *
     * @param  string  $region
     * @return boolean
     */
    public function has($region)
    {
        return (boolean) isset($this->regions[$region]);
    }

    /**
     * Render a region.
     *
     * @param  string $region
     * @param  mixed  $default
     * @return string
     */
    public function get($region, $default = null)
    {
        if ($this->has($region)) {
            return $this->regions[$region];
        }

        return $default ? $default : '';
    }

    /**
     * Render a region.
     *
     * @param  string $region
     * @param  mixed  $default
     * @return string
     */
    public function place($region, $default = null)
    {
        return $this->get($region, $default);
    }

    /**
     * Place content in sub-view.
     *
     * @return string
     */
    public function content()
    {
        return $this->regions['content'];
    }

    /**
     * Return asset instance.
     *
     * @return \Arinstar\Theme\Asset
     */
    public function asset()
    {
        return $this->asset;
    }

    /**
     * Return breadcrumb instance.
     *
     * @return \Arinstar\Theme\Breadcrumb
     */
    public function breadcrumb()
    {
        return $this->breadcrumb;
    }

    /**
     * Set up a content to template.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function of($view, $args = array(), $type = null)
    {
        // Layout.
        $layout = ucfirst($this->layout);

        // Fire event global assets.
        $this->fire('asset', $this->asset);

        // Fire event before render theme.
        $this->fire('beforeRenderTheme', $this);

        // Fire event before render layout.
        $this->fire('beforeRenderLayout.'.$this->layout, $this);

        // Keeping arguments.
        $this->arguments = $args;

        // Compile string blade, string twig, or from file path.
        switch ($type) {
            case 'blade' :
                $content = $this->bladerWithOutServerScript($view, $args);
                break;
            case 'twig' :
                $content = $this->twigy($view, $args);
                break;
            default :
                $content = $this->view->make($view, $args)->render();
                break;
        }

        // View path of content.
        $this->content = $view;

        // Set up a content regional.
        $this->regions['content'] = $content;

        return $this;
    }

    /**
     * The same as "of", but having prefix layout.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function ofWithLayout($view, $args = array(), $type = null)
    {
        $view = $this->getLayoutName().'.'.$view;

        return $this->of($view, $args, $type);
    }

    /**
     * Container view.
     *
     * Using a container module view inside a theme, this is
     * useful when you separate a view inside a theme.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function scope($view, $args = array(), $type = null)
    {
        $viewDir = $this->getConfig('containerDir.view');

        // Add namespace to find in a theme path.
        $path = $this->getThemeNamespace($viewDir.'.'.$view);

        return $this->of($path, $args, $type);
    }

    /**
     * The same as "scope", but having prefix layout.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function scopeWithLayout($view, $args = array(), $type = null)
    {
        $view = $this->getLayoutName().'.'.$view;

        return $this->scope($view, $args, $type);
    }

    /**
     * Load subview from direct path.
     *
     * @param  string $view
     * @param  array  $args
     * @return Theme
     */
    public function load($view, $args = array())
    {
        $view = ltrim($view, '/');

        $segments = explode('/', str_replace('.', '/', $view));

        // Pop file from segments.
        $view = array_pop($segments);

        // Custom directory path.
        $pathOfView = app('path.base').'/'.implode('/', $segments);

        // Add temporary path with a hint type.
        $this->view->addNamespace('custom', $pathOfView);

        return $this->of('custom::'.$view, $args);
    }

    /**
     * Watch view file in anywhere.
     *
     * Finding from scope first, then try to find from application view.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function watch($view, $args = array(), $type = null)
    {
        try {
            return $this->scope($view, $args, $type);
        } catch (\InvalidArgumentException $e) {
            return $this->of($view, $args, $type);
        }
    }

    /**
     * The same as "watch", but having prefix layout.
     *
     * Finding from scope first, then try to find from application view.
     *
     * @param  string $view
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function watchWithLayout($view, $args = array(), $type = null)
    {
        try {
            return $this->scopeWithLayout($view, $args, $type);
        } catch (\InvalidArgumentException $e) {
            return $this->ofWithLayout($view, $args, $type);
        }
    }

    /**
     * Get all arguments assigned to content.
     *
     * @return mixed
     */
    public function getContentArguments()
    {
        return $this->arguments;
    }

    /**
     * Get a argument assigned to content.
     *
     * @param  string $key
     * @param null $default
     * @return mixed
     */
    public function getContentArgument($key, $default = null)
    {
        return array_get($this->arguments, $key, $default);
    }

    /**
     * Checking content argument existing.
     *
     * @param  string  $key
     * @return boolean
     */
    public function hasContentArgument($key)
    {
        return (bool) isset($this->arguments[$key]);
    }

    /**
     * Find view location.
     *
     * @param  boolean $realpath
     * @return string
     */
    public function location($realpath = false)
    {
        if ($this->view->exists($this->content)) {
            return ($realpath) ? $this->view->getFinder()->find($this->content) : $this->content;
        }
    }

    /**
     * It's similar to location, but will look up from both
     * application's view and theme's view.
     *
     * ex. Theme::which('general.welcome');
     *
     * @param  string  $view
     * @param  boolean $realpath
     * @return string
     */
    public function which($view, $realpath = false)
    {
        return $this->watch($view)->location($realpath);
    }

    /**
     * Compile from string.
     *
     * @param  string $str
     * @param  array  $args
     * @param  string $type
     * @return Theme
     */
    public function string($str, $args = array(), $type = 'blade')
    {
        $shared = $this->view->getShared();
        $data['errors'] = $shared['errors'];
        $args = array_merge($data, $args);

        return $this->of($str, $args, $type);
    }

    /**
     * Set cookie to response.
     *
     * @param  Cookie $cookie
     * @return Theme
     */
    public function withCookie(Cookie $cookie)
    {
        $this->cookie = $cookie;

        return $this;
    }

    /**
     * Return a template with content.
     *
     * @param  integer $statusCode
     * @throws UnknownLayoutFileException
     * @return Response
     */
    public function render($statusCode = 200)
    {
        // Fire the event before render.
        $this->fire('after', $this);

        // Flush asset that need to serve.
        $this->asset->flush();

        // Layout directory.
        $layoutDir = $this->getConfig('containerDir.layout');

        $path = $this->getThemeNamespace($layoutDir.'.'.$this->layout);

        if (! $this->view->exists($path)) {
            throw new UnknownLayoutFileException("Layout [$this->layout] not found.");
        }

        $content = $this->view->make($path)->render();

        // Append status code to view.
        $content = new Response($content, $statusCode);

        // Having cookie set.
        if ($this->cookie) {
            $content->withCookie($this->cookie);
        }

        return $content;
    }

    /**
     * Magic method for set, prepend, append, has, get.
     *
     * @param  string $method
     * @param  array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters = array())
    {
        $callable = preg_split('|[A-Z]|', $method);

        if (in_array($callable[0], array('set', 'prepend', 'append', 'has', 'get'))) {
            $value = lcfirst(preg_replace('|^'.$callable[0].'|', '', $method));
            array_unshift($parameters, $value);

            return call_user_func_array(array($this, $callable[0]), $parameters);
        }

        trigger_error('Call to undefined method '.__CLASS__.'::'.$method.'()', E_USER_ERROR);
    }

}


text:
FROM unihubs/meteord:base
MAINTAINER MeteorHacks Pvt Ltd.

ONBUILD RUN bash $METEORD_DIR/lib/install_meteor.sh
ONBUILD COPY ./ /app
ONBUILD RUN bash $METEORD_DIR/lib/build_app.sh


text:
struct RenderCommandList;
struct RenderViewport;
class Scene;

class CustomRenderer
{
public:
	struct CommandParams
	{
		RenderCommandList* commandList;
		unsigned int callbackId;
		unsigned int fullscreenViewport;
		Scene* scene;
	};

	struct RenderParams
	{
		const RenderViewport* viewport;
		unsigned int callbackId;
		uint64_t command;
		Scene* scene;
	};

	virtual void AddRenderCommands(const CommandParams& params) {}
	virtual void RenderCustom(const RenderParams& params) {}
};


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Independence Day</title>
  <link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="game.css">
</head>
<body>
  <div ng-app="independence-day">
    <div ng-view>

    </div>
  </div>
  <script src="lib/jquery/dist/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="lib/angular/angular.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="lib/angular-route/angular-route.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="lib/phaser/build/phaser.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="lib/firebase/firebase.js" type="text/javascript" charset="utf-8"></script>
  <script src="lib/angular-bootstrap/ui-bootstrap-tpls.min.js" type="text/javascript" charset="utf-8"></script>
<!-- USER SCRIPTS -->
  <script src="main.js" type="text/javascript" charset="utf-8"></script>
  <script src="firebase-config.js" type="text/javascript" charset="utf-8"></script>
  <script src="config.js" type="text/javascript" charset="utf-8"></script>
  <script src="constants.js" type="text/javascript" charset="utf-8"></script>
  <script src="auth/auth-factory.js" type="text/javascript" charset="utf-8"></script>
  <script src="auth/auth-controller.js" type="text/javascript" charset="utf-8"></script>
  <script src="endOfGame/leaderboard-factory.js" type='text/javascript' charset="utf-8"></script>
  <script src="endOfGame/leaderboard-ctrl.js" type="text/javascript" charset="utf-8"></script>
  <script src="game/gameplay-controller.js" type="text/javascript" charset="utf-8"></script>

</body>
</html>


text:
require 'minitest/autorun'
require 'minitest/spec'
require 'minitest-spec-context'
require 'pp'

require_relative '../lib/retailcrm'
require_relative './bootstrap'

describe Retailcrm do

  before do
    @bootstrap = Bootstrap.new
    @api = Retailcrm.new(@bootstrap.api_url, @bootstrap.api_key)
    @customer = @bootstrap.customer
  end

  describe '#customers' do
    it 'responds with 200' do
      res = @api.customers({:email => 'test@example.com'}, 50, 1)
      res.status.to_i.must_equal 200
      res.response['customers'].must_be_instance_of Array
      res.response['customers'].each do |x|
        x['email'].must_equal 'test@example.com'
      end
    end
  end

end


text:
/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /api/<%= name %>              ->  index
 * POST    /api/<%= name %>              ->  create
 * GET     /api/<%= name %>/:id          ->  show
 * PUT     /api/<%= name %>/:id          ->  update
 * DELETE  /api/<%= name %>/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var Q = require('q');
var <%= className %> = require('./<%= name %>.model');
var utils = require('../../components/utils');

function handleError(res, statusCode) {
  statusCode = statusCode || 500;
  return function(err) {
    res.json(statusCode, err);
  };
}

function responseWithResult(res, statusCode) {
  statusCode = statusCode || 200;
  return function(entity) {
    if (entity) {
      res.json(statusCode, entity);
    }
  };
}

function handleEntityNotFound(res) {
  return function(entity) {
    if (!entity) {
      res.send(404);
      return null;
    }
    return entity;
  };
}

function saveUpdates(updates) {
  return function(entity) {
    var updated = _.merge(entity, updates);
    return updated.saveAsync()
      .then(function(updated) {
        return updated;
      });
  };
}

function removeEntity(res) {
  return function(entity) {
    if (entity) {
      return Q.Promise(function (resolve, reject) {
        entity.remove(function (err) {
          if(err) {
            reject(err);
          } else {
            resolve();
          }
        });
      }).then(function() {
        res.send(204);
      });
    }
  };
}

// Gets a list of Persons
exports.index = function(req, res) {
  var page  = req.query.page || 1,
      limit = req.query.limit || 20,
      skip  = (page - 1) * limit;

  var query = utils.parseQuery(req.query);

  Q.all([
    <%= className %>.count(query.where).exec(),
    <%= className %>.find(query.where)<%= referer ? '.populate({ path: \''+ referer.name +'\', select: \''+ referer.fields.toString().replace(/\,/g, ' ') +'\' })' : '' %>.sort(query.sort).skip(skip).limit(limit).exec()
  ])
  .spread(function (total, <%= name %>s) {
    res.set('X-Pagination-Total-Count', total);
    res.json(<%= name %>s);
  })
  .then(null, handleError(res));
};

// Gets a single <%= className %> from the DB
exports.show = function(req, res) {
<% if(referer) { %> <%= className %>.findById(req.params.id).populate({ path: '<%= referer.name %>', select: '<%= referer.fields.toString().replace(/\,/g, ' ') %>' }).exec() <% } else { %> <%= className %>.findById(req.params.id).exec() <% } %>
    .then(handleEntityNotFound(res))
    .then(responseWithResult(res))
    .then(null, handleError(res));
};

// Creates a new <%= className %> in the DB
exports.create = function(req, res) {
  <% if(referer) { %>
  if(req.body.<%= referer.name %>._id) {
    req.body.<%= referer.name %> = req.body.<%= referer.name %>._id;
  }
  <% } %>
  <%= className %>.create(req.body)
    .then(responseWithResult(res, 201))
    .then(null, handleError(res));
};

// Updates an existing <%= className %> in the DB
exports.update = function(req, res) {
  if (req.body._id) {
    delete req.body._id;
  }
  <% if(referer) { %>
  if(req.body.<%= referer.name %>._id) {
    req.body.<%= referer.name %> = req.body.<%= referer.name %>._id;
  }
  <% } %>
  <%= className %>.findById(req.params.id).exec()
    .then(handleEntityNotFound(res))
    .then(saveUpdates(req.body))
    .then(responseWithResult(res))
    .then(null, handleError(res));
};

// Deletes a <%= className %> from the DB
exports.destroy = function(req, res) {
  <%= className %>.findById(req.params.id).exec()
    .then(handleEntityNotFound(res))
    .then(removeEntity(res))
    .then(null, handleError(res));
};

/**
 * /api/<%= name %>/basic
 * @param  {String} req.query.q
 * @param  {String} req.query.fields field1|field2|field3
 *
 * @example
 *  /api/<%= name %>/basic?q=lorem&fields=field1|field2|field3
 */
exports.basic = function(req, res) {
  var q = req.query.q;
  var match = req.query.match,
      fields = req.query.fields;
  var filter = {};

  if(fields) {
    var or = (match || fields).split('|').map(function (field) {
      var obj = {};
      obj[field] = new RegExp(q, 'i');
      return obj;
    });
    filter = { $or: or };
  } else {
    <% if(referer) { %>
    filter = q ? { <%= referer.fields[0] %>: new RegExp(q, 'i') } : {} ;
    <% } else { %>
    filter = q ? { name: new RegExp(q, 'i') } : {} ;
    <% } %>
  }
  <%= className %>.find(filter).exec()
    .then(responseWithResult(res))
    .then(null, handleError(res));
};

exports.basicInfo = function(req, res) {
<% if(referer) { %> <%= className %>.findById(req.params.id).populate({ path: '<%= referer.className %>', select: '<%= referer.fields.toString().replace(/\,/g, ' ') %>' }).exec() <% } else { %> <%= className %>.findById(req.params.id).exec() <% } %>
    .then(handleEntityNotFound(res))
    .then(responseWithResult(res))
    .then(null, handleError(res));
};


text:
/* eslint-disable promise/always-return */
import { map } from "lodash"
import { runQuery, runAuthenticatedQuery } from "schema/v1/test/utils"

describe("HomePageArtistModules", () => {
  let context = null
  const artists = [
    {
      id: "foo-bar",
      name: "Foo Bar",
      bio: null,
      blurb: null,
      birthday: null,
      artworks_count: 42,
    },
  ]

  const artistResultsWithData = {
    body: artists,
    headers: { "x-total-count": 1 },
  }
  const artistResultsWithoutData = { body: [], headers: { "x-total-count": 0 } }

  beforeEach(() => {
    context = {
      suggestedSimilarArtistsLoader: () =>
        Promise.resolve(artistResultsWithData),
      trendingArtistsLoader: () => Promise.resolve(artistResultsWithData),
      popularArtistsLoader: () => Promise.resolve(artistResultsWithData),
    }
  })

  describe("concerning display", () => {
    const query = `
      {
        home_page {
          artist_modules {
            key
          }
        }
      }
    `

    describe("when signed-in", () => {
      it("shows all modules if there are any suggestions", () => {
        return runAuthenticatedQuery(query, context).then(({ home_page }) => {
          const keys = map(home_page.artist_modules, "key")
          expect(keys).toEqual(["SUGGESTED", "TRENDING", "POPULAR"])
        })
      })

      it("only shows the trending and popular artists modules if there are no suggestions", () => {
        context.suggestedSimilarArtistsLoader = () =>
          Promise.resolve(artistResultsWithoutData)
        return runAuthenticatedQuery(query, context).then(({ home_page }) => {
          const keys = map(home_page.artist_modules, "key")
          expect(keys).toEqual(["TRENDING", "POPULAR"])
        })
      })
    })

    describe("when signed-out", () => {
      it("only shows the trending and popular artists modules", () => {
        delete context.suggestedSimilarArtistsLoader
        return runQuery(query, context).then(({ home_page }) => {
          const keys = map(home_page.artist_modules, "key")
          expect(keys).toEqual(["TRENDING", "POPULAR"])
        })
      })
    })
  })
})


text:
import {
    OneToMany,
    Entity,
    PrimaryGeneratedColumn,
    Column,
} from "../../../../src"

import { UserPhoto } from "./UserPhoto"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany(() => UserPhoto, (userPhoto) => userPhoto.photo, {
        cascade: true,
    })
    userPhotos: UserPhoto[]
}


text:
require "browserify_rb/nvm"

require "stringio"
require "logger"

class BrowserifyRb::Nvm::Browserify
  DEFAULT_NVM_DIR = "#{ENV["HOME"]}/.nvm"
  LOG = Logger.new(STDERR)
  LOG.level = Logger::Severity.const_get(ENV["LOG"] || "INFO")
  LOG.progname = BrowserifyRb::Nvm::Browserify

  def initialize(
        browserify_opts: "", node_ver: nil, env: {},
        nvm_dir: DEFAULT_NVM_DIR, suppress_stderr: false,
        required_modules: nil)
    @nvm = BrowserifyRb::Nvm.new nvm_dir
    @node_ver = node_ver
    @env = env
    @browserify_opts = browserify_opts
    @suppress_stderr = suppress_stderr
    @prepared = false
    @modules = required_modules
  end

  def prepare
    ms = ["browserify", *@modules].map{|m| %!"#{m}"! }.join(" ")
    cmd = "npm install #{ms}"
    stdout_handler = proc { }
    stderr_handler = @suppress_stderr ?
                       proc { } :
                       proc {|d| STDERR.print d}
    LOG.debug "run: #{cmd}"
    status = @nvm.run(
      cmd,
      node_ver: @node_ver,
      env: @env,
      stdout_handler: stdout_handler,
      stderr_handler: stderr_handler
    ).value
    raise "non-zero exit status: #{status.to_i}" unless status.success?
    @prepared = true
  end

  def compile source
    prepare unless @prepared

    out_buf = StringIO.new
    cmd = <<-CMD
      $(npm bin)/browserify #{@browserify_opts} -- -
    CMD
    stdout_handler = proc {|d| out_buf << d }
    stderr_handler = @suppress_stderr ?
                       proc {|d| } :
                       proc {|d| STDERR.print d}
    status = @nvm.run(
      cmd,
      stdin: source,
      node_ver: @node_ver,
      env: @env,
      stdout_handler: stdout_handler,
      stderr_handler: stderr_handler
    ).value
    raise "non-zero exit status: #{status.to_i}" unless status.success?

    return out_buf.string
  end

  def self.compile(
        source, browserify_opts: "", node_ver: nil, env: {},
        nvm_dir: DEFAULT_NVM_DIR, suppress_stderr: false)
    new(
      browserify_opts: browserify_opts,
      node_ver: node_ver,
      env: env,
      nvm_dir: nvm_dir,
      suppress_stderr: suppress_stderr
    ).compile(source)
  end
end


text:
namespace jwt {

class Base64
{
public:
    static std::string decode(const std::string& data);
    static std::string encode(const std::string& data);
};

}

#endif // JWT_BASE64_H


text:
    /**
     *  Ignores all elements in an observable sequence leaving only the termination messages.
     * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
     */
    observableProto.ignoreElements = function () {
        var source = this;
        return new AnonymousObservable(function (observer) {
            return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
        });
    };


text:
import time
import logging

logging.basicConfig()

import madmin_db

i = 0
while True:
    try:
        q = madmin_db.Query("SELECT value FROM test")
        q.run()
        print "Succes", i
    except madmin_db.DatabaseError, e:
        print "Fail", i
    i = i + 1
    time.sleep(1)


text:
package org.camunda.bpm.container.impl.threading.ra.outbound;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.resource.NotSupportedException;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.LocalTransaction;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionMetaData;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;

import org.camunda.bpm.container.ExecutorService;
import org.camunda.bpm.container.impl.threading.ra.JcaExecutorServiceConnector;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;

/**
 *
 * @author Daniel Meyer
 *
 */
public class JcaExecutorServiceManagedConnection implements ManagedConnection {

  protected PrintWriter logwriter;

  protected JcaExecutorServiceManagedConnectionFactory mcf;
  protected List<ConnectionEventListener> listeners;
  protected JcaExecutorServiceConnectionImpl connection;

  protected ExecutorService delegate;

  public JcaExecutorServiceManagedConnection() {
  }

  public JcaExecutorServiceManagedConnection(JcaExecutorServiceManagedConnectionFactory mcf) {
    this.mcf = mcf;
    this.logwriter = null;
    this.listeners = Collections.synchronizedList(new ArrayList<ConnectionEventListener>(1));
    this.connection = null;
    JcaExecutorServiceConnector ra = (JcaExecutorServiceConnector) mcf.getResourceAdapter();
    delegate = (ExecutorService) ra.getExecutorServiceWrapper().getExecutorService();
  }

  public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
    connection = new JcaExecutorServiceConnectionImpl(this, mcf);
    return connection;
  }

  public void associateConnection(Object connection) throws ResourceException {
    if (connection == null) {
      throw new ResourceException("Null connection handle");
    }
    if (!(connection instanceof JcaExecutorServiceConnectionImpl)) {
      throw new ResourceException("Wrong connection handle");
    }
    this.connection = (JcaExecutorServiceConnectionImpl) connection;
  }

  public void cleanup() throws ResourceException {
    // no-op
  }

  public void destroy() throws ResourceException {
    // no-op
  }

  public void addConnectionEventListener(ConnectionEventListener listener) {
    if (listener == null) {
      throw new IllegalArgumentException("Listener is null");
    }
    listeners.add(listener);
  }

  public void removeConnectionEventListener(ConnectionEventListener listener) {
    if (listener == null) {
      throw new IllegalArgumentException("Listener is null");
    }
    listeners.remove(listener);
  }

  void closeHandle(JcaExecutorServiceConnection handle) {
    ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED);
    event.setConnectionHandle(handle);
    for (ConnectionEventListener cel : listeners) {
      cel.connectionClosed(event);
    }

  }
  public PrintWriter getLogWriter() throws ResourceException {
    return logwriter;
  }

  public void setLogWriter(PrintWriter out) throws ResourceException {
    logwriter = out;
  }

  public LocalTransaction getLocalTransaction() throws ResourceException {
    throw new NotSupportedException("LocalTransaction not supported");
  }

  public XAResource getXAResource() throws ResourceException {
    throw new NotSupportedException("GetXAResource not supported not supported");
  }

  public ManagedConnectionMetaData getMetaData() throws ResourceException {
    return null;
  }

  // delegate methods /////////////////////////////////////////

  public boolean schedule(Runnable runnable, boolean isLongRunning) {
    return delegate.schedule(runnable, isLongRunning);
  }

  public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
    return delegate.getExecuteJobsRunnable(jobIds, processEngine);
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ApplicationDescription (AWS SDK for Java - 1.4.7)
</TITLE>

<META NAME="date" CONTENT="2013-06-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../JavaDoc.css" TITLE="Style">

      Overview
      Package
    Class
      Index
      Help

Did this page help you?
   Yes   No   Tell us about it...

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.amazonaws.services.elasticbeanstalk.model

Class ApplicationDescription

java.lang.Object
  com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription

All Implemented Interfaces:
Serializable

public class ApplicationDescription
extends Object
implements Serializable

 Describes the properties of an application.

See Also:
Serialized Form

Constructor Summary

ApplicationDescription()

          Default constructor for a new ApplicationDescription object.

Method Summary

 boolean
equals(Object obj)

 String
getApplicationName()

          The name of the application.

 List<String>
getConfigurationTemplates()

          The names of the configuration templates associated with this
 application.

 Date
getDateCreated()

          The date when the application was created.

 Date
getDateUpdated()

          The date when the application was last modified.

 String
getDescription()

          User-defined description of the application.

 List<String>
getVersions()

          The names of the versions for this application.

 int
hashCode()

 void
setApplicationName(String applicationName)

          The name of the application.

 void
setConfigurationTemplates(Collection<String> configurationTemplates)

          The names of the configuration templates associated with this
 application.

 void
setDateCreated(Date dateCreated)

          The date when the application was created.

 void
setDateUpdated(Date dateUpdated)

          The date when the application was last modified.

 void
setDescription(String description)

          User-defined description of the application.

 void
setVersions(Collection<String> versions)

          The names of the versions for this application.

 String
toString()

          Returns a string representation of this object; useful for testing and
 debugging.

 ApplicationDescription
withApplicationName(String applicationName)

          The name of the application.

 ApplicationDescription
withConfigurationTemplates(Collection<String> configurationTemplates)

          The names of the configuration templates associated with this
 application.

 ApplicationDescription
withConfigurationTemplates(String... configurationTemplates)

          The names of the configuration templates associated with this
 application.

 ApplicationDescription
withDateCreated(Date dateCreated)

          The date when the application was created.

 ApplicationDescription
withDateUpdated(Date dateUpdated)

          The date when the application was last modified.

 ApplicationDescription
withDescription(String description)

          User-defined description of the application.

 ApplicationDescription
withVersions(Collection<String> versions)

          The names of the versions for this application.

 ApplicationDescription
withVersions(String... versions)

          The names of the versions for this application.

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

ApplicationDescription

public ApplicationDescription()

Default constructor for a new ApplicationDescription object.  Callers should use the
 setter or fluent setter (with...) methods to initialize this object after creating it.

Method Detail

getApplicationName

public String getApplicationName()

The name of the application.

 Constraints:

 Length: 1 - 100

Returns:
The name of the application.

setApplicationName

public void setApplicationName(String applicationName)

The name of the application.

 Constraints:

 Length: 1 - 100

Parameters:
applicationName - The name of the application.

withApplicationName

public ApplicationDescription withApplicationName(String applicationName)

The name of the application.

 Returns a reference to this object so that method calls can be chained together.

 Constraints:

 Length: 1 - 100

Parameters:
applicationName - The name of the application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

getDescription

public String getDescription()

User-defined description of the application.

 Constraints:

 Length: 0 - 200

Returns:
User-defined description of the application.

setDescription

public void setDescription(String description)

User-defined description of the application.

 Constraints:

 Length: 0 - 200

Parameters:
description - User-defined description of the application.

withDescription

public ApplicationDescription withDescription(String description)

User-defined description of the application.

 Returns a reference to this object so that method calls can be chained together.

 Constraints:

 Length: 0 - 200

Parameters:
description - User-defined description of the application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

getDateCreated

public Date getDateCreated()

The date when the application was created.

Returns:
The date when the application was created.

setDateCreated

public void setDateCreated(Date dateCreated)

The date when the application was created.

Parameters:
dateCreated - The date when the application was created.

withDateCreated

public ApplicationDescription withDateCreated(Date dateCreated)

The date when the application was created.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
dateCreated - The date when the application was created.

Returns:
A reference to this updated object so that method calls can be chained
         together.

getDateUpdated

public Date getDateUpdated()

The date when the application was last modified.

Returns:
The date when the application was last modified.

setDateUpdated

public void setDateUpdated(Date dateUpdated)

The date when the application was last modified.

Parameters:
dateUpdated - The date when the application was last modified.

withDateUpdated

public ApplicationDescription withDateUpdated(Date dateUpdated)

The date when the application was last modified.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
dateUpdated - The date when the application was last modified.

Returns:
A reference to this updated object so that method calls can be chained
         together.

getVersions

public List<String> getVersions()

The names of the versions for this application.

Returns:
The names of the versions for this application.

setVersions

public void setVersions(Collection<String> versions)

The names of the versions for this application.

Parameters:
versions - The names of the versions for this application.

withVersions

public ApplicationDescription withVersions(String... versions)

The names of the versions for this application.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
versions - The names of the versions for this application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

withVersions

public ApplicationDescription withVersions(Collection<String> versions)

The names of the versions for this application.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
versions - The names of the versions for this application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

getConfigurationTemplates

public List<String> getConfigurationTemplates()

The names of the configuration templates associated with this
 application.

Returns:
The names of the configuration templates associated with this
         application.

setConfigurationTemplates

public void setConfigurationTemplates(Collection<String> configurationTemplates)

The names of the configuration templates associated with this
 application.

Parameters:
configurationTemplates - The names of the configuration templates associated with this
         application.

withConfigurationTemplates

public ApplicationDescription withConfigurationTemplates(String... configurationTemplates)

The names of the configuration templates associated with this
 application.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
configurationTemplates - The names of the configuration templates associated with this
         application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

withConfigurationTemplates

public ApplicationDescription withConfigurationTemplates(Collection<String> configurationTemplates)

The names of the configuration templates associated with this
 application.

 Returns a reference to this object so that method calls can be chained together.

Parameters:
configurationTemplates - The names of the configuration templates associated with this
         application.

Returns:
A reference to this updated object so that method calls can be chained
         together.

toString

public String toString()

Returns a string representation of this object; useful for testing and
 debugging.

Overrides:
toString in class Object

Returns:
A string representation of this object.
See Also:
Object.toString()

hashCode

public int hashCode()

Overrides:
hashCode in class Object

equals

public boolean equals(Object obj)

Overrides:
equals in class Object

      Overview
      Package
    Class
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright © 2010 Amazon Web Services, Inc. All Rights Reserved.


text:
<?php

namespace React\Promise\PromiseTest;

use React\Promise;
use React\Promise\Deferred;

trait RejectTestTrait
{
    /**
     * @return \React\Promise\PromiseAdapter\PromiseAdapterInterface
     */
    abstract public function getPromiseTestAdapter(callable $canceller = null);

    /** @test */
    public function rejectShouldRejectWithAnImmediateValue()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->then($this->expectCallableNever(), $mock);

        $adapter->reject(1);
    }

    /** @test */
    public function rejectShouldRejectWithFulfilledPromise()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->then($this->expectCallableNever(), $mock);

        $adapter->reject(Promise\resolve(1));
    }

    /** @test */
    public function rejectShouldRejectWithRejectedPromise()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->then($this->expectCallableNever(), $mock);

        $adapter->reject(Promise\reject(1));
    }

    /** @test */
    public function rejectShouldForwardReasonWhenCallbackIsNull()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->then(
                $this->expectCallableNever()
            )
            ->then(
                $this->expectCallableNever(),
                $mock
            );

        $adapter->reject(1);
    }

    /** @test */
    public function rejectShouldMakePromiseImmutable()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->then(null, function ($value) use ($adapter) {
                $adapter->reject(3);

                return Promise\reject($value);
            })
            ->then(
                $this->expectCallableNever(),
                $mock
            );

        $adapter->reject(1);
        $adapter->reject(2);
    }

    /** @test */
    public function notifyShouldInvokeOtherwiseHandler()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $adapter->promise()
            ->otherwise($mock);

        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldInvokeRejectionHandler()
    {
        $adapter = $this->getPromiseTestAdapter();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo(1));

        $this->assertNull($adapter->promise()->done(null, $mock));
        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldThrowExceptionThrownByRejectionHandler()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('\Exception', 'UnhandledRejectionException');

        $this->assertNull($adapter->promise()->done(null, function () {
            throw new \Exception('UnhandledRejectionException');
        }));
        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldThrowUnhandledRejectionExceptionWhenRejectedWithNonException()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('React\\Promise\\UnhandledRejectionException');

        $this->assertNull($adapter->promise()->done());
        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldThrowUnhandledRejectionExceptionWhenRejectionHandlerRejects()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('React\\Promise\\UnhandledRejectionException');

        $this->assertNull($adapter->promise()->done(null, function () {
            return \React\Promise\reject();
        }));
        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldThrowRejectionExceptionWhenRejectionHandlerRejectsWithException()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('\Exception', 'UnhandledRejectionException');

        $this->assertNull($adapter->promise()->done(null, function () {
            return \React\Promise\reject(new \Exception('UnhandledRejectionException'));
        }));
        $adapter->reject(1);
    }

    /** @test */
    public function doneShouldThrowUnhandledRejectionExceptionWhenRejectionHandlerRetunsPendingPromiseWhichRejectsLater()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('React\\Promise\\UnhandledRejectionException');

        $d = new Deferred();
        $promise = $d->promise();

        $this->assertNull($adapter->promise()->done(null, function () use ($promise) {
            return $promise;
        }));
        $adapter->reject(1);
        $d->reject(1);
    }

    /** @test */
    public function doneShouldThrowExceptionProvidedAsRejectionValue()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->setExpectedException('\Exception', 'UnhandledRejectionException');

        $this->assertNull($adapter->promise()->done());
        $adapter->reject(new \Exception('UnhandledRejectionException'));
    }

    /** @test */
    public function doneShouldThrowWithDeepNestingPromiseChains()
    {
        $this->setExpectedException('\Exception', 'UnhandledRejectionException');

        $exception = new \Exception('UnhandledRejectionException');

        $d = new Deferred();

        $result = \React\Promise\resolve(\React\Promise\resolve($d->promise()->then(function () use ($exception) {
            $d = new Deferred();
            $d->resolve();

            return \React\Promise\resolve($d->promise()->then(function () {}))->then(
                function () use ($exception) {
                    throw $exception;
                }
            );
        })));

        $result->done();

        $d->resolve();
    }

    /** @test */
    public function doneShouldRecoverWhenRejectionHandlerCatchesException()
    {
        $adapter = $this->getPromiseTestAdapter();

        $this->assertNull($adapter->promise()->done(null, function (\Exception $e) {

        }));
        $adapter->reject(new \Exception('UnhandledRejectionException'));
    }

    /** @test */
    public function alwaysShouldNotSuppressRejection()
    {
        $adapter = $this->getPromiseTestAdapter();

        $exception = new \Exception();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo($exception));

        $adapter->promise()
            ->always(function () {})
            ->then(null, $mock);

        $adapter->reject($exception);
    }

    /** @test */
    public function alwaysShouldNotSuppressRejectionWhenHandlerReturnsANonPromise()
    {
        $adapter = $this->getPromiseTestAdapter();

        $exception = new \Exception();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo($exception));

        $adapter->promise()
            ->always(function () {
                return 1;
            })
            ->then(null, $mock);

        $adapter->reject($exception);
    }

    /** @test */
    public function alwaysShouldNotSuppressRejectionWhenHandlerReturnsAPromise()
    {
        $adapter = $this->getPromiseTestAdapter();

        $exception = new \Exception();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo($exception));

        $adapter->promise()
            ->always(function () {
                return \React\Promise\resolve(1);
            })
            ->then(null, $mock);

        $adapter->reject($exception);
    }

    /** @test */
    public function alwaysShouldRejectWhenHandlerThrowsForRejection()
    {
        $adapter = $this->getPromiseTestAdapter();

        $exception = new \Exception();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo($exception));

        $adapter->promise()
            ->always(function () use ($exception) {
                throw $exception;
            })
            ->then(null, $mock);

        $adapter->reject($exception);
    }

    /** @test */
    public function alwaysShouldRejectWhenHandlerRejectsForRejection()
    {
        $adapter = $this->getPromiseTestAdapter();

        $exception = new \Exception();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($this->identicalTo($exception));

        $adapter->promise()
            ->always(function () use ($exception) {
                return \React\Promise\reject($exception);
            })
            ->then(null, $mock);

        $adapter->reject($exception);
    }
}


text:
    The protocol to use to communicate with CAS.
    Certain features, such as attributes, may not be available with all protocols.

    If unsure, select CAS 3.0. For more information, see the
    CAS Protocols documentation.
    Only certain protocols are supported by this plugin.