text:
import sympy
import collections
from IPython.display import display
from sympy import *
from sympy.tensor import IndexedBase, Idx, Indexed
from sympy.physics.secondquant import KroneckerDelta as delta
from sympy.core.relational import Relational

init_printing()

class Equals(Relational):
    """
    Non-functional equals for display purpose only
    """
    rel_op = '=='

def apply_recursive(f, expr):
    """
    Applys a function to each sub-tree of the expression tree,
    returns the new expression.
    """
    if expr.args:
        new_args = [apply_recursive(f,e) for e in expr.args]
        return f(expr.func(*new_args))
    else: return f(expr)

def expand_sums(expr, indices):
    """
    Expands sums on multiplicative terms on RHS where
    indices appear exactly twice.
    """

    if not indices: return expr
    if not isinstance(indices, collections.Iterable): indices = [indices]

    contracted = set()

    def sum_mul_term(expr, index):
        if not isinstance(expr, sympy.Mul): return expr

        count = expr.count(index)
        if (count == 2):
            contracted.add(index)
            terms = [expr.subs(index,val) for val in range(index.lower, index.upper+1)]
            expr = sympy.Add(*terms)
        return expr

    # Expand sum for every index
    rhs = expr.rhs
    for index in indices:
        rhs = apply_recursive(lambda e: sum_mul_term(e, index), rhs)

    return Equals(expr.lhs, rhs)

def enumerate_indices(expr, indices):
    """
    Generates a list of expressions from a single
    expression by substitutng values into indices
    based on their range.
    """

    # Make sure indices is a list
    if not indices: return expr
    if not isinstance(indices, collections.Iterable): indices = [indices]

    all_expr = [expr]
    indices = list(indices)        # To allow for popping below

    # For every index
    while indices:
        index = indices.pop()

        # For every previously added expression
        num_expr = len(all_expr)
        for i in range(0,num_expr):
            expr = all_expr.pop(0)
            # Substitute
            new_exprs = [expr.subs(index, val) for val in range(index.lower, index.upper+1)]
            # Add only if doesnt exist yet
            [all_expr.append(new) for new in new_exprs if new not in all_expr]

    return all_expr

# Pair -> Parent value
voigt_map = {1:{(0,0):0},

             2:{(0,0):0,  (0,1):2,
                (1,0):2,  (1,1):1},

             3:{(0,0):0, (0,1):5, (0,2):4,
                (1,0):5, (1,1):1, (1,2):3,
                (2,0):4, (2,1):3, (2,2):2}}

def apply_rules(tensor, full_exprs, voigt_pairs, kinematic_pairs, vector_pairs):
    """
    Cycles through index pairs and applies voigt/vector rules if required
    """

    # Cycle through index pairs
    indices = tensor.indices
    for pos in range(len(indices)-1,-1,-1):
        pair = tuple(indices[pos:pos+2])

        # Determine what rule to apply
        rule = None
        rhs_transform = lambda num_pair, x: x
        if pair in voigt_pairs:
            # Get corrent dimension
            dim = pair[0].upper+1

            # Get factor to multiply rhs by
            if pair in kinematic_pairs:
                rhs_transform = lambda num_pair, x: 2*x if num_pair[0] != num_pair[1] else x

            # Pair mapping rule
            rule = lambda num_pair: voigt_map[dim][num_pair]

        elif pair in vector_pairs:
            # Flip pair
            if (pair[0].label.name.islower()):
                dim = pair[0].upper+1
                rule = lambda num_pair: num_pair[1]*dim + num_pair[0]
            else:
                dim = pair[1].upper+1
                rule = lambda num_pair: num_pair[0]*dim + num_pair[1]

        # Dont transform this rule if nothing found
        if not rule: continue

        results = []
        for expr in full_exprs:
            lhs = expr.lhs
            num_pair = tuple(lhs.indices[pos:pos+2])
            new_val = rule(num_pair)
            new_indices = lhs.indices[0:pos] + (new_val,) + lhs.indices[pos+2:]
            lhs = lhs.base[new_indices]
            rhs = rhs_transform(num_pair, expr.rhs)
            results.append(Equals(lhs, rhs))
        full_exprs = results

    return full_exprs

def generate_matrix(exprs):
    """
    Converts a set of expressions to a matrix
    """

    # Count required indicies
    nindices = min([len(expr.lhs.indices) for expr in exprs])
    nrows = max([expr.lhs.indices[0] for expr in exprs]) + 1
    if nindices == 1:
        ncols = 1
    elif nindices == 2:
        ncols = max([expr.lhs.indices[1] for expr in exprs]) + 1
    else:
        return exprs    # Cannot generate matrix

    #lhs_mat = zeros(nrows, ncols)
    rhs_mat = zeros(nrows, ncols)

    for expr in exprs:
        row = expr.lhs.indices[0]
        if nindices == 2: col = expr.lhs.indices[1]
        else: col = 0
        #lhs_mat[row,col] = expr.lhs
        if not rhs_mat[row,col]: rhs_mat[row,col] = expr.rhs

    return Equals(expr.lhs.base, rhs_mat)

def generate_subs_map(exprs):
    return {expr.rhs : expr.lhs for expr in exprs}

def transform(expr, indices, voigt=[], kinematic=[], vector=[]):
    """
    Converts a tensor expression to a set of expanded expressions with
    voigt and vector rules applied
    """

    # Convert voigt, kinematic, vector to lists of pairs, if required
    def ensure_list_of_pairs(x): return [x] if (x and isinstance(x[0], Idx)) else x
    voigt     = ensure_list_of_pairs(voigt)
    kinematic = ensure_list_of_pairs(kinematic)
    vector    = ensure_list_of_pairs(vector)

    # This is the lhs of the original tensor expression, which is used to determine
    # where the original indices were
    tensor = expr.lhs
    if not isinstance(tensor, Indexed): raise TypeError("Require an indexed expression on lhs.")

    # Expand sums, generate expressions
    exprs = expand_sums(expr, indices)
    exprs = enumerate_indices(exprs, indices)
    exprs = apply_rules(tensor, exprs, voigt, kinematic, vector)
    return exprs

A = IndexedBase("A")
B = IndexedBase("B")
C = IndexedBase("\mathbb{C}")
N = IndexedBase("N")
dNdX = IndexedBase("\\frac{dN}{dX}")
IoI = IndexedBase("I \otimes I")
II = IndexedBase("\mathbb{I}")
P = IndexedBase("\mathbb{P}")
dRdu = IndexedBase("dRdu")

strain = IndexedBase("varepsilon")

i = Idx("i",2)
j = Idx("j",2)
k = Idx("k",2)
l = Idx("l",2)
r = Idx("r",2)
m = Idx("m",2)
n = Idx("n",2)

I = Idx("I",4)
J = Idx("J",4)
M = Idx("M",4)

# Strain tensor
expr = Equals(strain[i,j], strain[i,j])
exprs = transform(expr, (i,j), (i,j), (i,j))
mat = generate_matrix(exprs)
display(mat)

# B Matrix
expr = Equals(B[i,j,r,I], Rational(1,2)*(N[I,j]*delta(r,i) + N[I,i]*delta(r,j)))
exprs = transform(expr, (i,j,r,I), voigt=(i,j), kinematic=(i,j), vector=(r,I))
B = generate_matrix(exprs)
display(B)
B = B.rhs

# Trace operatpr
expr = Equals(IoI[i,j,k,l], delta(i,j)*delta(k,l))
exprs = transform(expr, (i,j,k,l), voigt=[(i,j), (k,l)])
mat = generate_matrix(exprs)
display(mat)

# 4th order identity
expr = Equals(II[i,j,k,l], 0.5*delta(i,k)*delta(j,l) + 0.5*delta(i,l)*delta(j,k))
exprs = transform(expr, (i,j,k,l), voigt=[(i,j), (k,l)])
mat = generate_matrix(exprs)
display(mat)

# Projection
expr = Equals(P[i,j,k,l], Rational(1,2)*(delta(i, k)*delta(j, l)+delta(i, l)*delta(j, k))-Rational(1,3)*delta(i, j)*delta(k, l))
exprs = transform(expr, (i,j,k,l), voigt=[(i,j), (k,l)])
mat = generate_matrix(exprs)
display(mat)

# Tangent matrix
expr = Equals(C[i,j,k,l], C[i,j,k,l])
exprs = transform(expr, (i,j,k,l), voigt=[(i,j), (k,l)])
sub_map = generate_subs_map(exprs)
CC = generate_matrix(exprs)
CC = CC.rhs

# Derivative of residual  w.r.t. displacement
expr = Equals(dRdu[I, i, J, j], N[I,k]*C[i, k, j, n]*N[J,n])
exprs = transform(expr, (i,I,j,J,k,n), vector=[(I,i), (J,j)])
exprs = [e.subs(sub_map) for e in exprs]
mat = generate_matrix(exprs)
display(mat)

# Multiplication
A = IndexedBase("A")
B = IndexedBase("B")
C = IndexedBase("C")

i = Idx("i", 2)
j = Idx("j", 2)
k = Idx("k", 2)

expr = Equals(C[i,j], A[i,k]*B[k,j])

exprs = transform(expr, (i,j,k))
mat = generate_matrix(exprs)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GitTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //第一次提交
            //第二次提交
            //第三次提交
            //第四次提交
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.ilivoo.common.socket.serializing.serializers;

import java.io.IOException;

import com.ilivoo.common.socket.buffer.ChannelBuffer;
import com.ilivoo.common.socket.serializing.Serializer;

