text:
package jo.vecmath;

import jo.vecmath.Tuple3d;
import jo.vecmath.Tuple4d;
import jo.vecmath.Tuple4f;
import jo.vecmath.Vector4f;

/**
 * A 4-element vector represented by double-precision floating point
 * x,y,z,w coordinates.
 *
 */
 public class Vector4d extends Tuple4d implements java.io.Serializable {

    // Compatible with 1.1
    static final long serialVersionUID = 3938123424117448700L;

    /**
     * Constructs and initializes a Vector4d from the specified xyzw coordinates.
     * @param x the x coordinate
     * @param y the y coordinate
     * @param z the z coordinate
     * @param w the w coordinate
     */
     public Vector4d(double x, double y, double z, double w)
    {
        super(x,y,z,w);
    }

    /**
     * Constructs and initializes a Vector4d from the coordinates contained
     * in the array.
     * @param v the array of length 4 containing xyzw in order
     */
     public Vector4d(double[] v)
    {
        super(v);
    }

    /**
     * Constructs and initializes a Vector4d from the specified Vector4d.
     * @param v1 the Vector4d containing the initialization x y z w data
     */
     public Vector4d(Vector4d v1)
    {
         super(v1);
    }

    /**
     * Constructs and initializes a Vector4d from the specified Vector4f.
     * @param v1 the Vector4f containing the initialization x y z w data
     */
     public Vector4d(Vector4f v1)
    {
       super(v1);
    }

    /**
     * Constructs and initializes a Vector4d from the specified Tuple4f.
     * @param t1 the Tuple4f containing the initialization x y z w data
     */
     public Vector4d(Tuple4f t1)
    {
       super(t1);
    }

    /**
     * Constructs and initializes a Vector4d from the specified Tuple4d.
     * @param t1 the Tuple4d containing the initialization x y z w data
     */
     public Vector4d(Tuple4d t1)
    {
       super(t1);
    }

    /**
     * Constructs and initializes a Vector4d from the specified Tuple3d.
     * The x,y,z components of this vector are set to the corresponding
     * components of tuple t1.  The w component of this vector
     * is set to 0.
     * @param t1 the tuple to be copied
     *
     * @since vecmath 1.2
     */
     public Vector4d(Tuple3d t1) {
      super(t1.x, t1.y, t1.z, 0.0);
    }

    /**
     * Constructs and initializes a Vector4d to (0,0,0,0).
     */
     public Vector4d()
    {
       super();
    }

    /**
     * Sets the x,y,z components of this vector to the corresponding
     * components of tuple t1.  The w component of this vector
     * is set to 0.
     * @param t1 the tuple to be copied
     *
     * @since vecmath 1.2
     */
     public final void set(Tuple3d t1) {
      this.x = t1.x;
      this.y = t1.y;
      this.z = t1.z;
      this.w = 0.0;
    }

    /**
     * Returns the length of this vector.
     * @return the length of this vector
     */
     public final double length()
    {
        return Math.sqrt(this.x*this.x + this.y*this.y +
                              this.z*this.z + this.w*this.w);
    }

    /**
     * Returns the squared length of this vector.
     * @return the squared length of this vector
     */
     public final double lengthSquared()
    {
        return (this.x*this.x + this.y*this.y +
                this.z*this.z + this.w*this.w);
    }

  /**
   * Returns the dot product of this vector and vector v1.
   * @param v1 the other vector
   * @return the dot product of this vector and vector v1
   */
     public final double dot(Vector4d v1)
    {
      return (this.x*v1.x + this.y*v1.y + this.z*v1.z + this.w*v1.w);
    }

   /**
     * Sets the value of this vector to the normalization of vector v1.
     * @param v1 the un-normalized vector
     */
     public final void normalize(Vector4d v1)
    {
        double norm;

        norm = 1.0/Math.sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z + v1.w*v1.w);
        this.x = v1.x*norm;
        this.y = v1.y*norm;
        this.z = v1.z*norm;
        this.w = v1.w*norm;
    }

    /**
     * Normalizes this vector in place.
     */
     public final void normalize()
    {
        double norm;

        norm = 1.0/Math.sqrt(this.x*this.x + this.y*this.y +
                              this.z*this.z + this.w*this.w);
        this.x *= norm;
        this.y *= norm;
        this.z *= norm;
        this.w *= norm;
    }

  /**
    *   Returns the (4-space) angle in radians between this vector and
    *   the vector parameter; the return value is constrained to the
    *   range [0,PI].
    *   @param v1    the other vector
    *   @return   the angle in radians in the range [0,PI]
    */
    public final double angle(Vector4d v1)
   {
      double vDot = this.dot(v1) / ( this.length()*v1.length() );
      if( vDot < -1.0) vDot = -1.0;
      if( vDot >  1.0) vDot =  1.0;
      return((double) (Math.acos( vDot )));
   }

}


text:
<documentation title="Inline Comments">
    <standard>
        <![CDATA[
    Perl-style # comments are not allowed.
    ]]>
    </standard>
    <code_comparison>

            <![CDATA[
// A comment.
        ]]>

            <![CDATA[
# A comment.
        ]]>

    </code_comparison>
</documentation>

redpajama_set_name: RedPajamaGithub


text:
package de.uniulm.omi.cloudiator.sword.drivers.openstack4j.internal;

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

import com.google.inject.Inject;
import com.google.inject.Provider;
import de.uniulm.omi.cloudiator.sword.domain.Location;
import de.uniulm.omi.cloudiator.util.OneWayConverter;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.openstack4j.api.OSClient;
import org.openstack4j.api.OSClient.OSClientV3;
import org.openstack4j.model.identity.v3.Region;

/**
 * Created by daniel on 18.11.16.
 */
public class OsClientV3RegionSupplier implements RegionSupplier {

  private final Provider<OSClient> osClient;
  private final OneWayConverter<String, Location> regionConverter;

  @Inject
  public OsClientV3RegionSupplier(Provider<OSClient> osClient,
      OneWayConverter<String, Location> regionConverter) {
    checkNotNull(regionConverter, "regionConverter is null.");
    this.regionConverter = regionConverter;
    checkNotNull(osClient, "osClient is null");
    checkState(osClient.get() instanceof OSClient.OSClientV3,
        "Illegal version of OSClient supplied.");
    this.osClient = osClient;
  }

  @Override
  public Set<Location> get() {
    return ((OSClientV3) osClient.get()).identity().regions().list().stream()
        .map((Function<Region, String>) Region::getId).map(regionConverter)
        .collect(Collectors.toSet());
  }
}


text:
package cmd

import "fmt"

const lpmWarningMessage = `
Note that for Linux kernel versions between 4.11 and 4.15 inclusive, the native
LPM map type used for implementing this feature does not provide the ability to
walk / dump the entries, so on these kernel versions this tool will never
return any entries, even if entries exist in the map. `

const suggestionTemplate = `You may instead run:
    cilium map get %s
`

func lpmKernelVersionWarning(mapName string) string {
	if mapName == "" {
		return lpmWarningMessage
	}

	return lpmWarningMessage + fmt.Sprintf(suggestionTemplate, mapName)
}


text:
class Automoc4 < Formula
  desc "Tool to add rules for generating Qt moc files"
  homepage "https://techbase.kde.org/Development/Tools/Automoc4"
  url "http://download.kde.org/stable/automoc4/0.9.88/automoc4-0.9.88.tar.bz2"
  sha256 "234116f4c05ae21d828594d652b4c4a052ef75727e2d8a4f3a4fb605de9e4c49"

  bottle do
    sha256 "3f9efbccd2e54425aefa23beb359a84790a702fbc83e7950a709b3a56c818898" => :el_capitan
    sha256 "db251dc1e60d49c6ba011c28cf4d08f82468af379195c66fc5e7777b6e9fc4fd" => :yosemite
    sha256 "86fc5bddf7faf6f2897fc626903f0d927c8c9094e41c3d238c4b3e718acf4f47" => :mavericks
  end

  depends_on "cmake" => :build
  depends_on "qt"

  # Patch needed to find Qt in Homebrew upstreamed but upstream version
  # does not apply. Won't be needed for next version.
  # https://projects.kde.org/projects/kdesupport/automoc/repository/revisions/6b9597ff
  patch :p0, :DATA

  def install
    system "cmake", ".", *std_cmake_args
    system "make", "install"
  end