/**
 * The Long serializer.
 *
 * @author Lars Wesselius
 */
@SuppressWarnings("rawtypes")
public class LongSerializer extends Serializer {

    @SuppressWarnings("unchecked")
    public Long readObject(ChannelBuffer data, Class c) throws IOException {
        return data.getLong();
    }

    public void writeObject(ChannelBuffer buffer, Object object) throws IOException {
        buffer.putLong((Long)object);
    }
}


text:
namespace llvm {
  // Containers.
  class StringRef;
  class Twine;
  template <typename T> class SmallPtrSetImpl;
  template <typename T, unsigned N> class SmallPtrSet;
  template <typename T> class SmallVectorImpl;
  template <typename T, unsigned N> class SmallVector;
  template <unsigned N> class SmallString;
  template<typename T> class ArrayRef;
  template<typename T> class MutableArrayRef;
  template<typename T> class TinyPtrVector;
  template<typename T> class Optional;
  template <typename PT1, typename PT2> class PointerUnion;

  // Other common classes.
  class raw_ostream;
  class APInt;
  class APFloat;
} // end namespace llvm

namespace swift {
  // Casting operators.
  using llvm::isa;
  using llvm::cast;
  using llvm::dyn_cast;
  using llvm::dyn_cast_or_null;
  using llvm::cast_or_null;

  // Containers.
  using llvm::None;
  using llvm::Optional;
  using llvm::SmallPtrSetImpl;
  using llvm::SmallPtrSet;
  using llvm::SmallString;
  using llvm::StringRef;
  using llvm::Twine;
  using llvm::SmallVectorImpl;
  using llvm::SmallVector;
  using llvm::ArrayRef;
  using llvm::MutableArrayRef;
  using llvm::TinyPtrVector;
  using llvm::PointerUnion;

  // Other common classes.
  using llvm::raw_ostream;
  using llvm::APInt;
  using llvm::APFloat;
  using llvm::NoneType;
} // end namespace swift

#endif // SWIFT_BASIC_LLVM_H


text:
#ifndef STAN_SERVICES_UTIL_INITIALIZE_HPP
#define STAN_SERVICES_UTIL_INITIALIZE_HPP

#include <stan/callbacks/logger.hpp>
#include <stan/callbacks/writer.hpp>
#include <stan/io/var_context.hpp>
#include <stan/io/random_var_context.hpp>
#include <stan/io/chained_var_context.hpp>
#include <stan/model/log_prob_grad.hpp>
#include <stan/math/prim.hpp>
#include <chrono>
#include <sstream>
#include <string>
#include <vector>

namespace stan {
namespace services {
namespace util {

/**
 * Returns a valid initial value of the parameters of the model
 * on the unconstrained scale.
 *
 * For identical inputs (model, init, rng, init_radius), this
 * function will produce the same initialization.
 *
 * Initialization first tries to use the provided
 * stan::io::var_context, then it will generate
 * random uniform values from -init_radius to +init_radius for missing
 * parameters.
 *
 * When the var_context provides all variables or
 * the init_radius is 0, this function will only evaluate the
 * log probability of the model with the unconstrained
 * parameters once to see if it's valid.
 *
 * When at least some of the initialization is random, it will
 * randomly initialize until it finds a set of unconstrained
 * parameters that are valid or it hits MAX_INIT_TRIES =
 * 100 (hard-coded).
 *
 * Valid initialization is defined as a finite, non-NaN value for the
 * evaluation of the log probability density function and all its
 * gradients.
 *
 * @tparam Jacobian indicates whether to include the Jacobian term when
 *   evaluating the log density function
 * @tparam Model the type of the model class
 * @tparam RNG the type of the random number generator
 *
 * @param[in] model the model
 * @param[in] init a var_context with initial values
 * @param[in,out] rng random number generator
 * @param[in] init_radius the radius for generating random values.
 *   A value of 0 indicates that the unconstrained parameters (not
 *   provided by init) should be initialized with 0.
 * @param[in] print_timing indicates whether a timing message should
 *   be printed to the logger
 * @param[in,out] logger logger for messages
 * @param[in,out] init_writer init writer (on the unconstrained scale)
 * @throws exception passed through from the model if the model has a
 *   fatal error (not a std::domain_error)
 * @throws std::domain_error if the model can not be initialized and
 *   the model does not have a fatal error (only allows for
 *   std::domain_error)
 * @return valid unconstrained parameters for the model
 */
template <bool Jacobian = true, typename Model, typename InitContext,
          typename RNG>
std::vector<double> initialize(Model& model, const InitContext& init, RNG& rng,
                               double init_radius, bool print_timing,
                               stan::callbacks::logger& logger,
                               stan::callbacks::writer& init_writer) {
  std::vector<double> unconstrained;
  std::vector<int> disc_vector;

  bool is_fully_initialized = true;
  bool any_initialized = false;
  std::vector<std::string> param_names;
  model.get_param_names(param_names);
  for (size_t n = 0; n < param_names.size(); n++) {
    is_fully_initialized &= init.contains_r(param_names[n]);
    any_initialized |= init.contains_r(param_names[n]);
  }

  bool is_initialized_with_zero = init_radius == 0.0;

  int MAX_INIT_TRIES
      = is_fully_initialized || is_initialized_with_zero ? 1 : 100;
  int num_init_tries = 0;
  for (; num_init_tries < MAX_INIT_TRIES; num_init_tries++) {
    std::stringstream msg;
    try {
      stan::io::random_var_context random_context(model, rng, init_radius,
                                                  is_initialized_with_zero);

      if (!any_initialized) {
        unconstrained = random_context.get_unconstrained();
      } else {
        stan::io::chained_var_context context(init, random_context);

        model.transform_inits(context, disc_vector, unconstrained, &msg);
      }
    } catch (std::domain_error& e) {
      if (msg.str().length() > 0)
        logger.info(msg);
      logger.info("Rejecting initial value:");
      logger.info(
          "  Error evaluating the log probability"
          " at the initial value.");
      logger.info(e.what());
      continue;
    } catch (std::exception& e) {
      if (msg.str().length() > 0)
        logger.info(msg);
      logger.info(
          "Unrecoverable error evaluating the log probability"
          " at the initial value.");
      logger.info(e.what());
      throw;
    }

    msg.str("");
    double log_prob(0);
    try {
      // we evaluate the log_prob function with propto=false
      // because we're evaluating with `double` as the type of
      // the parameters.
      log_prob = model.template log_prob<false, Jacobian>(unconstrained,
                                                          disc_vector, &msg);
      if (msg.str().length() > 0)
        logger.info(msg);
    } catch (std::domain_error& e) {
      if (msg.str().length() > 0)
        logger.info(msg);
      logger.info("Rejecting initial value:");
      logger.info(
          "  Error evaluating the log probability"
          " at the initial value.");
      logger.info(e.what());
      continue;
    } catch (std::exception& e) {
      if (msg.str().length() > 0)
        logger.info(msg);
      logger.info(
          "Unrecoverable error evaluating the log probability"
          " at the initial value.");
      logger.info(e.what());
      throw;
    }
    if (!std::isfinite(log_prob)) {
      logger.info("Rejecting initial value:");
      logger.info(
          "  Log probability evaluates to log(0),"
          " i.e. negative infinity.");
      logger.info(
          "  Stan can't start sampling from this"
          " initial value.");
      continue;
    }
    std::stringstream log_prob_msg;
    std::vector<double> gradient;
    auto start = std::chrono::steady_clock::now();
    try {
      // we evaluate this with propto=true since we're
      // evaluating with autodiff variables
      log_prob = stan::model::log_prob_grad<true, Jacobian>(
          model, unconstrained, disc_vector, gradient, &log_prob_msg);
    } catch (const std::exception& e) {
      if (log_prob_msg.str().length() > 0)
        logger.info(log_prob_msg);
      logger.info(e.what());
      throw;
    }
    auto end = std::chrono::steady_clock::now();
    double deltaT
        = std::chrono::duration_cast<std::chrono::microseconds>(end - start)
              .count()
          / 1000000.0;
    if (log_prob_msg.str().length() > 0)
      logger.info(log_prob_msg);

    bool gradient_ok = std::isfinite(stan::math::sum(gradient));

    if (!gradient_ok) {
      logger.info("Rejecting initial value:");
      logger.info(
          "  Gradient evaluated at the initial value"
          " is not finite.");
      logger.info(
          "  Stan can't start sampling from this"
          " initial value.");
    }
    if (gradient_ok && print_timing) {
      logger.info("");
      std::stringstream msg1;
      msg1 << "Gradient evaluation took " << deltaT << " seconds";
      logger.info(msg1);

      std::stringstream msg2;
      msg2 << "1000 transitions using 10 leapfrog steps"
           << " per transition would take"
           << " " << 1e4 * deltaT << " seconds.";
      logger.info(msg2);

      logger.info("Adjust your expectations accordingly!");
      logger.info("");
      logger.info("");
    }
    if (gradient_ok) {
      init_writer(unconstrained);
      return unconstrained;
    }
  }

  if (!is_initialized_with_zero) {
    logger.info("");
    std::stringstream msg;
    msg << "Initialization between (-" << init_radius << ", " << init_radius
        << ") failed after"
        << " " << MAX_INIT_TRIES << " attempts. ";
    logger.info(msg);
    logger.info(
        " Try specifying initial values,"
        " reducing ranges of constrained values,"
        " or reparameterizing the model.");
  }
  throw std::domain_error("Initialization failed.");
}

}  // namespace util
}  // namespace services
}  // namespace stan
#endif


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

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

View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.cpd;
5
6   import java.util.List;
7
8   /**
9    * Simple tokenizer for PHP.
10   */
11  public class PHPTokenizer implements Tokenizer {
12
13      @Override
14      public void tokenize(SourceCode tokens, Tokens tokenEntries) {
15          List<String> code = tokens.getCode();
16          for (int i = 0; i < code.size(); i++) {
17              String currentLine = code.get(i);
18              for (int j = 0; j < currentLine.length(); j++) {
19                  char tok = currentLine.charAt(j);
20                  if (!Character.isWhitespace(tok) && tok != '{' && tok != '}' && tok != ';') {
21                      tokenEntries.add(new TokenEntry(String.valueOf(tok), tokens.getFileName(), i + 1));
22                  }
23              }
24          }
25          tokenEntries.add(TokenEntry.getEOF());
26      }
27  }

Copyright © 2002–2016 InfoEther. All rights reserved.


text:
namespace System.ServiceModel.Channels
{
    // Bindings can implement this interface in order to advertise capabilities
    // that DeliveryRequirementsAttribute consumes
    public interface IBindingDeliveryCapabilities
    {
        // This bool gives an assurance: "true" means you get Ordered, "false" means you may not
        // [DeliveryRequirements(RequireOrderedDelivery)] consumes this
        bool AssuresOrderedDelivery { get; }

        // Is this binding a queue (in the transacted-receive sense)
        // [DeliveryRequirements(QueuedDeliveryRequirements)] consumes this
        bool QueuedDelivery { get; }
    }
}


text:
package dockershim

import (
	"bytes"
	"fmt"
	"io"
	"math"
	"time"

	dockertypes "github.com/docker/engine-api/types"
	runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
	"k8s.io/kubernetes/pkg/kubelet/dockertools"
	"k8s.io/kubernetes/pkg/kubelet/server/streaming"
	"k8s.io/kubernetes/pkg/kubelet/util/ioutils"
	"k8s.io/kubernetes/pkg/util/term"
)

type streamingRuntime struct {
	client      dockertools.DockerInterface
	execHandler dockertools.ExecHandler
}

var _ streaming.Runtime = &streamingRuntime{}