end

__END__
--- kde4automoc.cpp.old	2009-01-22 18:50:09.000000000 +0000
+++ kde4automoc.cpp	2010-03-15 22:26:03.000000000 +0000
@@ -175,16 +175,22 @@
     dotFilesCheck(line == "MOC_INCLUDES:\n");
     line = dotFiles.readLine().trimmed();
     const QStringList &incPaths = QString::fromUtf8(line).split(';', QString::SkipEmptyParts);
+    QSet<QString> frameworkPaths;
     foreach (const QString &path, incPaths) {
         Q_ASSERT(!path.isEmpty());
         mocIncludes << "-I" + path;
+        if (path.endsWith(".framework/Headers")) {
+            QDir framework(path);
+            // Go up twice to get to the framework root
+            framework.cdUp();
+            framework.cdUp();
+            frameworkPaths << framework.path();
+        }
     }

-    // on the Mac, add -F always, otherwise headers in the frameworks won't be found
-    // is it necessary to do this only optionally ? Alex
-#ifdef Q_OS_MAC
-    mocIncludes << "-F/Library/Frameworks";
-#endif
+    foreach (const QString &path, frameworkPaths) {
+        mocIncludes << "-F" << path;
+    }

     line = dotFiles.readLine();
     dotFilesCheck(line == "CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE:\n");


text:
module RuboCop
  module Cop
    module Rails
      # This cop checks for consistent uses of `request.referer` or
      # `request.referrer`, depending on the cop's configuration.
      #
      # @example
      #   # EnforcedStyle: referer
      #   # bad
      #   request.referrer
      #
      #   # good
      #   request.referer
      #
      #   # EnforcedStyle: referrer
      #   # bad
      #   request.referer
      #
      #   # good
      #   request.referrer
      class RequestReferer < Cop
        include ConfigurableEnforcedStyle

        MSG = 'Use `request.%s` instead of `request.%s`.'.freeze

        def_node_matcher :referer?, <<-PATTERN
          (send (send nil :request) {:referer :referrer})
        PATTERN

        def on_send(node)
          referer?(node) do
            return unless node.method?(wrong_method_name)

            add_offense(node.source_range, node.source_range, message)
          end
        end

        def autocorrect(node)
          ->(corrector) { corrector.replace(node, "request.#{style}") }
        end

        private

        def message
          format(MSG, style, wrong_method_name)
        end

        def wrong_method_name
          style == :referer ? :referrer : :referer
        end
      end
    end
  end
end


text:
import React, { PropTypes } from 'react'
import { Field, reduxForm } from 'redux-form'
import { Button, Form, FormGroup, Label, Container, Row, Col, Alert } from 'reactstrap'

const Login = (props) => {
  return (
    <Container>
      <Row>
        <Col sm={{ size: 6, push: 2, pull: 2, offset: 1 }}>
          <Form onSubmit={props.handleSubmit}>
            <FormGroup>
              <Label htmlFor='userName'>Username: </Label>
              <Field name='username' component='input' type='text' />
            </FormGroup>
            <FormGroup>
              <label htmlFor='password'>password: </label>
              <Field name='password' component='input' type='password' />
            </FormGroup>
            <Button type='submit'>Submit</Button>
          </Form>
        </Col>
      </Row>
      {props.loginError && <Alert color='danger'>{props.loginError}</Alert>}
    </Container>
  )
}

Login.propTypes = {
  requestLogin: PropTypes.func,
  handleSubmit: PropTypes.func.isRequired,
  loginError: PropTypes.string
}

const LoginForm = reduxForm({
  form: 'login'
})(Login)

export default LoginForm


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.netflix.astyanax.connectionpool.exceptions.ConnectionException (astyanax 1.0.3 API)
</TITLE>

<META NAME="date" CONTENT="2012-05-24">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.netflix.astyanax.connectionpool.exceptions.ConnectionException

Packages that use ConnectionException

com.netflix.astyanax

com.netflix.astyanax.connectionpool

com.netflix.astyanax.connectionpool.exceptions

com.netflix.astyanax.connectionpool.impl

com.netflix.astyanax.query

com.netflix.astyanax.recipes

com.netflix.astyanax.shallows

com.netflix.astyanax.thrift

com.netflix.astyanax.util

Uses of ConnectionException in com.netflix.astyanax

Methods in com.netflix.astyanax with parameters of type ConnectionException

 boolean
RowCallback.failure(ConnectionException e)

          Notification of an error calling cassandra.

 void
CassandraOperationTracer.failure(ConnectionException e)

 boolean
ExceptionCallback.onException(ConnectionException e)

Methods in com.netflix.astyanax that throw ConnectionException

 String
Cluster.addColumnFamily(ColumnFamilyDefinition def)

          Add a column family to an existing keyspace

 String
Cluster.addKeyspace(KeyspaceDefinition def)

          Add a new keyspace to the cluster.

 String
Cluster.describeClusterName()

          The cluster name is completely arbitrary

 KeyspaceDefinition
Keyspace.describeKeyspace()

          Return a complete description of the keyspace and its column families

 KeyspaceDefinition
Cluster.describeKeyspace(String ksName)

          Describe a single keyspace

 List<KeyspaceDefinition>
Cluster.describeKeyspaces()

          Return details about all keyspaces in the cluster

 String
Cluster.describePartitioner()

          Describe the partitioner used by the cluster

 List<TokenRange>
Keyspace.describeRing()

          Get a list of all tokens and their endpoints

 Map<String,List<String>>
Cluster.describeSchemaVersions()

 String
Cluster.describeSnitch()

          Describe the snitch name used on the cluster

 String
Cluster.dropColumnFamily(String keyspaceName,
                 String columnFamilyName)

          Delete the column family from the keyspace

 String
Cluster.dropKeyspace(String keyspaceName)

          Delete a keyspace from the cluster

 OperationResult<R>
Execution.execute()

          Block while executing the operations

 Future<OperationResult<R>>
Execution.executeAsync()

          Return a future to the operation.

 SerializerPackage
Keyspace.getSerializerPackage(String cfName,
                     boolean ignoreErrors)

          Return the serializer package for a specific column family.

 String
Cluster.getVersion()

          Return version of cassandra running on the cluster

 OperationResult<Void>
Keyspace.testOperation(Operation<?,?> operation)

          This method is used for testing purposes only.

 OperationResult<Void>
Keyspace.testOperation(Operation<?,?> operation,
              RetryPolicy retry)

          This method is used for testing purposes only.

<K,C> OperationResult<Void>

Keyspace.truncateColumnFamily(ColumnFamily<K,C> columnFamily)

          Delete all rows in a column family

 String
Cluster.updateColumnFamily(ColumnFamilyDefinition def)

          Update an existing column family

 String
Cluster.updateKeyspace(KeyspaceDefinition def)

          Update a new keyspace in the cluster.

Uses of ConnectionException in com.netflix.astyanax.connectionpool

Methods in com.netflix.astyanax.connectionpool that return ConnectionException

 ConnectionException
Connection.getLastException()

          Get the last exception that caused the connection to be closed

Methods in com.netflix.astyanax.connectionpool with parameters of type ConnectionException

 void
Connection.AsyncOpenCallback.failure(Connection<CL> conn,
        ConnectionException e)

 void
HostConnectionPool.markAsDown(ConnectionException reason)

          Shut down the host so no more connections may be created when
 borrowConnections is called and connections will be terminated when
 returnConnection is called.

Methods in com.netflix.astyanax.connectionpool that throw ConnectionException

 Connection<CL>
HostConnectionPool.borrowConnection(int timeout)

          Borrow a connection from the host.

 R
Operation.execute(CL client)

          Execute the operation on the client object and return the results

<R> OperationResult<R>

Connection.execute(Operation<CL,R> op)

          Execute an operation on the connection and return a result

<R> OperationResult<R>

ConnectionPool.executeWithFailover(Operation<CL,R> op,
                    RetryPolicy retry)

          Execute an operation with failover within the context of the connection
 pool.

 int
HostConnectionPool.growConnections(int numConnections)

          Create numConnections new connections and add them to the

 void
Connection.open()

          Open a new connection

 Connection<CL>