func (r *streamingRuntime) Exec(containerID string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error {
	return r.exec(containerID, cmd, in, out, err, tty, resize, 0)
}

// Internal version of Exec adds a timeout.
func (r *streamingRuntime) exec(containerID string, cmd []string, in io.Reader, out, errw io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error {
	container, err := checkContainerStatus(r.client, containerID)
	if err != nil {
		return err
	}
	return r.execHandler.ExecInContainer(r.client, container, cmd, in, out, errw, tty, resize, timeout)
}

func (r *streamingRuntime) Attach(containerID string, in io.Reader, out, errw io.WriteCloser, resize <-chan term.Size) error {
	container, err := checkContainerStatus(r.client, containerID)
	if err != nil {
		return err
	}

	tty := container.Config.Tty
	return dockertools.AttachContainer(r.client, containerID, in, out, errw, tty, resize)
}

func (r *streamingRuntime) PortForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error {
	if port < 0 || port > math.MaxUint16 {
		return fmt.Errorf("invalid port %d", port)
	}
	return dockertools.PortForward(r.client, podSandboxID, uint16(port), stream)
}

// ExecSync executes a command in the container, and returns the stdout output.
// If command exits with a non-zero exit code, an error is returned.
func (ds *dockerService) ExecSync(containerID string, cmd []string, timeout time.Duration) (stdout []byte, stderr []byte, err error) {
	var stdoutBuffer, stderrBuffer bytes.Buffer
	err = ds.streamingRuntime.exec(containerID, cmd,
		nil, // in
		ioutils.WriteCloserWrapper(&stdoutBuffer),
		ioutils.WriteCloserWrapper(&stderrBuffer),
		false, // tty
		nil,   // resize
		timeout)
	return stdoutBuffer.Bytes(), stderrBuffer.Bytes(), err
}

// Exec prepares a streaming endpoint to execute a command in the container, and returns the address.
func (ds *dockerService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {
	if ds.streamingServer == nil {
		return nil, streaming.ErrorStreamingDisabled("exec")
	}
	_, err := checkContainerStatus(ds.client, req.GetContainerId())
	if err != nil {
		return nil, err
	}
	return ds.streamingServer.GetExec(req)
}

// Attach prepares a streaming endpoint to attach to a running container, and returns the address.
func (ds *dockerService) Attach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {
	if ds.streamingServer == nil {
		return nil, streaming.ErrorStreamingDisabled("attach")
	}
	container, err := checkContainerStatus(ds.client, req.GetContainerId())
	if err != nil {
		return nil, err
	}
	tty := container.Config.Tty
	return ds.streamingServer.GetAttach(req, tty)
}

// PortForward prepares a streaming endpoint to forward ports from a PodSandbox, and returns the address.
func (ds *dockerService) PortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {
	if ds.streamingServer == nil {
		return nil, streaming.ErrorStreamingDisabled("port forward")
	}
	_, err := checkContainerStatus(ds.client, req.GetPodSandboxId())
	if err != nil {
		return nil, err
	}
	// TODO(timstclair): Verify that ports are exposed.
	return ds.streamingServer.GetPortForward(req)
}

func checkContainerStatus(client dockertools.DockerInterface, containerID string) (*dockertypes.ContainerJSON, error) {
	container, err := client.InspectContainer(containerID)
	if err != nil {
		return nil, err
	}
	if !container.State.Running {
		return nil, fmt.Errorf("container not running (%s)", container.ID)
	}
	return container, nil
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using TweetDuck.Management;
using TweetLib.Core;
using TweetLib.Core.Features.Plugins;
using TweetLib.Core.Systems.Configuration;

namespace TweetDuck.Dialogs.Settings {
	sealed partial class DialogSettingsManage : Form {
		private enum State {
			Deciding,
			Reset,
			Import,
			Export
		}

		private ProfileManager.Items SelectedItems {
			get => _selectedItems;

			set {
				// this will call events and SetFlag, which also updates the UI
				foreach (KeyValuePair<CheckBox, ProfileManager.Items> kvp in checkBoxMap) {
					kvp.Key.Checked = value.HasFlag(kvp.Value);
				}
			}
		}

		public bool IsRestarting { get; private set; }
		public bool ShouldReloadBrowser { get; private set; }

		private readonly PluginManager plugins;
		private readonly Dictionary<CheckBox, ProfileManager.Items> checkBoxMap = new (4);
		private readonly bool openImportImmediately;

		private State currentState;
		private ProfileManager? importManager;
		private bool requestedRestartFromConfig;

		private ProfileManager.Items _selectedItems = ProfileManager.Items.None;

		public DialogSettingsManage(PluginManager plugins, bool openImportImmediately = false) {
			InitializeComponent();

			this.plugins = plugins;
			this.currentState = State.Deciding;

			this.checkBoxMap[cbProgramConfig] = ProfileManager.Items.UserConfig;
			this.checkBoxMap[cbSystemConfig] = ProfileManager.Items.SystemConfig;
			this.checkBoxMap[cbSession] = ProfileManager.Items.Session;
			this.checkBoxMap[cbPluginData] = ProfileManager.Items.PluginData;

			this.openImportImmediately = openImportImmediately;

			if (openImportImmediately) {
				radioImport.Checked = true;
				btnContinue_Click(null, EventArgs.Empty);
			}
		}

		private void radioDecision_CheckedChanged(object? sender, EventArgs e) {
			btnContinue.Enabled = true;
		}

		private void checkBoxSelection_CheckedChanged(object? sender, EventArgs e) {
			CheckBox cb = (CheckBox) sender!;
			SetFlag(checkBoxMap[cb], cb.Checked);
		}

		private void btnContinue_Click(object? sender, EventArgs e) {
			string file;

			switch (currentState) {
				case State.Deciding:
					// Reset
					if (radioReset.Checked) {
						currentState = State.Reset;

						Text = "Restore Defaults";
						SelectedItems = ProfileManager.Items.UserConfig;
					}

					// Import
					else if (radioImport.Checked) {
						using (OpenFileDialog dialog = new OpenFileDialog {
							AutoUpgradeEnabled = true,
							DereferenceLinks = true,
							Title = "Import TweetDuck Profile",
							Filter = "TweetDuck Profile (*.tdsettings)|*.tdsettings"
						}) {
							if (dialog.ShowDialog() != DialogResult.OK) {
								if (openImportImmediately) {
									Close();
								}

								return;
							}

							file = dialog.FileName;
						}

						importManager = new ProfileManager(file, plugins);
						currentState = State.Import;

						Text = "Import Profile";
						SelectedItems = importManager.FindImportItems();

						foreach (CheckBox cb in checkBoxMap.Keys) {
							cb.Enabled = cb.Checked;
						}
					}

					// Export
					else if (radioExport.Checked) {
						currentState = State.Export;

						Text = "Export Profile";
						btnContinue.Text = "Export Profile";
						SelectedItems = ProfileManager.Items.UserConfig | ProfileManager.Items.PluginData;
					}

					// Continue...
					panelDecision.Visible = false;
					panelSelection.Visible = true;
					Height += panelSelection.Height - panelDecision.Height;
					break;

				case State.Reset:
					if (FormMessage.Warning("Reset TweetDuck Options", "This will reset the selected items. Are you sure you want to proceed?", FormMessage.Yes, FormMessage.No)) {
						App.ConfigManager.ProgramRestartRequested += Config_ProgramRestartRequested;

						if (SelectedItems.HasFlag(ProfileManager.Items.UserConfig)) {
							Program.Config.User.Reset();
						}

						if (SelectedItems.HasFlag(ProfileManager.Items.SystemConfig)) {
							Program.Config.System.Reset();
						}

						App.ConfigManager.ProgramRestartRequested -= Config_ProgramRestartRequested;

						if (SelectedItems.HasFlag(ProfileManager.Items.Session)) {
							ProfileManager.DeleteAuthCookie();
						}

						if (SelectedItems.HasFlag(ProfileManager.Items.PluginData)) {
							Program.Config.Plugins.Reset();

							try {
								Directory.Delete(plugins.PluginDataFolder, true);
							} catch (Exception ex) {
								App.ErrorHandler.HandleException("Profile Reset", "Could not delete plugin data.", true, ex);
							}
						}

						if (requestedRestartFromConfig && FormMessage.Information("Profile Reset", "The application must restart for some of the restored options to take place. Do you want to restart now?", FormMessage.Yes, FormMessage.No)) {
							RestartProgram();
						}

						ShouldReloadBrowser = true;

						DialogResult = DialogResult.OK;
						Close();
					}

					break;

				case State.Import:
					if (importManager!.Import(SelectedItems)) {
						App.ConfigManager.ProgramRestartRequested += Config_ProgramRestartRequested;
						App.ConfigManager.ReloadAll();
						App.ConfigManager.SaveAll();
						App.ConfigManager.ProgramRestartRequested -= Config_ProgramRestartRequested;

						if (requestedRestartFromConfig && FormMessage.Information("Profile Import", "The application must restart for some of the imported options to take place. Do you want to restart now?", FormMessage.Yes, FormMessage.No)) {
							RestartProgram();
						}
					}

					ShouldReloadBrowser = true;

					DialogResult = DialogResult.OK;
					Close();
					break;

				case State.Export:
					using (SaveFileDialog dialog = new SaveFileDialog {
						AddExtension = true,
						AutoUpgradeEnabled = true,
						OverwritePrompt = true,
						DefaultExt = "tdsettings",
						FileName = "TweetDuck.tdsettings",
						Title = "Export TweetDuck Profile",
						Filter = "TweetDuck Profile (*.tdsettings)|*.tdsettings"
					}) {
						if (dialog.ShowDialog() != DialogResult.OK) {
							return;
						}

						file = dialog.FileName;
					}

					new ProfileManager(file, plugins).Export(SelectedItems);

					DialogResult = DialogResult.OK;
					Close();
					break;
			}
		}

		private void btnCancel_Click(object? sender, EventArgs e) {
			DialogResult = DialogResult.Cancel;
			Close();
		}

		private void Config_ProgramRestartRequested(object? sender, EventArgs e) {
			requestedRestartFromConfig = true;
		}

		private void SetFlag(ProfileManager.Items flag, bool enable) {
			_selectedItems = enable ? _selectedItems | flag : _selectedItems & ~flag;
			btnContinue.Enabled = _selectedItems != ProfileManager.Items.None;

			if (currentState == State.Import) {
				btnContinue.Text = "Import Profile";
			}
			else if (currentState == State.Reset) {
				btnContinue.Text = "Restore Defaults";
			}
		}

		private void RestartProgram() {
			IsRestarting = true;
			Program.Restart();
		}
	}
}


text:
var assert = require('assert');
var Type = require('../union-type.js');

function isNumber(n) { return typeof n === 'number'; }

function T() { return true; };

describe('union type', function() {
  it('returns type with constructors', function() {
    var Point = Type({Point: [isNumber, isNumber]});
    assert.equal('function', typeof Point.Point);
  });
  it('constructors create object with fields in array', function() {
    var Point = Type({Point: [isNumber, isNumber]});
    var point = Point.Point(5, 10);
    assert.equal(5, point[0]);
    assert.equal(10, point[1]);
  });
  it('throws if field value does not pass validator', function() {
    var Point = Type({Point: [isNumber, isNumber]});
    assert.throws(function() {
      Point.Point('lol', 10);
    }, /Point/);
  });
  describe('primitives', function() {
    it('accepts strings with primitive constructors', function() {
      var Name = Type({Name: [String]});
      var name = Name.Name('Thumper');
      assert.equal(name[0], 'Thumper');
    });
    it('throws on strings with primitive constructors', function() {
      var Name = Type({Name: [String]});
      assert.throws(function() {
        var name = Name.Name(12);
      }, /Name/);
    });
    it('accepts number with primitive constructors', function() {
      var Age = Type({Age: [Number]});
      assert.equal(Age.Age(12)[0], 12);
    });
    it('throws on number with primitive constructors', function() {
      var Age = Type({Age: [Number]});
      assert.throws(function() {
        Age.Age('12');
      }, /wrong value/);
    });
  });
  it('nest types', function() {
    var Point = Type({Point: [isNumber, isNumber]});
    var Shape = Type({Circle: [Number, Point],
                      Rectangle: [Point, Point]});
    var square = Shape.Rectangle(Point.Point(1, 1), Point.Point(4, 4));
  });
  it('throws if field value is not of correct type', function() {
    var Length = Type({Length: [isNumber]});
    var Shape = Type({Rectangle: [Length, Length]});
    assert.throws(function() {
      Shape.Rectangle(1, Length.Length(12));
    }, /Rectangle/);
  });
  describe('case', function() {
    var Action = Type({Translate: [isNumber, isNumber], Rotate: [isNumber]});
    var sum = Action.case({
      Translate: function(x, y) {
        return x + y;
      },
      Rotate: function(n) { return n; },
    });
    it('works on types', function() {
      assert.equal(sum(Action.Translate(10, 8)), 18);
      assert.equal(sum(Action.Rotate(30)), 30);
    });
    it('throws on incorrect type', function() {
      var AnotherAction = Type({Translate: [Number]});
      assert.throws(function() {
        sum(AnotherAction.Translate(12));
      }, /wrong type/);
    });
    it('calls back to placeholder', function() {
      var called = false;
      var fn = Action.case({
        Translate: function() { throw new Error(); },
        _: function() { called = true; }
      });
      fn(Action.Rotate(30));
    });
    it('throws if no case handler found', function() {
      var called = false;
      var fn = Action.case({
        Translate: function() { throw new Error(); },
      });
      assert.throws(function() {
        fn(Action.Rotate(30));
      }, /unhandled/);
    });
  });
  describe('recursive data types', function() {
    var List = Type({Nil: [], Cons: [T, List]});
    it('can create single element list', function() {
      var list = List.Cons(1, List.Nil());
    });
    it('can get head', function() {
      var list = List.Cons(1, List.Cons(2, List.Cons(3, List.Nil())));
      function head(list) { return list[0]; }
      function tail(list) { return list[1]; }
      var toString = List.case({
        Cons: function(head, tail) { return head + ' : ' + toString(tail); },
        Nil: function() { return 'Nil'; }
      });
      assert.equal(toString(list), '1 : 2 : 3 : Nil');
    });
  });
});


text:
package com.aspose.imaging.examples.metafile;

import com.aspose.imaging.examples.Utils;
import com.aspose.imaging.imageoptions.PdfOptions;

public class ConvertEMFtoPDF
{
    public static void main(String... args)
    {
        //ExStart:ConvertEMFtoPDF
        String dataDir = Utils.getSharedDataDir() + "metafile/";
        String[] filePaths = new String[]{dataDir + "FilledRectangleRotateMode_c.emf", dataDir + "image5.emf",
                dataDir + "LinearGradientBrushCircuitMode.emf", dataDir + "Picture1.emf",
                dataDir + "test.emf", dataDir + "wrong-font-size.emf"};

        for (String filePath : filePaths)
        {
            String outPath = filePath + ".pdf";

            com.aspose.imaging.fileformats.emf.EmfImage image = (com.aspose.imaging.fileformats.emf.EmfImage) com.aspose.imaging.fileformats.emf.EmfImage.load(filePath);
            try
            {
                com.aspose.imaging.system.io.FileStream outputStream = new com.aspose.imaging.system.io.FileStream(
                        outPath, com.aspose.imaging.system.io.FileMode.Create);
                try
                {
                    if (!image.getHeader().getEmfHeader().getValid())
                    {
                        throw new com.aspose.imaging.coreexceptions.ImageLoadException(
                                "The file" + outPath + " is not valid");
                    }

                    com.aspose.imaging.imageoptions.EmfRasterizationOptions emfRasterization = new com.aspose.imaging.imageoptions.EmfRasterizationOptions();

                    emfRasterization.setPageWidth(image.getWidth());
                    emfRasterization.setPageHeight(image.getHeight());
                    emfRasterization.setBackgroundColor(com.aspose.imaging.Color.getWhiteSmoke());

                    PdfOptions pdfOptions = new PdfOptions();
                    pdfOptions.setVectorRasterizationOptions(emfRasterization);

                    image.save(outputStream.toOutputStream(), pdfOptions);
                }
                finally
                {
                    outputStream.close();
                }
            }
            finally
            {
                image.dispose();
            }
        }
        //ExEnd:ConvertEMFtoPDF
    }

}


text:
<?xml version="1.0" encoding="utf-8"?><!--

-->

<!-- The attributes in this XML file provide configuration information --><!-- for the Search Manager. -->

<input-method />


text:
num: "lect01"
lecture_date: 2017-04-04
desc: "Welcome"
ready: true
pdfurl: http://andrewduncan.net/cs32/lectures/lecture_1.pdf
---

First lecture of course.

Content is on the slides linked to above.


text:
@echo on

if NOT EXIST C:\projects\tools (
  mkdir C:\projects\tools
)
cd C:\projects\tools

::###########################################################################
:: Setup Compiler
::###########################################################################
if NOT EXIST llvm-installer.exe (
    appveyor DownloadFile http://prereleases.llvm.org/win-snapshots/LLVM-5.0.0-r306282-win32.exe -FileName llvm-installer.exe
)

START /WAIT llvm-installer.exe /S /D=C:\"projects\tools\LLVM-install"
@set PATH="C:\projects\tools\LLVM-install\bin";%PATH%
clang-cl -v

if DEFINED MINGW_PATH rename "C:\Program Files\Git\usr\bin\sh.exe" "sh-ignored.exe"
if DEFINED MINGW_PATH @set "PATH=%PATH:C:\Program Files (x86)\Git\bin=%"
if DEFINED MINGW_PATH @set "PATH=%PATH%;%MINGW_PATH%"
if DEFINED MINGW_PATH g++ -v

::###########################################################################
:: Install a recent CMake
::###########################################################################
if NOT EXIST cmake (
  appveyor DownloadFile https://cmake.org/files/v3.7/cmake-3.7.2-win64-x64.zip -FileName cmake.zip
  7z x cmake.zip -oC:\projects\tools > nul
  move C:\projects\tools\cmake-* C:\projects\tools\cmake
  rm cmake.zip
)
@set PATH=C:\projects\tools\cmake\bin;%PATH%
cmake --version

::###########################################################################
:: Install Ninja
::###########################################################################
if NOT EXIST ninja (
  appveyor DownloadFile https://github.com/ninja-build/ninja/releases/download/v1.6.0/ninja-win.zip -FileName ninja.zip
  7z x ninja.zip -oC:\projects\tools\ninja > nul
  rm ninja.zip
)
@set PATH=C:\projects\tools\ninja;%PATH%
ninja --version

@echo off


text:
package rabbitmq.src.main.java.cn.itcast.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import rabbitmq.src.main.java.cn.itcast.rabbitmq.util.ConnectionUtil;

public class Recv {

    private final static String QUEUE_NAME = "test_queue";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);

        // 获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
        }
    }
}


text:
namespace internal {

void CalcFivePortPressures(double air_density, double port_angle,
                           const Vec3 &apparent_wind_p, double *p_dynamic,
                           double *p_alpha, double *p_beta);

void CalcInflowFromRotorsAtPitot(double air_density, double thrust,
                                 double freestream_vel,
                                 const PitotSimParams &params, Vec3 *inflow_b);

}  // namespace internal

TEST(CalcFivePortPressures, Normal) {
  double air_density = 1.2;
  double airspeed = 20.0;
  double dynamic_pressure = 0.5 * air_density * airspeed * airspeed;
  Vec3 apparent_wind_w = {-airspeed, 0.0, 0.0};
  for (double alpha = -0.5; alpha <= 0.5; alpha += 0.1) {
    for (double beta = -0.5; alpha <= 0.5; alpha += 0.1) {
      Vec3 apparent_wind_b;
      RotWToB(&apparent_wind_w, alpha, beta, &apparent_wind_b);
      double p_dynamic, p_alpha, p_beta;
      internal::CalcFivePortPressures(air_density, PI / 4.0, apparent_wind_b,
                                      &p_dynamic, &p_alpha, &p_beta);
      EXPECT_NEAR(p_dynamic,
                  dynamic_pressure * (1.0 -
                                      (9.0 / 4.0) * (sin(alpha) * sin(alpha) *
                                                         cos(beta) * cos(beta) +
                                                     sin(beta) * sin(beta))),
                  1e-9);
      EXPECT_NEAR(p_alpha, dynamic_pressure * (9.0 / 4.0) * cos(beta) *
                               cos(beta) * sin(2.0 * alpha),
                  1e-9);
      EXPECT_NEAR(p_beta,
                  dynamic_pressure * (9.0 / 4.0) * cos(alpha) * sin(2.0 * beta),
                  1e-9);
    }
  }
}

// Tests that we calculate a reasonable inflow velocity during hover.
TEST(CalcInflowFromRotorsAtPitot, Hover) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];

  // Calculate the inflow velocity under typical hover conditions.
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.176, 22000.0, 20.0, params,
                                        &inflow_b);

  // This is a rough estimate of what the inflow should be based on
  // CFD simulations which were correlated to Pitot data from the
  // 2016-08-16 hover test.
  Vec3 expected_inflow_b = {-2.8, 0.0, 0.0};

  EXPECT_NEAR_VEC3(expected_inflow_b, inflow_b, 0.2);
}

TEST(CalcInflowFromRotorsAtPitot, NegativeXInflowDuringThrustingClimb) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.2, 17000.0, 10.0, params, &inflow_b);
  EXPECT_LT(inflow_b.x, 0.0);
}

TEST(CalcInflowFromRotorsAtPitot, NegativeXInflowDuringThrustingFall) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.2, 17000.0, -10.0, params, &inflow_b);
  EXPECT_LT(inflow_b.x, 0.0);
}

TEST(CalcInflowFromRotorsAtPitot, PositiveXInflowDuringDraggingClimb) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.2, -17000.0, 10.0, params, &inflow_b);
  EXPECT_GT(inflow_b.x, 0.0);
}

TEST(CalcInflowFromRotorsAtPitot, PositiveXInflowDuringDraggingFall) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.2, -17000.0, -10.0, params,
                                        &inflow_b);
  EXPECT_GT(inflow_b.x, 0.0);
}

// Tests that the inflow of the rotors does not have a large effect at
// high crosswind speeds.
TEST(CalcInflowFromRotorsAtPitot, Crosswind) {
  const PitotSimParams &params = GetSimParams()->pitots_sim[0];

  // Calculate the inflow velocity under typical crosswind conditions.
  Vec3 inflow_b;
  internal::CalcInflowFromRotorsAtPitot(1.2, 5000.0, 60.0, params, &inflow_b);

  // We expect relatively low inflows under crosswind conditions.
  EXPECT_NEAR_VEC3(kVec3Zero, inflow_b, 1.0);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
package us.koller.cameraroll.data.fileOperations;

import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import java.io.File;

import us.koller.cameraroll.R;
import us.koller.cameraroll.data.models.File_POJO;
import us.koller.cameraroll.util.StorageUtil;

public class NewDirectory extends FileOperation {

    @Override
    String getNotificationTitle() {
        return getString(R.string.new_folder);
    }

    @Override
    public int getNotificationSmallIconRes() {
        return R.drawable.ic_create_new_folder_white_24dp;
    }

    @Override
    public void execute(Intent workIntent) {
        final File_POJO[] files = getFiles(workIntent);
        if (files.length > 0) {
            final File_POJO file = files[0];

            //check if file is on removable storage
            boolean writingOntoRemovableStorage = Util.isOnRemovableStorage(file.getPath());

            Uri treeUri = null;
            if (writingOntoRemovableStorage) {
                treeUri = getTreeUri(workIntent, null);
                if (treeUri == null) {
                    return;
                }
            }

            boolean result;
            if (!writingOntoRemovableStorage) {
                result = createNewFolder(file.getPath());
            } else {
                result = StorageUtil.createDocumentDir(getApplicationContext(), treeUri, file.getPath()) != null;
            }

            if (!result) {
                sendFailedBroadcast(workIntent, file.getPath());
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), getString(R.string.successfully_created_new_folder), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    @Override
    public int getType() {
        return FileOperation.NEW_DIR;
    }

    private static boolean createNewFolder(String newFolderPath) {
        File dir = new File(newFolderPath);
        return !dir.exists() && dir.mkdirs();
    }
}


text:
int GetMaxShapeSerializedSize() {
    return GetTriangleMeshSerializedSize();
}

void Shape::SetAreaLight(const AreaLight *areaLight) {
    this->areaLight = areaLight;
}

const ADFloat *Intersect(const ADFloat *buffer,
                         const ADRay &ray,
                         const ADFloat time,
                         const bool isStatic,
                         ADIntersection &isect,
                         ADVector2 &st) {
    ADFloat type;
    buffer = Deserialize(buffer, type);
    std::vector<CondExprCPtr> ret = CreateCondExprVec(11);
    BeginIf(Eq(type, (Float)ShapeType::TriangleMesh), ret);
    {
        ADIntersection isect;
        IntersectTriangleMesh(buffer, ray, time, isStatic, isect, st);
        SetCondOutput({isect.position[0],
                       isect.position[1],
                       isect.position[2],
                       isect.geomNormal[0],
                       isect.geomNormal[1],
                       isect.geomNormal[2],
                       isect.shadingNormal[0],
                       isect.shadingNormal[1],
                       isect.shadingNormal[2],
                       st[0],
                       st[1]});
    }
    BeginElse();
    {
        SetCondOutput({Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0)});
    }
    EndIf();
    isect.position[0] = ret[0];
    isect.position[1] = ret[1];
    isect.position[2] = ret[2];
    isect.geomNormal[0] = ret[3];
    isect.geomNormal[1] = ret[4];
    isect.geomNormal[2] = ret[5];
    isect.shadingNormal[0] = ret[6];
    isect.shadingNormal[1] = ret[7];
    isect.shadingNormal[2] = ret[8];
    st[0] = ret[9];
    st[1] = ret[10];
    buffer += (GetMaxShapeSerializedSize() - 1);
    return buffer;
}

void SampleShape(const ADFloat *buffer,
                 const ADVector2 rndParam,
                 const ADFloat time,
                 const bool isStatic,
                 ADVector3 &position,
                 ADVector3 &normal,
                 ADFloat &pdf) {
    ADFloat type;
    buffer = Deserialize(buffer, type);
    std::vector<CondExprCPtr> ret = CreateCondExprVec(7);
    BeginIf(Eq(type, (Float)ShapeType::TriangleMesh), ret);
    {
        ADVector3 position;
        ADVector3 normal;
        ADFloat pdf;
        SampleTriangleMesh(buffer, rndParam, time, isStatic, position, normal, pdf);
        SetCondOutput(
            {position[0], position[1], position[2], normal[0], normal[1], normal[2], pdf});
    }
    BeginElse();
    {
        SetCondOutput({Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0)});
    }
    EndIf();
    position[0] = ret[0];
    position[1] = ret[1];
    position[2] = ret[2];
    normal[0] = ret[3];
    normal[1] = ret[4];
    normal[2] = ret[5];
    pdf = ret[6];
}

const ADFloat *SampleShapePdf(const ADFloat *buffer, ADFloat &shapePdf) {
    ADFloat type;
    buffer = Deserialize(buffer, type);
    std::vector<CondExprCPtr> ret = CreateCondExprVec(1);
    BeginIf(Eq(type, (Float)ShapeType::TriangleMesh), ret);
    {
        ADFloat shapePdf = SampleTriangleMeshPdf(buffer);
        SetCondOutput({shapePdf});
    }
    BeginElse();
    { SetCondOutput({Const<ADFloat>(0.0)}); }
    EndIf();
    shapePdf = ret[0];
    buffer += (GetMaxShapeSerializedSize() - 1);
    return buffer;
}


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

<TITLE>
Uses of Class fsb.ast.Branch
</TITLE>

<META NAME="date" CONTENT="2012-04-22">

<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
fsb.ast.Branch

Packages that use Branch

fsb.semantics

Uses of Branch in fsb.semantics

Methods in fsb.semantics with parameters of type Branch

protected  java.util.List<Action>
Semantics.applyBranch(SBState state,
            Branch branch,
            int pid)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import _ from 'lodash'
import update from 'react-addons-update'
import Action from '../actions'

const initialState = {
  list: [],
  items: {},
  item: {
    data: {},
    isLoading: false,
    errorMsg: null
  },
  hasMore: false,
  offset: 0,
  total: 0,
  isLoading: false,
  errorMsg: null
}

export default function (state: Object = initialState, action: Object) {
  switch (action.type) {

    case Action.GET_POSTS:
      return update(state, {
        $merge: {
          isLoading: true,
          isSuccess: false,
          errorMsg: null
        }
      })

    case Action.GET_POSTS_SUCCESS:
      const items = state.items
      action.list.map(v => {
        items[v.id] = v
      })
      const list = _.chain(items).map(v => {
        return {
          id: v.id,
          date: v.date,
          title: v.title
        }
      }).sortBy('date').reverse().value()

      return update(state, {
        $merge: {
          list: list,
          items: items,
          offset: Object.keys(items).length,
          hasMore: (action.list.length === 10),
          total: action.total,
          isLoading: false,
          errorMsg: null
        }
      })

    case Action.GET_POSTS_FAILED:
      return update(state, {
        $merge: {
          isLoading: false,
          isSuccess: false,
          errorMsg: action.error
        }
      })

    case Action.GET_POST:
      return update(state, {
        item: {$merge: {
          isLoading: true,
          isSuccess: false,
          errorMsg: null
        }}
      })

    case Action.GET_POST_SUCCESS:
      return update(state, {
        item: {$merge: {
          data: action.item,
          isLoading: false,
          isSuccess: true,
          errorMsg: null
        }},
        items: {
          [action.item.id]: {$set: action.item}
        }
      })

    case Action.GET_POST_FAILED:
      return update(state, {
        item: {$merge: {
          isLoading: true,
          isSuccess: false,
          errorMsg: action.error
        }}
      })

    default:
      return state
  }
}


text:
@interface ShareViewController () <UITableViewDataSource, UITableViewDelegate, UITextViewDelegate>

@property NYSegmentedControl *segmentedControl;
@property UITableView *tableView;

@property UITextField *titleTextField;
@property UITextField *urlTextField;
@property UITextView *postTextView;

@end

static NSString * const kTextFieldTableViewCellIdentifier = @"TextFieldTableViewCell";
static NSString * const kTextViewTableViewCellIdentifier = @"TextViewTableViewCell";

@implementation ShareViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [self.tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        [self.tableView registerClass:[HFTextFieldTableViewCell class] forCellReuseIdentifier:kTextFieldTableViewCellIdentifier];
        [self.tableView registerClass:[HFTextViewTableViewCell class] forCellReuseIdentifier:kTextViewTableViewCellIdentifier];
        [self.view addSubview:self.tableView];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_tableView]|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(_tableView)]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_tableView]|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(_tableView)]];

        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                target:self
                                                                                action:@selector(cancelButtonPressed:)];

        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Submit", nil)
                                                                                style:UIBarButtonItemStyleDone
                                                                                target:self
                                                                                action:@selector(submitButtonPressed:)];
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.segmentedControl = [[NYSegmentedControl alloc] initWithItems:@[NSLocalizedString(@"Link", nil), NSLocalizedString(@"Text", nil)]];
    [self.segmentedControl addTarget:self action:@selector(segmentSelected:) forControlEvents:UIControlEventValueChanged];
    self.segmentedControl.backgroundColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
    self.segmentedControl.segmentIndicatorBackgroundColor = [UIColor whiteColor];
    self.segmentedControl.segmentIndicatorInset = 0.0f;
    self.segmentedControl.titleTextColor = [UIColor lightGrayColor];
    self.segmentedControl.selectedTitleTextColor = [UIColor darkGrayColor];
    self.segmentedControl.selectedTitleFont = [UIFont semiboldApplicationFontOfSize:14.0f];
    self.segmentedControl.titleFont = [UIFont applicationFontOfSize:14.0f];
    [self.segmentedControl sizeToFit];
    self.segmentedControl.cornerRadius = CGRectGetHeight(self.segmentedControl.frame) / 2.0f;
    self.navigationItem.titleView = self.segmentedControl;
}