HostConnectionPool.openConnection()

          This open is different from borrowConnection in that it actually creates
 a new connection without waiting for one that may be idle.

 OperationResult<R>
ExecuteWithFailover.tryOperation(Operation<CL,R> operation)

Uses of ConnectionException in com.netflix.astyanax.connectionpool.exceptions

Subclasses of ConnectionException in com.netflix.astyanax.connectionpool.exceptions

 class
AuthenticationException

 class
BadConfigurationException

 class
BadRequestException

 class
ConnectionAbortedException

 class
HostDownException

          No more connections may be opened on a host and no timeout was specified.

 class
MaxConnsPerHostReachedException

          No more connections may be opened on a host and no timeout was specified.

 class
NoAvailableHostsException

 class
NotFoundException

 class
OperationException

          Application exception for an operation executed within the context of the
 connection pool.

 class
OperationTimeoutException

 class
PoolTimeoutException

 class
SchemaDisagreementException

 class
ThriftStateException

 class
ThrottledException

 class
TimeoutException

 class
TokenRangeOfflineException

 class
TransportException

 class
UnknownException

 class
WalException

Methods in com.netflix.astyanax.connectionpool.exceptions that return ConnectionException

 ConnectionException
ConnectionException.setAttempt(int attemptCount)

 ConnectionException
ConnectionException.setHost(Host host)

 ConnectionException
ConnectionException.setLatency(long latency)

 ConnectionException
ConnectionException.setLatencyWithPool(long latency)

Uses of ConnectionException in com.netflix.astyanax.connectionpool.impl

Methods in com.netflix.astyanax.connectionpool.impl with parameters of type ConnectionException

 void
AbstractExecuteWithFailoverImpl.informException(ConnectionException connectionException)

 void
SimpleHostConnectionPool.markAsDown(ConnectionException reason)

          Mark the host as down.

Methods in com.netflix.astyanax.connectionpool.impl that throw ConnectionException

 Connection<CL>
SimpleHostConnectionPool.borrowConnection(int timeout)

          Create a connection as long the max hasn't been reached

 Connection<CL>
RoundRobinExecuteWithFailover.borrowConnection(Operation<CL,R> operation)

abstract  Connection<CL>
AbstractExecuteWithFailoverImpl.borrowConnection(Operation<CL,R> operation)

<R> OperationResult<R>

AbstractHostPartitionConnectionPool.executeWithFailover(Operation<CL,R> op,
                    RetryPolicy retry)

 OperationResult<R>
AbstractExecutionImpl.executeWithRetry(RetryPolicy retry)

 int
SimpleHostConnectionPool.growConnections(int numConnections)

 void
AbstractExecuteWithFailoverImpl.informException(ConnectionException connectionException)

<R> ExecuteWithFailover<CL,R>

TokenAwareConnectionPoolImpl.newExecuteWithFailover(Operation<CL,R> op)

<R> ExecuteWithFailover<CL,R>

RoundRobinConnectionPoolImpl.newExecuteWithFailover(Operation<CL,R> operation)

<R> ExecuteWithFailover<CL,R>

BagOfConnectionsConnectionPoolImpl.newExecuteWithFailover(Operation<CL,R> op)

protected abstract

<R> ExecuteWithFailover<CL,R>

AbstractHostPartitionConnectionPool.newExecuteWithFailover(Operation<CL,R> op)

          Return a new failover context.

 Connection<CL>
SimpleHostConnectionPool.openConnection()

          Open a new connection synchronously

 OperationResult<R>
AbstractExecuteWithFailoverImpl.tryOperation(Operation<CL,R> operation)

Constructors in com.netflix.astyanax.connectionpool.impl that throw ConnectionException

AbstractExecuteWithFailoverImpl(ConnectionPoolConfiguration config,
                                ConnectionPoolMonitor monitor)

RoundRobinExecuteWithFailover(ConnectionPoolConfiguration config,
                              ConnectionPoolMonitor monitor,
                              List<HostConnectionPool<CL>> pools,
                              int index)

Uses of ConnectionException in com.netflix.astyanax.query

Methods in com.netflix.astyanax.query that throw ConnectionException

 void
AllRowsQuery.executeWithCallback(RowCallback<K,C> callback)

          Execute the operation in a separate thread for each token range and
 provide the results in a callback.

Uses of ConnectionException in com.netflix.astyanax.recipes

Methods in com.netflix.astyanax.recipes that throw ConnectionException

 String
UniquenessConstraintWithPrefix.isUnique(K key)

          Deprecated.

 C
UniquenessConstraint.isUnique(K key)

          Deprecated.

Uses of ConnectionException in com.netflix.astyanax.shallows

Methods in com.netflix.astyanax.shallows with parameters of type ConnectionException

 void
EmptyKeyspaceTracer.failure(ConnectionException e)

Uses of ConnectionException in com.netflix.astyanax.thrift

Methods in com.netflix.astyanax.thrift that return ConnectionException

static ConnectionException
ThriftConverter.ToConnectionPoolException(Exception e)

          Convert from Thrift exceptions to an internal ConnectionPoolException

Methods in com.netflix.astyanax.thrift that throw ConnectionException

 String
ThriftClusterImpl.addColumnFamily(ColumnFamilyDefinition def)

 String
ThriftClusterImpl.addKeyspace(KeyspaceDefinition def)

 String
ThriftClusterImpl.describeClusterName()

 KeyspaceDefinition
ThriftKeyspaceImpl.describeKeyspace()

 KeyspaceDefinition
ThriftClusterImpl.describeKeyspace(String ksName)

 List<KeyspaceDefinition>
ThriftClusterImpl.describeKeyspaces()

 String
ThriftClusterImpl.describePartitioner()

 List<TokenRange>
ThriftKeyspaceImpl.describeRing()

 Map<String,List<String>>
ThriftClusterImpl.describeSchemaVersions()

 String
ThriftClusterImpl.describeSnitch()

 String
ThriftClusterImpl.dropColumnFamily(String keyspaceName,
                 String columnFamilyName)

 String
ThriftClusterImpl.dropKeyspace(String keyspaceName)

 R
AbstractOperationImpl.execute(org.apache.cassandra.thrift.Cassandra.Client client)

 SerializerPackage
ThriftKeyspaceImpl.getSerializerPackage(String cfName,
                     boolean ignoreErrors)

 String
ThriftClusterImpl.getVersion()

          Get the version from the cluster

 OperationResult<Void>
ThriftKeyspaceImpl.testOperation(Operation<?,?> operation)

 OperationResult<Void>
ThriftKeyspaceImpl.testOperation(Operation<?,?> operation,
              RetryPolicy retry)

<K,C> OperationResult<Void>

ThriftKeyspaceImpl.truncateColumnFamily(ColumnFamily<K,C> columnFamily)

 String
ThriftClusterImpl.updateColumnFamily(ColumnFamilyDefinition def)

 String
ThriftClusterImpl.updateKeyspace(KeyspaceDefinition def)

Uses of ConnectionException in com.netflix.astyanax.util

Methods in com.netflix.astyanax.util that throw ConnectionException

 void
RecordWriter.start()

 void
ColumnarRecordWriter.start()

Constructors in com.netflix.astyanax.util that throw ConnectionException

JsonRowsWriter(PrintWriter out,
               SerializerPackage serializers)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012. All Rights Reserved.


text:
package io.apiman.cli.gatewayapi;

import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.jayway.restassured.RestAssured;
import io.apiman.cli.Cli;
import io.apiman.cli.common.BaseTest;
import io.apiman.cli.common.WaitForHttp;
import io.apiman.cli.util.MappingUtil;
import io.apiman.gateway.engine.beans.Api;
import org.junit.BeforeClass;
import org.junit.ClassRule;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static io.apiman.cli.util.Functions.not;
import static java.util.Optional.ofNullable;

/**
 * This base class waits for an instance of apiman.
 *
 * @author Pete Cornish {@literal <outofcoffee@gmail.com>}
 */
public class GatewayBaseTest {
    /**
     * Basic auth header.
     */
    protected static final String HEADER_AUTHORIZATION = "Authorization";

    /**
     * Gateway API username.
     */
    protected static final String APIMAN_USERNAME = "apimanager";

    /**
     * Gateway API password.
     */
    protected static final String APIMAN_PASSWORD = "apiman123!";