- (void)cancelButtonPressed:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)submitButtonPressed:(id)sender {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        [[HNManager sharedManager] submitPostWithTitle:self.titleTextField.text
                                                  link:self.urlTextField.text
                                                  text:nil
                                            completion:^(BOOL success) {
                                                if (success) {
                                                    [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Link submitted", nil)];
                                                    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                                                } else {
                                                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Error submitting link", nil)];
                                                }
                                            }];
    } else {
        [[HNManager sharedManager] submitPostWithTitle:self.titleTextField.text
                                                  link:nil
                                                  text:self.postTextView.text
                                            completion:^(BOOL success) {
                                                if (success) {
                                                    [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Post submitted", nil)];
                                                    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                                                } else {
                                                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Error submitting post", nil)];
                                                }
                                            }];
    }
}

- (void)segmentSelected:(NYSegmentedControl *)sender {
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        if (indexPath.row == 0) {
            HFTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTextFieldTableViewCellIdentifier forIndexPath:indexPath];
            cell.titleLabel.text = NSLocalizedString(@"Title", nil);
            cell.textField.placeholder = NSLocalizedString(@"Show HN: My App", nil);
            self.titleTextField = cell.textField;
            return cell;
        } else {
            HFTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTextFieldTableViewCellIdentifier forIndexPath:indexPath];
            cell.titleLabel.text = NSLocalizedString(@"URL", nil);
            cell.textField.placeholder = NSLocalizedString(@"http://example.com", nil);
            self.urlTextField = cell.textField;
            return cell;
        }
    } else {
        if (indexPath.row == 0) {
            HFTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTextFieldTableViewCellIdentifier forIndexPath:indexPath];
            cell.titleLabel.text = NSLocalizedString(@"Title", nil);

            return cell;
        } else {
            HFTextViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTextViewTableViewCellIdentifier forIndexPath:indexPath];
            cell.textView.delegate = self;
            cell.textView.editable = YES;
            cell.textView.placeholder = NSLocalizedString(@"Post text", nil);
            self.postTextView = cell.textView;

            return cell;
        }
    }
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        return 44.0f;
    } else {
        if (indexPath.row == 0) {
            return 44.0f;
        } else {
            static HFTextViewTableViewCell *textViewMetricsCell;

            if (!textViewMetricsCell) {
                textViewMetricsCell = [tableView dequeueReusableCellWithIdentifier:kTextViewTableViewCellIdentifier];
            }

            textViewMetricsCell.bounds = CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 9999.0f);
            textViewMetricsCell.textView.text = self.postTextView.text;
            [textViewMetricsCell setNeedsLayout];
            [textViewMetricsCell layoutIfNeeded];

            // Get the actual height required for the cell
            CGFloat height = [textViewMetricsCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

            // Add an extra point to the height to account for the cell separator, which is added between the bottom of the cell's contentView and the bottom of the table view cell.
            height += 1;

            return height;
        }
    }
}

# pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // Trigger an update of cell heights so the text view can add a new line if needed
    [self.tableView beginUpdates];
    [self.tableView endUpdates];

    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    } else {
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
        return YES;
    }
}

@end


text:
HELP_STR="sudo $0 <1|0(start|stop)>, ex: sudo $0 1 or sudo $0 0"

function check_input_parameter_empty_error()
{
  if [ -z "$1" ]
  then
    printf "Parameters error! Usage: $HELP_STR\n"
    exit 1
  fi
}

check_input_parameter_empty_error $1;

if [ "$1" -eq 1 ]
then
  DISV="StartDiscovery"
else
  DISV="StopDiscovery"
fi
echo "$DISV"
echo "----------------"

# First you need to get path to the default bluetooth adapter which should appear when you have bluetoothd running and bluetooth device is powered on. Do it like this:
export BTADAPTER=`dbus-send --system --dest=org.bluez --print-reply / org.bluez.Manager.DefaultAdapter | tail -1 | sed 's/^.*"\(.*\)".*$/\1/'`
echo "BTADAPTER=$BTADAPTER"
echo

# To make your device discoverable:
dbus-send --system --print-reply --reply-timeout=2000 --dest=org.bluez $BTADAPTER org.bluez.Adapter.$DISV
echo "----------------"
echo


text:
namespace EleicaoBrasil.Model.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.1-30610")]
    public sealed partial class InitialCreate1 : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate1));

        string IMigrationMetadata.Id
        {
            get { return "201409100003425_InitialCreate1"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
title: Centered Masonry
layout: default
category: custom-layout-modes
---

Modified masonry layout mode for centered container.

  {% include filter-buttons.html %}

  {% include sort-buttons.html %}

Etc

Toggle variable sizes

Insert new elements

Append new elements

Shuffle

  {% for elem_number in site.best_of_order %}
    {% assign element = site.elements[elem_number] %}
    {% include element-partial.html %}
  {% endfor %}


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

import org.archive.modules.ProcessorTestBase;

/**
 * Unit test for {@link CrawlerProcessor}.
 *
 * @author pjack
 */
public abstract class CrawlerProcessorTestBase extends ProcessorTestBase {

    protected CrawlController controller;

    protected void setUp() throws Exception {
        controller = CrawlControllerTest.makeTempCrawlController();
    }

    @Override
    protected void verifySerialization(Object first, byte[] firstBytes,
            Object second, byte[] secondBytes) throws Exception {

    }

    // TODO TESTME!

}


text:
package org.jpasecurity.model;

import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

/**
 * @author Arne Limburg
 */
public class TestEntityListener {

    @PrePersist
    public void publicTestMethod(Object entity) {
        if (entity == null) {
            throw new PublicTestMethodCalledException();
        }
    }

    @PreRemove
    protected void protectedTestMethod(Object entity) {
        if (entity == null) {
            throw new ProtectedTestMethodCalledException();
        }
    }

    @PreUpdate
    void packageProtectedTestMethod(Object entity) {
        if (entity == null) {
            throw new PackageProtectedTestMethodCalledException();
        }
    }

    @SuppressWarnings("unused") // is used by reflection
    private void privateTestMethod(Object entity) {
        if (entity == null) {
            throw new PrivateTestMethodCalledException();
        }
    }

    public static class PublicTestMethodCalledException extends RuntimeException {
    }

    public static class ProtectedTestMethodCalledException extends RuntimeException {
    }

    public static class PackageProtectedTestMethodCalledException extends RuntimeException {
    }

    public static class PrivateTestMethodCalledException extends RuntimeException {
    }
}


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Target-related functions for the XMEGA target's NVM module.
 */

#define  INCLUDE_FROM_XMEGA_NVM_C
#include "XMEGANVM.h"

#if defined(ENABLE_XPROG_PROTOCOL) || defined(__DOXYGEN__)

/** Sends the given 32-bit absolute address to the target.
 *
 *  \param[in] AbsoluteAddress  Absolute address to send to the target
 */
static void XMEGANVM_SendAddress(const uint32_t AbsoluteAddress)
{
	/* Send the given 32-bit address to the target, LSB first */
	XPROGTarget_SendByte(AbsoluteAddress &  0xFF);
	XPROGTarget_SendByte(AbsoluteAddress >> 8);
	XPROGTarget_SendByte(AbsoluteAddress >> 16);
	XPROGTarget_SendByte(AbsoluteAddress >> 24);
}

/** Sends the given NVM register address to the target.
 *
 *  \param[in] Register  NVM register whose absolute address is to be sent
 */
static void XMEGANVM_SendNVMRegAddress(const uint8_t Register)
{
	/* Determine the absolute register address from the NVM base memory address and the NVM register address */
	uint32_t Address = XPROG_Param_NVMBase | Register;

	/* Send the calculated 32-bit address to the target, LSB first */
	XMEGANVM_SendAddress(Address);
}

/** Busy-waits while the NVM controller is busy performing a NVM operation, such as a FLASH page read or CRC
 *  calculation.
 *
 *  \return Boolean true if the NVM controller became ready within the timeout period, false otherwise
 */
bool XMEGANVM_WaitWhileNVMBusBusy(void)
{
	/* Poll the STATUS register to check to see if NVM access has been enabled */
	for (;;)
	{
		/* Send the LDCS command to read the PDI STATUS register to see the NVM bus is active */
		XPROGTarget_SendByte(PDI_CMD_LDCS | PDI_STATUS_REG);

		uint8_t StatusRegister = XPROGTarget_ReceiveByte();

		/* We might have timed out waiting for the status register read response, check here */
		if (TimeoutExpired)
		  return false;

		/* Check the status register read response to see if the NVM bus is enabled */
		if (StatusRegister & PDI_STATUS_NVM)
		  return true;
	}
}

/** Waits while the target's NVM controller is busy performing an operation, exiting if the
 *  timeout period expires.
 *
 *  \return Boolean true if the NVM controller became ready within the timeout period, false otherwise
 */
bool XMEGANVM_WaitWhileNVMControllerBusy(void)
{
	/* Preload the pointer register with the NVM STATUS register address to check the BUSY flag */
	XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_DIRECT << 2) | PDI_DATSIZE_4BYTES);
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_STATUS);

	/* Poll the NVM STATUS register while the NVM controller is busy */
	for (;;)
	{
		/* Fetch the current status value via the pointer register (without auto-increment afterwards) */
		XPROGTarget_SendByte(PDI_CMD_LD | (PDI_POINTER_INDIRECT << 2) | PDI_DATSIZE_1BYTE);

		uint8_t StatusRegister = XPROGTarget_ReceiveByte();

		/* We might have timed out waiting for the status register read response, check here */
		if (TimeoutExpired)
		  return false;

		/* Check to see if the BUSY flag is still set */
		if (!(StatusRegister & (1 << 7)))
		  return true;
	}
}

/** Enables the physical PDI interface on the target and enables access to the internal NVM controller.
 *
 *  \return Boolean true if the PDI interface was enabled successfully, false otherwise
 */
bool XMEGANVM_EnablePDI(void)
{
	/* Enable PDI programming mode with the attached target */
	XPROGTarget_EnableTargetPDI();

	/* Store the RESET key into the RESET PDI register to keep the XMEGA in reset */
	XPROGTarget_SendByte(PDI_CMD_STCS | PDI_RESET_REG);
	XPROGTarget_SendByte(PDI_RESET_KEY);

	/* Lower direction change guard time to 0 USART bits */
	XPROGTarget_SendByte(PDI_CMD_STCS | PDI_CTRL_REG);
	XPROGTarget_SendByte(0x07);

	/* Enable access to the XPROG NVM bus by sending the documented NVM access key to the device */
	XPROGTarget_SendByte(PDI_CMD_KEY);
	for (uint8_t i = sizeof(PDI_NVMENABLE_KEY); i > 0; i--)
	  XPROGTarget_SendByte(PDI_NVMENABLE_KEY[i - 1]);

	/* Wait until the NVM bus becomes active */
	return XMEGANVM_WaitWhileNVMBusBusy();
}

/** Removes access to the target's NVM controller and physically disables the target's physical PDI interface. */
void XMEGANVM_DisablePDI(void)
{
	XMEGANVM_WaitWhileNVMBusBusy();

	/* Clear the RESET key in the RESET PDI register to allow the XMEGA to run */
	XPROGTarget_SendByte(PDI_CMD_STCS | PDI_RESET_REG);
	XPROGTarget_SendByte(0x00);

	/* Do it twice to make sure it takes effect (silicon bug?) */
	XPROGTarget_SendByte(PDI_CMD_STCS | PDI_RESET_REG);
	XPROGTarget_SendByte(0x00);

	XPROGTarget_DisableTargetPDI();
}

/** Retrieves the CRC value of the given memory space.
 *
 *  \param[in]  CRCCommand  NVM CRC command to issue to the target
 *  \param[out] CRCDest     CRC Destination when read from the target
 *
 *  \return Boolean true if the command sequence complete successfully
 */