    /**
     * Encoded credentials for Basic auth.
     */
    protected static final String BASIC_AUTH_VALUE = "Basic " + BaseEncoding.base64().encode(
            (APIMAN_USERNAME + ":" + APIMAN_PASSWORD).getBytes());

    /**
     * Wait for apiman to be available.
     * Returns a 200 on 'http://docker.local:8080/apiman-gateway-api/system/status' when ready.
     */
    @ClassRule
    public static WaitForHttp apiman = new WaitForHttp(getApimanHost(), getApimanPort(), "/apiman-gateway-api/system/status")
            .withStatusCode(HttpURLConnection.HTTP_OK)
            .withBasicCredentials(APIMAN_USERNAME, APIMAN_PASSWORD);

    private static String getApimanHost() {
        return ofNullable(System.getProperty("apiman.host"))
                .filter(not(Strings::isNullOrEmpty))
                .orElse("localhost");
    }

    private static int getApimanPort() {
        return ofNullable(System.getProperty("apiman.port"))
                .filter(not(Strings::isNullOrEmpty))
                .map(Integer::parseInt)
                .orElse(8080);
    }

    @BeforeClass
    public static void beforeClass() throws Exception {
        RestAssured.baseURI = getApimanUrl();
    }

    protected static String getApimanUrl() {
        return apiman.getAddress() + "/apiman-gateway-api";
    }

    protected void applyDeclaration(String resourcePath) throws IOException, URISyntaxException {
        Cli.main("gateway",
            "apply",
            "--debug",
            "-f", getResourceAsPath(resourcePath).toAbsolutePath().toString());
    }

    protected Api getApi(String org, String apiId, String version) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream currentOut = System.out;
        System.setOut(new PrintStream(outputStream));

        Cli.main("gateway",
                "api",
                "list",
                "--org", org,
                "--api", apiId,
                "--version", version,
                "--server", getApimanUrl(),
                "--serverUsername", APIMAN_USERNAME,
                "--serverPassword", APIMAN_PASSWORD);

        System.setOut(currentOut);
        //System.out.println(new String(outputStream.toByteArray()));
        return MappingUtil.readJsonValue(new String(outputStream.toByteArray()), Api.class);
    }

    protected <T> T expectJson(String resource, Class<T> klazz) throws URISyntaxException, MalformedURLException { // TODO rename to unmarshall JSON?
        return MappingUtil.readJsonValue(getResourceAsURL(resource), klazz);
    }

    protected URL getResourceAsURL(String resource) throws URISyntaxException, MalformedURLException {
        return BaseTest.class.getResource(resource).toURI().toURL();
    }

    protected Path getResourceAsPath(String resource) throws URISyntaxException, MalformedURLException {
        return Paths.get(getResourceAsURL(resource).toURI());
    }

    protected String getResourceAsString(String resource) throws URISyntaxException, IOException {
        return new String(Files.readAllBytes(Paths.get(getResourceAsURL(resource).toURI())));
    }
}


text:
package com.connectsdk.service.webos.lgcast.common.connection;

import android.os.Handler;
import com.connectsdk.device.ConnectableDevice;
import com.connectsdk.service.WebOSTVService;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.ServiceCommand;
import com.connectsdk.service.command.ServiceCommandError;
import com.connectsdk.service.command.URLServiceSubscription;
import com.connectsdk.service.webos.lgcast.common.utils.JSONObjectEx;
import com.connectsdk.service.webos.lgcast.common.utils.Logger;
import com.connectsdk.service.webos.lgcast.common.utils.ThreadUtil;
import com.connectsdk.service.webos.lgcast.common.utils.ThreadWait;
import org.json.JSONException;
import org.json.JSONObject;

public class LGCastCommand {
    private static final String KEY_SUBSCRIBE = "subscribe";
    private static final String KEY_CMD = "cmd";
    private static final String KEY_SERVICE = "service";
    private static final String KEY_DEVICEINFO = "deviceInfo";
    private static final String KEY_CLIENY_KEY = "clientKey";

    private static final String VAL_CONNECT = "CONNECT";
    private static final String VAL_GET_PARAMETER = "GET_PARAMETER";
    private static final String VAL_SET_PARAMETER = "SET_PARAMETER";
    private static final String VAL_GET_PARAMETER_RESPONSE = "GET_PARAMETER_RESPONSE"; // Remote Camera
    private static final String VAL_SET_PARAMETER_RESPONSE = "SET_PARAMETER_RESPONSE"; // Remote Camera
    private static final String VAL_PLAY = "PLAY";
    private static final String VAL_PAUSE = "PAUSE"; // Remote Camera
    private static final String VAL_KEEPALIVE = "KEEPALIVE";
    private static final String VAL_TEARDOWN = "TEARDOWN";

    private static final String SSAP_SEND_COMMAND = "ssap://com.webos.service.appcasting/sendCommand";
    private static final String SSAP_GET_COMMAND = "ssap://com.webos.service.appcasting/getCommand";
    private static final String SSAP_RECEIVE_UIBC = "ssap://com.webos.service.appcasting/receiveUIBCEvent"; // Screen Mirroring
    private static final String SSAP_GET_POWERSTATE = "ssap://com.webos.service.tvpower/power/getPowerState"; // Screen Mirroring

    private WebOSTVService mWebOSTVService;

    private LGCastCommand() {
    }

    public static LGCastCommand newInstance(ConnectableDevice connectableDevice) {
        WebOSTVService webOsService = (connectableDevice != null) ? (WebOSTVService) connectableDevice.getServiceByName(WebOSTVService.ID) : null;
        if (webOsService == null) return null;

        LGCastCommand wsc = new LGCastCommand();
        wsc.mWebOSTVService = webOsService;
        return wsc;
    }

    public String getClientKey() {
        return mWebOSTVService.getClientKey();
    }

    public void subscribeForServiceCommand(LGCastCommandListener commandListener, Handler responseHandler) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_SUBSCRIBE, true);
        subscribeToService(SSAP_GET_COMMAND, payload.toJSONObject(), commandListener, responseHandler);
    }

    public void subscribeForUserInput(LGCastCommandListener commandListener, Handler responseHandler) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_SUBSCRIBE, true);
        subscribeToService(SSAP_RECEIVE_UIBC, payload.toJSONObject(), commandListener, responseHandler);
    }

    public void subscribeForPowerState(LGCastCommandListener commandListener, Handler responseHandler) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_SUBSCRIBE, true);
        subscribeToService(SSAP_GET_POWERSTATE, payload.toJSONObject(), commandListener, responseHandler);
    }

    public boolean sendConnect(String featureName) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_CONNECT).put(KEY_SERVICE, featureName);;
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    public JSONObject sendGetParameter(String featureName) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_GET_PARAMETER).put(KEY_SERVICE, featureName);
        return sendServiceCommand(payload.toJSONObject());
    }

    public boolean sendSetParameter(String name, JSONObject capability, JSONObject deviceInfo) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_SET_PARAMETER);
        if (name != null && capability != null) payload.put(name, capability);
        if (deviceInfo != null) payload.put(KEY_DEVICEINFO, deviceInfo);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    // Remote Camera
    public JSONObject sendGetParameterResponse(String name, JSONObject parameter) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_GET_PARAMETER_RESPONSE);
        if (name != null && parameter != null) payload.put(name, parameter);
        return sendServiceCommand(payload.toJSONObject());
    }

    // Remote Camera
    public boolean sendSetParameterResponse(String name, JSONObject parameter) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_SET_PARAMETER_RESPONSE);
        if (name != null && parameter != null) payload.put(name, parameter);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    public boolean sendPlay() {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_PLAY);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    // Remote Camera
    public boolean sendStop() {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_PAUSE);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    public boolean sendKeepAlive() {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_KEEPALIVE);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    public boolean sendTeardown(String featureName) {
        JSONObjectEx payload = new JSONObjectEx().put(KEY_CMD, VAL_TEARDOWN).put(KEY_SERVICE, featureName);
        return sendServiceCommand(payload.toJSONObject()) != null;
    }

    private void subscribeToService(String ssapUrl, JSONObject payload, LGCastCommandListener commandListener, Handler responseHandler) {
        if (ThreadUtil.isMainThread() == true) throw new IllegalStateException("Invalid state");
        if (ssapUrl == null || payload == null) return;

        ResponseListener<Object> listener = new ResponseListener<Object>() {
            @Override
            public void onSuccess(Object object) {
                if (commandListener == null) return;
                if (responseHandler != null) responseHandler.post(() -> commandListener.onReceive((JSONObject) object));
                else ThreadUtil.runInBackground(() -> commandListener.onReceive((JSONObject) object));
            }

            @Override
            public void onError(ServiceCommandError error) {
                Logger.error("sendURLServiceSubscription error - " + error.getMessage());
                if (commandListener == null) return;
                ThreadUtil.runInBackground(() -> commandListener.onReceive(null));
            }
        };

        new URLServiceSubscription<ResponseListener<Object>>(mWebOSTVService, ssapUrl, payload, true, listener).send();
    }

    private JSONObject sendServiceCommand(JSONObject payload) {
        if (ThreadUtil.isMainThread() == true) throw new IllegalStateException("Invalid state");
        if (payload == null) return null;
        ThreadWait<JSONObject> threadWait = new ThreadWait<>();

        ResponseListener<Object> listener = new ResponseListener<Object>() {
            @Override
            public void onSuccess(Object object) {
                threadWait.wakeUp((JSONObject) object);
            }

            @Override
            public void onError(ServiceCommandError error) {
                Logger.error("sendServiceCommand error: payload=%s, error=%s", payload.toString(), error.getMessage());
                threadWait.wakeUp(null);
            }
        };

        try {
            payload.put(KEY_CLIENY_KEY, getClientKey());
        } catch (JSONException e) {
            Logger.error(e);
        }

        new ServiceCommand<>(mWebOSTVService, SSAP_SEND_COMMAND, payload, true, listener).send();
        return threadWait.waitFor(3000, null);
    }
}


text:
namespace BigEgg.Tools.ConsoleExtension.Tests.Parameters.Utils
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using BigEgg.Tools.ConsoleExtension.Parameters.Utils;

    [TestClass]
    public class ProgramInfoTest : TestClassBase
    {
        [TestMethod]
        public void DataTest()
        {
            var programInfo = Container.GetExportedValue<IProgramInfo>();
            Assert.IsFalse(string.IsNullOrWhiteSpace(programInfo.Title));
            Assert.IsFalse(string.IsNullOrWhiteSpace(programInfo.Version));
            Assert.IsFalse(string.IsNullOrWhiteSpace(programInfo.Product));
            Assert.IsFalse(string.IsNullOrWhiteSpace(programInfo.Copyright));
        }
    }
}


text:
package parser // CQL

import "github.com/antlr/antlr4/runtime/Go/antlr"

// A complete Visitor for a parse tree produced by CQLParser.
type CQLVisitor interface {
	antlr.ParseTreeVisitor

	// Visit a parse tree produced by CQLParser#cql.
	VisitCql(ctx *CqlContext) interface{}

	// Visit a parse tree produced by CQLParser#create.
	VisitCreate(ctx *CreateContext) interface{}

	// Visit a parse tree produced by CQLParser#destroy.
	VisitDestroy(ctx *DestroyContext) interface{}

	// Visit a parse tree produced by CQLParser#insert.
	VisitInsert(ctx *InsertContext) interface{}

	// Visit a parse tree produced by CQLParser#del.
	VisitDel(ctx *DelContext) interface{}

	// Visit a parse tree produced by CQLParser#query.
	VisitQuery(ctx *QueryContext) interface{}

	// Visit a parse tree produced by CQLParser#indexName.
	VisitIndexName(ctx *IndexNameContext) interface{}

	// Visit a parse tree produced by CQLParser#document.
	VisitDocument(ctx *DocumentContext) interface{}

	// Visit a parse tree produced by CQLParser#uintPropDef.
	VisitUintPropDef(ctx *UintPropDefContext) interface{}

	// Visit a parse tree produced by CQLParser#enumPropDef.
	VisitEnumPropDef(ctx *EnumPropDefContext) interface{}

	// Visit a parse tree produced by CQLParser#strPropDef.
	VisitStrPropDef(ctx *StrPropDefContext) interface{}

	// Visit a parse tree produced by CQLParser#orderLimit.
	VisitOrderLimit(ctx *OrderLimitContext) interface{}

	// Visit a parse tree produced by CQLParser#order.
	VisitOrder(ctx *OrderContext) interface{}

	// Visit a parse tree produced by CQLParser#property.
	VisitProperty(ctx *PropertyContext) interface{}

	// Visit a parse tree produced by CQLParser#uintType.
	VisitUintType(ctx *UintTypeContext) interface{}

	// Visit a parse tree produced by CQLParser#docId.
	VisitDocId(ctx *DocIdContext) interface{}

	// Visit a parse tree produced by CQLParser#value.
	VisitValue(ctx *ValueContext) interface{}

	// Visit a parse tree produced by CQLParser#uintPred.
	VisitUintPred(ctx *UintPredContext) interface{}

	// Visit a parse tree produced by CQLParser#enumPred.
	VisitEnumPred(ctx *EnumPredContext) interface{}

	// Visit a parse tree produced by CQLParser#strPred.
	VisitStrPred(ctx *StrPredContext) interface{}

	// Visit a parse tree produced by CQLParser#compare.
	VisitCompare(ctx *CompareContext) interface{}

	// Visit a parse tree produced by CQLParser#intList.
	VisitIntList(ctx *IntListContext) interface{}

	// Visit a parse tree produced by CQLParser#limit.
	VisitLimit(ctx *LimitContext) interface{}
}


text:
package com.liyu.fakeweather.http.api;

import com.liyu.fakeweather.http.BaseAppResponse;
import com.liyu.fakeweather.http.BaseHeWeatherCityResponse;
import com.liyu.fakeweather.model.UpdateInfo;

import retrofit2.http.GET;
import rx.Observable;

/**
 * Created by liyu on 2016/12/1.
 */

public interface AppController {

    @GET("http://api.caoliyu.cn/appupdate.json")
    Observable<BaseAppResponse<UpdateInfo>> checkUpdate();

    @GET("https://raw.githubusercontent.com/li-yu/FakeWeather/master/api/weatherkey.json")
    Observable<BaseAppResponse<String>> getWeatherKey();

    @GET("https://raw.githubusercontent.com/li-yu/FakeWeather/master/api/heweather_city_list.json")
    Observable<BaseHeWeatherCityResponse> getHeWeatherCityList();
}


text:
#include "dlm_internal.h"
#include "lockspace.h"
#include "member.h"
#include "lowcomms.h"
#include "rcom.h"
#include "config.h"
#include "memory.h"
#include "recover.h"
#include "util.h"
#include "lock.h"
#include "dir.h"

static void put_free_de(struct dlm_ls *ls, struct dlm_direntry *de)
{
	spin_lock(&ls->ls_recover_list_lock);
	list_add(&de->list, &ls->ls_recover_list);
	spin_unlock(&ls->ls_recover_list_lock);
}

static struct dlm_direntry *get_free_de(struct dlm_ls *ls, int len)
{
	int found = 0;
	struct dlm_direntry *de;

	spin_lock(&ls->ls_recover_list_lock);
	list_for_each_entry(de, &ls->ls_recover_list, list) {
		if (de->length == len) {
			list_del(&de->list);
			de->master_nodeid = 0;
			memset(de->name, 0, len);
			found = 1;
			break;
		}
	}
	spin_unlock(&ls->ls_recover_list_lock);

	if (!found)
		de = kzalloc(sizeof(struct dlm_direntry) + len, GFP_NOFS);
	return de;
}

void dlm_clear_free_entries(struct dlm_ls *ls)
{
	struct dlm_direntry *de;

	spin_lock(&ls->ls_recover_list_lock);
	while (!list_empty(&ls->ls_recover_list)) {
		de = list_entry(ls->ls_recover_list.next, struct dlm_direntry,
				list);
		list_del(&de->list);
		kfree(de);
	}
	spin_unlock(&ls->ls_recover_list_lock);
}

/*
 * We use the upper 16 bits of the hash value to select the directory node.
 * Low bits are used for distribution of rsb's among hash buckets on each node.
 *
 * To give the exact range wanted (0 to num_nodes-1), we apply a modulus of
 * num_nodes to the hash value.  This value in the desired range is used as an
 * offset into the sorted list of nodeid's to give the particular nodeid.
 */