bool XMEGANVM_GetMemoryCRC(const uint8_t CRCCommand, uint32_t* const CRCDest)
{
	/* Wait until the NVM controller is no longer busy */
	if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
	  return false;

	/* Set the NVM command to the correct CRC read command */
	XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
	XPROGTarget_SendByte(CRCCommand);

	/* Set CMDEX bit in NVM CTRLA register to start the CRC generation */
	XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CTRLA);
	XPROGTarget_SendByte(1 << 0);

	/* Wait until the NVM bus is ready again */
	if (!(XMEGANVM_WaitWhileNVMBusBusy()))
	  return false;

	/* Wait until the NVM controller is no longer busy */
	if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
	  return false;

	/* Load the PDI pointer register with the DAT0 register start address */
	XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_DIRECT << 2) | PDI_DATSIZE_4BYTES);
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_DAT0);

	/* Send the REPEAT command to grab the CRC bytes */
	XPROGTarget_SendByte(PDI_CMD_REPEAT | PDI_DATSIZE_1BYTE);
	XPROGTarget_SendByte(XMEGA_CRC_LENGTH - 1);

	/* Read in the CRC bytes from the target */
	XPROGTarget_SendByte(PDI_CMD_LD | (PDI_POINTER_INDIRECT_PI << 2) | PDI_DATSIZE_1BYTE);
	for (uint8_t i = 0; i < XMEGA_CRC_LENGTH; i++)
	  ((uint8_t*)CRCDest)[i] = XPROGTarget_ReceiveByte();

	return (TimeoutExpired == false);
}

/** Reads memory from the target's memory spaces.
 *
 *  \param[in]  ReadAddress  Start address to read from within the target's address space
 *  \param[out] ReadBuffer   Buffer to store read data into
 *  \param[in]  ReadSize     Number of bytes to read
 *
 *  \return Boolean true if the command sequence complete successfully
 */
bool XMEGANVM_ReadMemory(const uint32_t ReadAddress, uint8_t* ReadBuffer, uint16_t ReadSize)
{
	/* Wait until the NVM controller is no longer busy */
	if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
	  return false;

	/* Send the READNVM command to the NVM controller for reading of an arbitrary location */
	XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
	XPROGTarget_SendByte(XMEGA_NVM_CMD_READNVM);

	/* Load the PDI pointer register with the start address we want to read from */
	XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_DIRECT << 2) | PDI_DATSIZE_4BYTES);
	XMEGANVM_SendAddress(ReadAddress);

	/* Send the REPEAT command with the specified number of bytes to read */
	XPROGTarget_SendByte(PDI_CMD_REPEAT | PDI_DATSIZE_1BYTE);
	XPROGTarget_SendByte(ReadSize - 1);

	/* Send a LD command with indirect access and post-increment to read out the bytes */
	XPROGTarget_SendByte(PDI_CMD_LD | (PDI_POINTER_INDIRECT_PI << 2) | PDI_DATSIZE_1BYTE);
	while (ReadSize-- && !(TimeoutExpired))
	  *(ReadBuffer++) = XPROGTarget_ReceiveByte();

	return (TimeoutExpired == false);
}

/** Writes byte addressed memory to the target's memory spaces.
 *
 *  \param[in]  WriteCommand  Command to send to the device to write each memory byte
 *  \param[in]  WriteAddress  Address to write to within the target's address space
 *  \param[in]  Byte          Byte to write to the target
 *
 *  \return Boolean true if the command sequence complete successfully
 */
bool XMEGANVM_WriteByteMemory(const uint8_t WriteCommand, const uint32_t WriteAddress, const uint8_t Byte)
{
	/* Wait until the NVM controller is no longer busy */
	if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
	  return false;

	/* Send the memory write command to the target */
	XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
	XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
	XPROGTarget_SendByte(WriteCommand);

	/* Send new memory byte to the memory of the target */
	XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
	XMEGANVM_SendAddress(WriteAddress);
	XPROGTarget_SendByte(Byte);

	return true;
}

/** Writes page addressed memory to the target's memory spaces.
 *
 *  \param[in]  WriteBuffCommand  Command to send to the device to write a byte to the memory page buffer
 *  \param[in]  EraseBuffCommand  Command to send to the device to erase the memory page buffer
 *  \param[in]  WritePageCommand  Command to send to the device to write the page buffer to the destination memory
 *  \param[in]  PageMode          Bitfield indicating what operations need to be executed on the specified page
 *  \param[in]  WriteAddress      Start address to write the page data to within the target's address space
 *  \param[in]  WriteBuffer       Buffer to source data from
 *  \param[in]  WriteSize         Number of bytes to write
 *
 *  \return Boolean true if the command sequence complete successfully
 */
bool XMEGANVM_WritePageMemory(const uint8_t WriteBuffCommand, const uint8_t EraseBuffCommand,
                              const uint8_t WritePageCommand, const uint8_t PageMode, const uint32_t WriteAddress,
                              const uint8_t* WriteBuffer, uint16_t WriteSize)
{
	if (PageMode & XPRG_PAGEMODE_ERASE)
	{
		/* Wait until the NVM controller is no longer busy */
		if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
		  return false;

		/* Send the memory buffer erase command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(EraseBuffCommand);

		/* Set CMDEX bit in NVM CTRLA register to start the buffer erase */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CTRLA);
		XPROGTarget_SendByte(1 << 0);
	}

	if (WriteSize)
	{
		/* Wait until the NVM controller is no longer busy */
		if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
		  return false;

		/* Send the memory buffer write command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(WriteBuffCommand);

		/* Load the PDI pointer register with the start address we want to write to */
		XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_DIRECT << 2) | PDI_DATSIZE_4BYTES);
		XMEGANVM_SendAddress(WriteAddress);

		/* Send the REPEAT command with the specified number of bytes to write */
		XPROGTarget_SendByte(PDI_CMD_REPEAT | PDI_DATSIZE_1BYTE);
		XPROGTarget_SendByte(WriteSize - 1);

		/* Send a ST command with indirect access and post-increment to write the bytes */
		XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_INDIRECT_PI << 2) | PDI_DATSIZE_1BYTE);
		while (WriteSize--)
		  XPROGTarget_SendByte(*(WriteBuffer++));
	}

	if (PageMode & XPRG_PAGEMODE_WRITE)
	{
		/* Wait until the NVM controller is no longer busy */
		if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
		  return false;

		/* Send the memory write command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(WritePageCommand);

		/* Send the address of the first page location to write the memory page */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendAddress(WriteAddress);
		XPROGTarget_SendByte(0x00);
	}

	return true;
}

/** Erases a specific memory space of the target.
 *
 *  \param[in] EraseCommand  NVM erase command to send to the device
 *  \param[in] Address       Address inside the memory space to erase
 *
 *  \return Boolean true if the command sequence complete successfully
 */
bool XMEGANVM_EraseMemory(const uint8_t EraseCommand, const uint32_t Address)
{
	/* Wait until the NVM controller is no longer busy */
	if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
	  return false;

	/* EEPROM and Chip erasures are triggered differently to FLASH section erasures */
	if (EraseCommand == XMEGA_NVM_CMD_CHIPERASE)
	{
		/* Send the memory erase command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(EraseCommand);

		/* Set CMDEX bit in NVM CTRLA register to start the erase sequence */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CTRLA);
		XPROGTarget_SendByte(1 << 0);
	}
	else if (EraseCommand == XMEGA_NVM_CMD_ERASEEEPROM)
	{
		/* Send the EEPROM page buffer erase command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(XMEGA_NVM_CMD_ERASEEEPROMPAGEBUFF);

		/* Set CMDEX bit in NVM CTRLA register to start the buffer erase */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CTRLA);
		XPROGTarget_SendByte(1 << 0);

		/* Wait until the NVM controller is no longer busy */
		if (!(XMEGANVM_WaitWhileNVMControllerBusy()))
		  return false;

		/* Send the EEPROM memory buffer write command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(XMEGA_NVM_CMD_LOADEEPROMPAGEBUFF);

		/* Load the PDI pointer register with the EEPROM page start address */
		XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_DIRECT << 2) | PDI_DATSIZE_4BYTES);
		XMEGANVM_SendAddress(Address);

		/* Send the REPEAT command with the specified number of bytes to write */
		XPROGTarget_SendByte(PDI_CMD_REPEAT | PDI_DATSIZE_1BYTE);
		XPROGTarget_SendByte(XPROG_Param_EEPageSize - 1);

		/* Send a ST command with indirect access and post-increment to tag each byte in the EEPROM page buffer */
		XPROGTarget_SendByte(PDI_CMD_ST | (PDI_POINTER_INDIRECT_PI << 2) | PDI_DATSIZE_1BYTE);
		for (uint8_t PageByte = 0; PageByte < XPROG_Param_EEPageSize; PageByte++)
		  XPROGTarget_SendByte(0x00);

		/* Send the memory erase command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(EraseCommand);

		/* Set CMDEX bit in NVM CTRLA register to start the EEPROM erase sequence */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CTRLA);
		XPROGTarget_SendByte(1 << 0);
	}
	else
	{
		/* Send the memory erase command to the target */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendNVMRegAddress(XMEGA_NVM_REG_CMD);
		XPROGTarget_SendByte(EraseCommand);

		/* Other erase modes just need us to address a byte within the target memory space */
		XPROGTarget_SendByte(PDI_CMD_STS | (PDI_DATSIZE_4BYTES << 2));
		XMEGANVM_SendAddress(Address);
		XPROGTarget_SendByte(0x00);
	}

	/* Wait until the NVM bus is ready again */
	if (!(XMEGANVM_WaitWhileNVMBusBusy()))
	  return false;

	return true;
}

#endif


text:
package org.osmdroid.tileprovider.modules;

public interface INetworkAvailablityCheck {

	boolean getNetworkAvailable();

	boolean getWiFiNetworkAvailable();

	boolean getCellularDataNetworkAvailable();

	boolean getRouteToPathExists(int hostAddress);
}