int dlm_hash2nodeid(struct dlm_ls *ls, uint32_t hash)
{
	struct list_head *tmp;
	struct dlm_member *memb = NULL;
	uint32_t node, n = 0;
	int nodeid;

	if (ls->ls_num_nodes == 1) {
		nodeid = dlm_our_nodeid();
		goto out;
	}

	if (ls->ls_node_array) {
		node = (hash >> 16) % ls->ls_total_weight;
		nodeid = ls->ls_node_array[node];
		goto out;
	}

	/* make_member_array() failed to kmalloc ls_node_array... */

	node = (hash >> 16) % ls->ls_num_nodes;

	list_for_each(tmp, &ls->ls_nodes) {
		if (n++ != node)
			continue;
		memb = list_entry(tmp, struct dlm_member, list);
		break;
	}

	DLM_ASSERT(memb , printk("num_nodes=%u n=%u node=%u\n",
				 ls->ls_num_nodes, n, node););
	nodeid = memb->nodeid;
 out:
	return nodeid;
}

int dlm_dir_nodeid(struct dlm_rsb *r)
{
	return dlm_hash2nodeid(r->res_ls, r->res_hash);
}

static inline uint32_t dir_hash(struct dlm_ls *ls, char *name, int len)
{
	uint32_t val;

	val = jhash(name, len, 0);
	val &= (ls->ls_dirtbl_size - 1);

	return val;
}

static void add_entry_to_hash(struct dlm_ls *ls, struct dlm_direntry *de)
{
	uint32_t bucket;

	bucket = dir_hash(ls, de->name, de->length);
	list_add_tail(&de->list, &ls->ls_dirtbl[bucket].list);
}

static struct dlm_direntry *search_bucket(struct dlm_ls *ls, char *name,
					  int namelen, uint32_t bucket)
{
	struct dlm_direntry *de;

	list_for_each_entry(de, &ls->ls_dirtbl[bucket].list, list) {
		if (de->length == namelen && !memcmp(name, de->name, namelen))
			goto out;
	}
	de = NULL;
 out:
	return de;
}

void dlm_dir_remove_entry(struct dlm_ls *ls, int nodeid, char *name, int namelen)
{
	struct dlm_direntry *de;
	uint32_t bucket;

	bucket = dir_hash(ls, name, namelen);

	spin_lock(&ls->ls_dirtbl[bucket].lock);

	de = search_bucket(ls, name, namelen, bucket);

	if (!de) {
		log_error(ls, "remove fr %u none", nodeid);
		goto out;
	}

	if (de->master_nodeid != nodeid) {
		log_error(ls, "remove fr %u ID %u", nodeid, de->master_nodeid);
		goto out;
	}

	list_del(&de->list);
	kfree(de);
 out:
	spin_unlock(&ls->ls_dirtbl[bucket].lock);
}

void dlm_dir_clear(struct dlm_ls *ls)
{
	struct list_head *head;
	struct dlm_direntry *de;
	int i;

	DLM_ASSERT(list_empty(&ls->ls_recover_list), );

	for (i = 0; i < ls->ls_dirtbl_size; i++) {
		spin_lock(&ls->ls_dirtbl[i].lock);
		head = &ls->ls_dirtbl[i].list;
		while (!list_empty(head)) {
			de = list_entry(head->next, struct dlm_direntry, list);
			list_del(&de->list);
			put_free_de(ls, de);
		}
		spin_unlock(&ls->ls_dirtbl[i].lock);
	}
}

int dlm_recover_directory(struct dlm_ls *ls)
{
	struct dlm_member *memb;
	struct dlm_direntry *de;
	char *b, *last_name = NULL;
	int error = -ENOMEM, last_len, count = 0;
	uint16_t namelen;

	log_debug(ls, "dlm_recover_directory");

	if (dlm_no_directory(ls))
		goto out_status;

	dlm_dir_clear(ls);

	last_name = kmalloc(DLM_RESNAME_MAXLEN, GFP_NOFS);
	if (!last_name)
		goto out;

	list_for_each_entry(memb, &ls->ls_nodes, list) {
		memset(last_name, 0, DLM_RESNAME_MAXLEN);
		last_len = 0;

		for (;;) {
			int left;
			error = dlm_recovery_stopped(ls);
			if (error)
				goto out_free;

			error = dlm_rcom_names(ls, memb->nodeid,
					       last_name, last_len);
			if (error)
				goto out_free;

			schedule();

			/*
			 * pick namelen/name pairs out of received buffer
			 */

			b = ls->ls_recover_buf->rc_buf;
			left = ls->ls_recover_buf->rc_header.h_length;
			left -= sizeof(struct dlm_rcom);

			for (;;) {
				__be16 v;

				error = -EINVAL;
				if (left < sizeof(__be16))
					goto out_free;

				memcpy(&v, b, sizeof(__be16));
				namelen = be16_to_cpu(v);
				b += sizeof(__be16);
				left -= sizeof(__be16);

				/* namelen of 0xFFFFF marks end of names for
				   this node; namelen of 0 marks end of the
				   buffer */

				if (namelen == 0xFFFF)
					goto done;
				if (!namelen)
					break;

				if (namelen > left)
					goto out_free;

				if (namelen > DLM_RESNAME_MAXLEN)
					goto out_free;

				error = -ENOMEM;
				de = get_free_de(ls, namelen);
				if (!de)
					goto out_free;

				de->master_nodeid = memb->nodeid;
				de->length = namelen;
				last_len = namelen;
				memcpy(de->name, b, namelen);
				memcpy(last_name, b, namelen);
				b += namelen;
				left -= namelen;

				add_entry_to_hash(ls, de);
				count++;
			}
		}
         done:
		;
	}

 out_status:
	error = 0;
	log_debug(ls, "dlm_recover_directory %d entries", count);
 out_free:
	kfree(last_name);
 out:
	dlm_clear_free_entries(ls);
	return error;
}

static int get_entry(struct dlm_ls *ls, int nodeid, char *name,
		     int namelen, int *r_nodeid)
{
	struct dlm_direntry *de, *tmp;
	uint32_t bucket;

	bucket = dir_hash(ls, name, namelen);

	spin_lock(&ls->ls_dirtbl[bucket].lock);
	de = search_bucket(ls, name, namelen, bucket);
	if (de) {
		*r_nodeid = de->master_nodeid;
		spin_unlock(&ls->ls_dirtbl[bucket].lock);
		if (*r_nodeid == nodeid)
			return -EEXIST;
		return 0;
	}

	spin_unlock(&ls->ls_dirtbl[bucket].lock);

	if (namelen > DLM_RESNAME_MAXLEN)
		return -EINVAL;

	de = kzalloc(sizeof(struct dlm_direntry) + namelen, GFP_NOFS);
	if (!de)
		return -ENOMEM;

	de->master_nodeid = nodeid;
	de->length = namelen;
	memcpy(de->name, name, namelen);

	spin_lock(&ls->ls_dirtbl[bucket].lock);
	tmp = search_bucket(ls, name, namelen, bucket);
	if (tmp) {
		kfree(de);
		de = tmp;
	} else {
		list_add_tail(&de->list, &ls->ls_dirtbl[bucket].list);
	}
	*r_nodeid = de->master_nodeid;
	spin_unlock(&ls->ls_dirtbl[bucket].lock);
	return 0;
}

int dlm_dir_lookup(struct dlm_ls *ls, int nodeid, char *name, int namelen,
		   int *r_nodeid)
{
	return get_entry(ls, nodeid, name, namelen, r_nodeid);
}

static struct dlm_rsb *find_rsb_root(struct dlm_ls *ls, char *name, int len)
{
	struct dlm_rsb *r;
	uint32_t hash, bucket;
	int rv;

	hash = jhash(name, len, 0);
	bucket = hash & (ls->ls_rsbtbl_size - 1);

	spin_lock(&ls->ls_rsbtbl[bucket].lock);
	rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[bucket].keep, name, len, 0, &r);
	if (rv)
		rv = dlm_search_rsb_tree(&ls->ls_rsbtbl[bucket].toss,
					 name, len, 0, &r);
	spin_unlock(&ls->ls_rsbtbl[bucket].lock);

	if (!rv)
		return r;

	down_read(&ls->ls_root_sem);
	list_for_each_entry(r, &ls->ls_root_list, res_root_list) {
		if (len == r->res_length && !memcmp(name, r->res_name, len)) {
			up_read(&ls->ls_root_sem);
			log_error(ls, "find_rsb_root revert to root_list %s",
				  r->res_name);
			return r;
		}
	}
	up_read(&ls->ls_root_sem);
	return NULL;
}

/* Find the rsb where we left off (or start again), then send rsb names
   for rsb's we're master of and whose directory node matches the requesting
   node.  inbuf is the rsb name last sent, inlen is the name's length */

void dlm_copy_master_names(struct dlm_ls *ls, char *inbuf, int inlen,
 			   char *outbuf, int outlen, int nodeid)
{
	struct list_head *list;
	struct dlm_rsb *r;
	int offset = 0, dir_nodeid;
	__be16 be_namelen;

	down_read(&ls->ls_root_sem);

	if (inlen > 1) {
		r = find_rsb_root(ls, inbuf, inlen);
		if (!r) {
			inbuf[inlen - 1] = '\0';
			log_error(ls, "copy_master_names from %d start %d %s",
				  nodeid, inlen, inbuf);
			goto out;
		}
		list = r->res_root_list.next;
	} else {
		list = ls->ls_root_list.next;
	}

	for (offset = 0; list != &ls->ls_root_list; list = list->next) {
		r = list_entry(list, struct dlm_rsb, res_root_list);
		if (r->res_nodeid)
			continue;

		dir_nodeid = dlm_dir_nodeid(r);
		if (dir_nodeid != nodeid)
			continue;

		/*
		 * The block ends when we can't fit the following in the
		 * remaining buffer space:
		 * namelen (uint16_t) +
		 * name (r->res_length) +
		 * end-of-block record 0x0000 (uint16_t)
		 */

		if (offset + sizeof(uint16_t)*2 + r->res_length > outlen) {
			/* Write end-of-block record */
			be_namelen = cpu_to_be16(0);
			memcpy(outbuf + offset, &be_namelen, sizeof(__be16));
			offset += sizeof(__be16);
			goto out;
		}

		be_namelen = cpu_to_be16(r->res_length);
		memcpy(outbuf + offset, &be_namelen, sizeof(__be16));
		offset += sizeof(__be16);
		memcpy(outbuf + offset, r->res_name, r->res_length);
		offset += r->res_length;
	}

	/*
	 * If we've reached the end of the list (and there's room) write a
	 * terminating record.
	 */

	if ((list == &ls->ls_root_list) &&
	    (offset + sizeof(uint16_t) <= outlen)) {
		be_namelen = cpu_to_be16(0xFFFF);
		memcpy(outbuf + offset, &be_namelen, sizeof(__be16));
		offset += sizeof(__be16);
	}

 out:
	up_read(&ls->ls_root_sem);
}


text:
module ResqueUnit
  module Helpers
    # Given a Ruby object, returns a string suitable for storage in a
    # queue.
    def encode(object)
      if defined? Yajl
        Yajl::Encoder.encode(object)
      else
        object.to_json
      end
    end

    # Given a string, returns a Ruby object.
    def decode(object)
      return unless object

      if defined? Yajl
        begin
          Yajl::Parser.parse(object, :check_utf8 => false)
        rescue Yajl::ParseError
        end
      else
        begin
          JSON.parse(object)
        rescue JSON::ParserError
        end
      end
    end

    # Given a word with dashes, returns a camel cased version of it.
    #
    # classify('job-name') # => 'JobName'
    def classify(dashed_word)
      dashed_word.split('-').each { |part| part[0] = part[0].chr.upcase }.join
    end

    # Given a camel cased word, returns the constant it represents
    #
    # constantize('JobName') # => JobName
    def constantize(camel_cased_word)
      camel_cased_word = camel_cased_word.to_s

      if camel_cased_word.include?('-')
        camel_cased_word = classify(camel_cased_word)
      end

      names = camel_cased_word.split('::')
      names.shift if names.empty? || names.first.empty?

      constant = Object
      names.each do |name|
        constant = constant.const_get(name) || constant.const_missing(name)
      end
      constant
    end
  end
end


text:
<?xml version="1.0" encoding="latin1" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>1996</year><year>2010</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.

      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.

    </legalnotice>

    <title>erl_lint</title>
    <prepared>Robert Virding</prepared>
    <responsible>Bjarne Dacker</responsible>
    <docno>1</docno>
    <approved>Bjarne Däcker</approved>
    <checked></checked>
    <date>97-01-27</date>
    <rev>B</rev>
    <file>erl_lint.sgml</file>

  <module>erl_lint</module>
  <modulesummary>The Erlang Code Linter</modulesummary>
  <description>

This module is used to check Erlang code for illegal syntax and
      other bugs. It also warns against coding practices which are
      not recommended.

The errors detected include:

    <list type="bulleted">
      <item>redefined and undefined functions</item>
      <item>unbound and unsafe variables</item>
      <item>illegal record usage.</item>
    </list>

Warnings include:

    <list type="bulleted">
      <item>unused functions and imports</item>
      <item>unused variables</item>
      <item>variables imported into matches</item>
      <item>variables exported from
      <c>if</c>/<c>case</c>/<c>receive</c></item>
      <item>variables shadowed in lambdas and list
       comprehensions.</item>
    </list>

Some of the warnings are optional, and can be turned on by
      giving the appropriate option, described below.

The functions in this module are invoked automatically by the
      Erlang compiler and there is no reason to invoke these
      functions separately unless you have written your own Erlang
      compiler.

  </description>
  <funcs>
    <func>
      <name>module(AbsForms) -> {ok,Warnings}  | {error,Errors,Warnings}</name>
      <name>module(AbsForms, FileName) -> {ok,Warnings}  | {error,Errors,Warnings}</name>
      <name>module(AbsForms, FileName, CompileOptions) ->  {ok,Warnings} | {error,Errors,Warnings}</name>
      <fsummary>Check a module for errors</fsummary>
      <type>
        <v>AbsForms = [term()]</v>
        <v>FileName = FileName2 = atom() | string()</v>
        <v>Warnings = Errors = [{Filename2,[ErrorInfo]}]</v>
        <v>ErrorInfo = see separate description below.</v>
        <v>CompileOptions = [term()]</v>
      </type>
      <desc>

This function checks all the forms in a module for errors.
          It returns:

        <taglist>
          <tag><c>{ok,Warnings}</c></tag>
          <item>

There were no errors in the module.

          </item>
          <tag><c>{error,Errors,Warnings}</c></tag>
          <item>

There were errors in the module.

          </item>
        </taglist>

Since this module is of interest only to the maintainers of
          the compiler, and to avoid having the same description in
          two places to avoid the usual maintenance nightmare, the
          elements of <c>Options</c> that control the warnings are
          only described in <seealso marker="compiler:compile#erl_lint_options">compile(3)</seealso>.

The <c>AbsForms</c> of a module which comes from a file
          that is read through <c>epp</c>, the Erlang pre-processor,
          can come from many files. This means that any references to
          errors must include the file name (see <seealso marker="epp">epp(3)</seealso>, or parser <seealso marker="erl_parse">erl_parse(3)</seealso>).
          The warnings and errors returned have the following format:

    [{FileName2,[ErrorInfo]}]

The errors and warnings are listed in the order in which
          they are encountered in the forms. This means that the
          errors from one file may be split into different entries in
          the list of errors.

      </desc>
    </func>
    <func>
      <name>is_guard_test(Expr) -> bool()</name>
      <fsummary>Test for a guard test</fsummary>
      <type>
        <v>Expr = term()</v>
      </type>
      <desc>

This function tests if <c>Expr</c> is a legal guard test.
          <c>Expr</c> is an Erlang term representing the abstract form
          for the expression. <c>erl_parse:parse_exprs(Tokens)</c> can
          be used to generate a list of <c>Expr</c>.

      </desc>
    </func>
    <func>
      <name>format_error(ErrorDescriptor) -> Chars</name>
      <fsummary>Format an error descriptor</fsummary>
      <type>
        <v>ErrorDescriptor = errordesc()</v>
        <v>Chars = [char() | Chars]</v>
      </type>
      <desc>

Takes an <c>ErrorDescriptor</c> and returns a string which
          describes the error or warning. This function is usually
          called implicitly when processing an <c>ErrorInfo</c>
          structure (see below).

      </desc>
    </func>
  </funcs>

    <title>Error Information</title>

The <c>ErrorInfo</c> mentioned above is the standard
      <c>ErrorInfo</c> structure which is returned from all IO
      modules. It has the following format:

    {ErrorLine, Module, ErrorDescriptor}

A string which describes the error is obtained with the following call:

    Module:format_error(ErrorDescriptor)

    <title>See Also</title>

<seealso marker="erl_parse">erl_parse(3)</seealso>,
      <seealso marker="epp">epp(3)</seealso>

</erlref>


text:
require 'spec_helper'

module FlexibleFeeds
  describe Feed do

    it "validates a unique name within the scope of its feedable" do
      group = FactoryGirl.create(:group)
      group.feeds.create(name: "My Feed")
      expect(group.feeds.create(name: "My Feed").invalid?).to be true
    end

    context "belongs to" do
      before :each do
        @feed = FactoryGirl.build(:flexible_feeds_feed)
      end

      it "feedable" do
        expect(@feed).to belong_to(:feedable)
      end
    end

    context "has many" do
      before :each do
        @feed = FactoryGirl.build(:flexible_feeds_feed)
      end

      it "event joins" do
        expect(@feed).to have_many(:event_joins).dependent(:destroy)
      end

      it "events" do
        expect(@feed).to have_many(:events).through(:event_joins)
      end

      it "follows" do
        expect(@feed).to have_many(:follows).dependent(:destroy)
      end

      it "moderator joins" do
        expect(@feed).to have_many(:moderator_joins).dependent(:destroy)
      end
    end

    context "manages polymorphic moderators" do
      before :each do
        @feed = FactoryGirl.create(:flexible_feeds_feed)
        @user = FactoryGirl.create(:user)
      end

      it "by adding and listing them" do
        @feed.add_moderator(@user)
        expect(@feed.moderators).to include(@user)
      end

      it "by refusing to add moderators that are already moderators" do
        @feed.add_moderator(@user)
        expect(@feed.add_moderator(@user).invalid?).to be true
      end

      it "by checking if someone is a moderator" do
        @feed.add_moderator(@user)
        expect(@feed.moderators_include?(@user)).to be true
      end

      it "by checking if someone is not a moderator" do
        expect(@feed.moderators_include?(@user)).to be false
      end

      it "by removing them" do
        @feed.add_moderator(@user)
        @feed.remove_moderator(@user)
        expect(@feed.moderators).to_not include(@user)
      end

      it "by only attempting to remove moderators that are present" do
        @feed.remove_moderator(@user)
        expect(@feed.remove_moderator(@user)).to be false
      end
    end

    context "manages polymorphic followers" do
      before :each do
        @feed = FactoryGirl.create(:flexible_feeds_feed)
        @user = FactoryGirl.create(:user)
      end

      it "by adding and listing them" do
        @feed.add_follower(@user)
        expect(@feed.followers).to include(@user)
      end

      it "by checking if someone is a follower" do
        @feed.add_follower(@user)
        expect(@feed.followers_include?(@user)).to be true
      end

      it "by checking if someone is not a follower" do
        expect(@feed.followers_include?(@user)).to be false
      end

      it "by removing them" do
        @feed.add_follower(@user)
        @feed.remove_follower(@user)
        expect(@feed.followers).to_not include(@user)
      end
    end
  end
end


text:
"""A live word cloud for Twitch chat.
"""
from __future__ import division
from collections import deque
from pubsub import pub
import wx
import gui
import plugins

class Tail(object):

    def __init__(self, length=100):
        self._words = {}
        self._tail = deque(maxlen=length)
        self._length = length

    def add(self, line):
        if not line:
            return

        for word in self._words.values():
            word.frecency -= word.occurences

        newline = []
        for key in line:
            if key in self._words:
                word = self._words[key]
            else:
                word = Word(key)
                self._words[key] = word
            word.occurences += 1
            word.frecency += self._length
            newline.append(word)

        if len(self._tail) == self._length:
            for word in self._tail[0]:
                word.occurences -= 1
                if word.occurences == 0:
                    del self._words[word.word]

        self._tail.append(newline)

    def words(self):
        return sorted(self._words.values(), key=lambda w: w.frecency, reverse=True)

class Word(object):

    def __init__(self, word):
        self.word = word
        self.occurences = 0
        self.frecency = 0

class View(plugins.View):

    def oninit(self):
        self.limit = 30
        self.sizer = gui.FlowSizer()
        self.sizer.SetLineSpacing(4)
        self.iswindows = 'wxMSW' in wx.PlatformInfo

        self.wordtexts = []
        for _ in range(self.limit):
            ctrl = wx.StaticText(self.panel, -1, '', style=wx.ALIGN_RIGHT)
            ctrl.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL))
            ctrl.SetForegroundColour((255, 255, 255))
            self.sizer.Add(ctrl, 0, flag=wx.LEFT | wx.RIGHT, border=3)
            self.wordtexts.append(ctrl)

        self.panel.SetSizer(self.sizer)

    def setwords(self, words):
        if not words:
            return

        words = words[:self.limit]

        min_fontsize = 10
        max_fontsize = 30
        fontsize_range = min_fontsize - max_fontsize
        default_fontsize = min_fontsize + fontsize_range / 2

        min_frecency = words[-1].frecency
        max_frecency = words[0].frecency
        frecency_range = min_frecency - max_frecency

        for i, word in enumerate(words):
            if frecency_range:
                fontsize = min_fontsize + \
                    (((word.frecency - min_frecency) / frecency_range) * fontsize_range)
            else:
                fontsize = default_fontsize

            # Windows wxPython hack
            if self.iswindows:
                self.wordtexts[i].SetFont(
                    wx.Font(fontsize, wx.ROMAN, wx.NORMAL, wx.NORMAL))

            self.wordtexts[i].SetFont(
                wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.NORMAL))

            self.wordtexts[i].SetLabel(word.word)

        self.sizer.Layout()

IGNORE_DEFAULT = [
    "a", "about", "all", "am", "an", "and", "any", "anything", "are", "as",
    "at", "be", "because", "been", "but", "can", "can't", "cant", "come",
    "could", "couldn't", "couldnt", "did", "didn't", "didnt", "do", "don't",
    "dont", "for", "from", "get", "go", "going", "good", "got", "had", "has",
    "have", "he", "her", "here", "he's", "hes", "hey", "him", "his", "how",
    "i", "i'd", "if", "i'll", "ill", "i'm", "im", "in", "is", "it", "it's",
    "its", "ive", "i've", "just", "like", "look", "me", "my", "no", "not",
    "now", "of", "oh", "ok", "okay", "on", "one", "or", "out", "see", "she",
    "she's", "shes", "so", "some", "than", "that", "that's", "thats", "the",
    "them", "then", "there", "theres", "there's", "they", "they're", "theyre",
    "think", "this", "time", "to", "u", "up", "want", "was", "we", "well",
    "were", "what", "when", "where", "who", "why", "will", "with", "would",
    "yeah", "yes", "you", "your", "you're", "youre"]

class Plugin(plugins.Plugin):
    name = 'Word Cloud'
    viewtype = View

    def oninit(self):
        self.filters = [lambda x: not "http://" in x and not "https://" in x]
        self.ignore = IGNORE_DEFAULT + ["kappa", "keepo", "kreygasm"]
        self.strip = " .;\"',:?!(){}/*-+=<>"

    def onopen(self):
        self.tail = Tail()
        pub.subscribe(self.onchatmessage, "service.chat.message")

    def onclose(self):
        pub.unsubscribe(self.onchatmessage, "service.chat.message")
        self.tail = None

    def onchatmessage(self, user, message):
        if not message:
            return

        for filter_ in self.filters:
            if not filter_(message):
                return

        line = []
        message = message.strip().split()
        for word in message:
            try:
                word.decode('ascii')
            except UnicodeDecodeError:
                pass
            else:
                word = word.strip(self.strip).lower()
                if word and not word in line and not word in self.ignore:
                    line.append(word)

        if len(line):
            self.tail.add(line)

        self.view.setwords(self.tail.words())