text:
"""
Author: Dr. John T. Hwang <hwangjt@umich.edu>

This package is distributed under New BSD license.
"""
import numpy as np
import scipy.sparse
from numbers import Integral

from smt.utils.linear_solvers import get_solver, LinearSolver, VALID_SOLVERS
from smt.utils.line_search import get_line_search_class, LineSearch, VALID_LINE_SEARCHES
from smt.utils.caching import cached_operation
from smt.surrogate_models.surrogate_model import SurrogateModel

class RMTS(SurrogateModel):
    """
    Regularized Minimal-energy Tensor-product Spline interpolant base class for RMTC and RMTB.
    """

    name = "RMTS"

    def _initialize(self):
        super(RMTS, self)._initialize()
        declare = self.options.declare
        supports = self.supports

        declare(
            "xlimits",
            types=np.ndarray,
            desc="Lower/upper bounds in each dimension - ndarray [nx, 2]",
        )
        declare(
            "smoothness",
            1.0,
            types=(Integral, float, tuple, list, np.ndarray),
            desc="Smoothness parameter in each dimension - length nx. None implies uniform",
        )
        declare(
            "regularization_weight",
            1e-14,
            types=(Integral, float),
            desc="Weight of the term penalizing the norm of the spline coefficients."
            + " This is useful as an alternative to energy minimization "
            + " when energy minimization makes the training time too long.",
        )
        declare(
            "energy_weight",
            1e-4,
            types=(Integral, float),
            desc="The weight of the energy minimization terms",
        )
        declare(
            "extrapolate",
            False,
            types=bool,
            desc="Whether to perform linear extrapolation for external evaluation points",
        )
        declare(
            "min_energy",
            True,
            types=bool,
            desc="Whether to perform energy minimization",
        )
        declare(
            "approx_order", 4, types=Integral, desc="Exponent in the approximation term"
        )
        declare(
            "solver",
            "krylov",
            values=VALID_SOLVERS,
            types=LinearSolver,
            desc="Linear solver",
        )
        declare(
            "derivative_solver",
            "krylov",
            values=VALID_SOLVERS,
            types=LinearSolver,
            desc="Linear solver used for computing output derivatives (dy_dyt)",
        )
        declare(
            "grad_weight",
            0.5,
            types=(Integral, float),
            desc="Weight on gradient training data",
        )
        declare(
            "solver_tolerance",
            1e-12,
            types=(Integral, float),
            desc="Convergence tolerance for the nonlinear solver",
        )
        declare(
            "nonlinear_maxiter",
            10,
            types=Integral,
            desc="Maximum number of nonlinear solver iterations",
        )
        declare(
            "line_search",
            "backtracking",
            values=VALID_LINE_SEARCHES,
            types=LineSearch,
            desc="Line search algorithm",
        )
        declare(
            "save_energy_terms",
            False,
            types=bool,
            desc="Whether to cache energy terms in the data_dir directory",
        )
        declare(
            "data_dir",
            None,
            values=(None,),
            types=str,
            desc="Directory for loading / saving cached data; None means do not save or load",
        )
        declare(
            "max_print_depth",
            5,
            types=Integral,
            desc="Maximum depth (level of nesting) to print operation descriptions and times",
        )

        supports["training_derivatives"] = True
        supports["derivatives"] = True
        supports["output_derivatives"] = True

    def _setup_hessian(self):
        diag = np.ones(self.num["dof"])
        arange = np.arange(self.num["dof"])
        full_hess = scipy.sparse.csc_matrix((diag, (arange, arange)))
        return full_hess

    def _compute_jac(self, ix1, ix2, x):
        data, rows, cols = self._compute_jac_raw(ix1, ix2, x)
        n = x.shape[0]
        full_jac = scipy.sparse.csc_matrix(
            (data, (rows, cols)), shape=(n, self.num["coeff"])
        )
        if self.full_dof2coeff is not None:
            full_jac = full_jac * self.full_dof2coeff
        return full_jac

    def _compute_approx_terms(self):
        # This computes the approximation terms for the training points.
        # We loop over kx: 0 is for values and kx>0 represents.
        # the 1-based index of the derivative given by the training point data.
        num = self.num
        xlimits = self.options["xlimits"]

        full_jac_dict = {}
        for kx in self.training_points[None]:
            xt, yt = self.training_points[None][kx]

            xmin = np.min(xt, axis=0)
            xmax = np.max(xt, axis=0)
            assert np.all(xlimits[:, 0] <= xmin), (
                "Training points below min for %s" % kx
            )
            assert np.all(xlimits[:, 1] >= xmax), (
                "Training points above max for %s" % kx
            )

            if kx == 0:
                c = 1.0
            else:
                self.options["grad_weight"] / xlimits.shape[0]

            full_jac = self._compute_jac(kx, 0, xt)
            full_jac_dict[kx] = (full_jac, full_jac.T.tocsc(), c)

        return full_jac_dict

    def _compute_energy_terms(self):
        # This computes the energy terms that are to be minimized.
        # The quadrature points are the centroids of the multi-dimensional elements.
        num = self.num
        xlimits = self.options["xlimits"]

        inputs = {}
        inputs["nx"] = xlimits.shape[0]
        inputs["elem_list"] = num["elem_list"]
        if self.__class__.__name__ == "RMTB":
            inputs["num_ctrl_list"] = num["ctrl_list"]
            inputs["order_list"] = num["order_list"]

        if self.options["save_energy_terms"]:
            cache_dir = self.options["data_dir"]
        else:
            cache_dir = None
        with cached_operation(inputs, cache_dir) as outputs:
            if outputs:
                sq_mtx = outputs["sq_mtx"]
            else:
                n = np.prod(2 * num["elem_list"])
                x = np.empty(n * num["x"])
                self.rmtsc.compute_quadrature_points(
                    n, np.array(2 * num["elem_list"], dtype=np.int32), x
                )
                x = x.reshape((n, num["x"]))

                sq_mtx = [None] * num["x"]
                for kx in range(num["x"]):
                    mtx = self._compute_jac(kx + 1, kx + 1, x)
                    sq_mtx[kx] = (
                        mtx.T.tocsc() * mtx * (xlimits[kx, 1] - xlimits[kx, 0]) ** 4
                    )

                outputs["sq_mtx"] = sq_mtx

        elem_vol = np.prod((xlimits[:, 1] - xlimits[:, 0]) / (2 * num["elem_list"]))
        total_vol = np.prod(xlimits[:, 1] - xlimits[:, 0])

        full_hess = scipy.sparse.csc_matrix((num["dof"], num["dof"]))
        for kx in range(num["x"]):
            full_hess += sq_mtx[kx] * (
                elem_vol
                / total_vol
                * self.options["smoothness"][kx]
                / (xlimits[kx, 1] - xlimits[kx, 0]) ** 4
            )

        return full_hess

    def _opt_func(self, sol, p, yt_dict):
        full_hess = self.full_hess
        full_jac_dict = self.full_jac_dict

        func = 0.5 * np.dot(sol, full_hess * sol)
        for kx in self.training_points[None]:
            full_jac, full_jac_T, c = full_jac_dict[kx]
            yt = yt_dict[kx]
            func += 0.5 * c * np.sum((full_jac * sol - yt) ** p)

        return func

    def _opt_grad(self, sol, p, yt_dict):
        full_hess = self.full_hess
        full_jac_dict = self.full_jac_dict

        grad = full_hess * sol
        for kx in self.training_points[None]:
            full_jac, full_jac_T, c = full_jac_dict[kx]
            yt = yt_dict[kx]
            grad += 0.5 * c * full_jac_T * p * (full_jac * sol - yt) ** (p - 1)

        return grad

    def _opt_dgrad_dyt(self, sol, p, yt_dict, kx):
        full_hess = self.full_hess
        full_jac_dict = self.full_jac_dict

        full_jac, full_jac_T, c = full_jac_dict[kx]
        yt = yt_dict[kx]

        diag_vec = p * (p - 1) * (full_jac * sol - yt) ** (p - 2)
        diag_mtx = scipy.sparse.diags(diag_vec, format="csc")
        mtx = 0.5 * c * full_jac_T.dot(diag_mtx)

        return -mtx.todense()

    def _opt_hess(self, sol, p, yt_dict):
        full_hess = self.full_hess
        full_jac_dict = self.full_jac_dict

        hess = scipy.sparse.csc_matrix(full_hess)
        for kx in self.training_points[None]:
            full_jac, full_jac_T, c = full_jac_dict[kx]
            yt = yt_dict[kx]

            diag_vec = p * (p - 1) * (full_jac * sol - yt) ** (p - 2)
            diag_mtx = scipy.sparse.diags(diag_vec, format="csc")
            hess += 0.5 * c * full_jac_T * diag_mtx * full_jac

        return hess

    def _opt_norm(self, sol, p, yt_dict):
        full_hess = self.full_hess
        full_jac_dict = self.full_jac_dict

        grad = self._opt_grad(sol, p, yt_dict)
        return np.linalg.norm(grad)

    def _get_yt_dict(self, ind_y):
        yt_dict = {}
        for kx in self.training_points[None]:
            xt, yt = self.training_points[None][kx]
            yt_dict[kx] = yt[:, ind_y]
        return yt_dict

    def _run_newton_solver(self, sol):
        num = self.num
        options = self.options

        solver = get_solver(options["solver"])
        ls_class = get_line_search_class(options["line_search"])

        total_size = int(num["dof"])
        rhs = np.zeros((total_size, num["y"]))
        d_sol = np.zeros((total_size, num["y"]))

        p = self.options["approx_order"]
        for ind_y in range(rhs.shape[1]):

            with self.printer._timed_context("Solving for output %i" % ind_y):

                yt_dict = self._get_yt_dict(ind_y)

                norm = self._opt_norm(sol[:, ind_y], p, yt_dict)
                fval = self._opt_func(sol[:, ind_y], p, yt_dict)
                self.printer(
                    "Iteration (num., iy, grad. norm, func.) : %3i %3i %15.9e %15.9e"
                    % (0, ind_y, norm, fval)
                )

                iter_count = 0
                while (
                    iter_count < options["nonlinear_maxiter"]
                    and norm > options["solver_tolerance"]
                ):
                    with self.printer._timed_context():
                        with self.printer._timed_context("Assembling linear system"):
                            mtx = self._opt_hess(sol[:, ind_y], p, yt_dict)
                            rhs[:, ind_y] = -self._opt_grad(sol[:, ind_y], p, yt_dict)

                        with self.printer._timed_context("Initializing linear solver"):
                            solver._setup(mtx, self.printer)

                        with self.printer._timed_context("Solving linear system"):
                            solver._solve(rhs[:, ind_y], d_sol[:, ind_y], ind_y=ind_y)

                        func = lambda x: self._opt_func(x, p, yt_dict)
                        grad = lambda x: self._opt_grad(x, p, yt_dict)

                        # sol[:, ind_y] += d_sol[:, ind_y]

                        ls = ls_class(sol[:, ind_y], d_sol[:, ind_y], func, grad)
                        with self.printer._timed_context("Performing line search"):
                            sol[:, ind_y] = ls(1.0)

                    norm = self._opt_norm(sol[:, ind_y], p, yt_dict)
                    fval = self._opt_func(sol[:, ind_y], p, yt_dict)
                    self.printer(
                        "Iteration (num., iy, grad. norm, func.) : %3i %3i %15.9e %15.9e"
                        % (iter_count, ind_y, norm, fval)
                    )

                    self.mtx = mtx

                    iter_count += 1

    def _solve(self):
        num = self.num
        options = self.options

        solver = get_solver(options["solver"])
        ls_class = get_line_search_class(options["line_search"])

        total_size = int(num["dof"])
        rhs = np.zeros((total_size, num["y"]))
        sol = np.zeros((total_size, num["y"]))
        d_sol = np.zeros((total_size, num["y"]))

        with self.printer._timed_context(
            "Solving initial startup problem (n=%i)" % total_size
        ):

            approx_order = options["approx_order"]
            nonlinear_maxiter = options["nonlinear_maxiter"]
            options["approx_order"] = 2
            options["nonlinear_maxiter"] = 1

            self._run_newton_solver(sol)

            options["approx_order"] = approx_order
            options["nonlinear_maxiter"] = nonlinear_maxiter

        with self.printer._timed_context(
            "Solving nonlinear problem (n=%i)" % total_size
        ):

            self._run_newton_solver(sol)

        return sol

    def _new_train(self):
        """
        Train the model
        """
        with self.printer._timed_context("Pre-computing matrices", "assembly"):

            with self.printer._timed_context("Computing dof2coeff", "dof2coeff"):
                self.full_dof2coeff = self._compute_dof2coeff()

            with self.printer._timed_context("Initializing Hessian", "init_hess"):
                self.full_hess = (
                    self._setup_hessian() * self.options["regularization_weight"]
                )

            if self.options["min_energy"]:
                with self.printer._timed_context("Computing energy terms", "energy"):
                    self.full_hess += (
                        self._compute_energy_terms() * self.options["energy_weight"]
                    )

            with self.printer._timed_context("Computing approximation terms", "approx"):
                self.full_jac_dict = self._compute_approx_terms()

        with self.printer._timed_context(
            "Solving for degrees of freedom", "total_solution"
        ):
            self.sol = self._solve()

        if self.full_dof2coeff is not None:
            self.sol_coeff = self.full_dof2coeff * self.sol
        else:
            self.sol_coeff = self.sol

    def _train(self):
        """
        Train the model
        """
        self._setup()

        tmp = self.rmtsc
        self.rmtsc = None

        inputs = {"self": self}
        with cached_operation(inputs, self.options["data_dir"]) as outputs:
            self.rmtsc = tmp

            if outputs:
                self.sol_coeff = outputs["sol_coeff"]
                self.sol = outputs["sol"]
                self.mtx = outputs["mtx"]
                self.full_dof2coeff = outputs["full_dof2coeff"]
                self.full_hess = outputs["full_hess"]
                self.full_jac_dict = outputs["full_jac_dict"]
            else:
                self._new_train()
                outputs["sol_coeff"] = self.sol_coeff
                outputs["sol"] = self.sol
                outputs["mtx"] = self.mtx
                outputs["full_dof2coeff"] = self.full_dof2coeff
                outputs["full_hess"] = self.full_hess
                outputs["full_jac_dict"] = self.full_jac_dict

    def _predict_values(self, x):
        """
        Evaluates the model at a set of points.

        Arguments
        ---------
        x : np.ndarray [n_evals, dim]
            Evaluation point input variable values

        Returns
        -------
        y : np.ndarray
            Evaluation point output variable values
        """
        mtx = self._compute_prediction_mtx(x, 0)
        y = mtx.dot(self.sol_coeff)

        return y

    def _predict_derivatives(self, x, kx):
        """
        Evaluates the derivatives at a set of points.

        Arguments
        ---------
        x : np.ndarray [n_evals, dim]
            Evaluation point input variable values
        kx : int
            The 0-based index of the input variable with respect to which derivatives are desired.

        Returns
        -------
        y : np.ndarray
            Derivative values.
        """
        mtx = self._compute_prediction_mtx(x, kx + 1)
        y = mtx.dot(self.sol_coeff)

        return y

    def _compute_prediction_mtx(self, x, kx):
        n = x.shape[0]

        num = self.num
        options = self.options

        data, rows, cols = self._compute_jac_raw(kx, 0, x)

        # In the explanation below, n is the number of dimensions, and
        # a_k and b_k are the lower and upper bounds for x_k.
        #
        # A C1 extrapolation can get very tricky, so we implement a simple C0
        # extrapolation. We basically linarly extrapolate from the nearest
        # domain point. For example, if n = 4 and x2 > b2 and x3 > b3:
        #    f(x1,x2,x3,x4) = f(x1,b2,b3,x4) + dfdx2 (x2-b2) + dfdx3 (x3-b3)
        #    where the derivatives are evaluated at x1,b2,b3,x4 (called b) and
        #    dfdx1|x = dfdx1|b + d2fdx1dx2|b (x2-b2) + d2fdx1dx3|b (x3-b3)
        #    dfdx2|x = dfdx2|b.
        # The dfdx2|x derivative is what it is because f and all derivatives
        # evaluated at x1,b2,b3,x4 are constant with respect to changes in x2.
        # On the other hand, the dfdx1|x derivative is what it is because
        # f and all derivatives evaluated at x1,b2,b3,x4 change with x1.
        # The extrapolation function is non-differentiable at boundaries:
        # i.e., where x_k = a_k or x_k = b_k for at least one k.
        if options["extrapolate"]:

            # First we evaluate the vector pointing to each evaluation points
            # from the nearest point on the domain, in a matrix called dx.
            # If the ith evaluation point is not external, dx[i, :] = 0.
            dx = np.empty(n * num["support"] * num["x"])
            self.rmtsc.compute_ext_dist(n, num["support"], x.flatten(), dx)
            dx = dx.reshape((n * num["support"], num["x"]))

            isexternal = np.array(np.array(dx, bool), float)

            for ix in range(num["x"]):
                # Now we compute the first order term where we have a
                # derivative times (x_k - b_k) or (x_k - a_k).
                data_tmp, rows, cols = self._compute_jac_raw(kx, ix + 1, x)
                data_tmp *= dx[:, ix]

                # If we are evaluating a derivative (with index kx),
                # we zero the first order terms for which dx_k = 0.
                if kx != 0:
                    data_tmp *= 1 - isexternal[:, kx - 1]

                data += data_tmp

        mtx = scipy.sparse.csc_matrix((data, (rows, cols)), shape=(n, num["coeff"]))
        return mtx

    def _predict_output_derivatives(self, x):
        # dy_dyt = dy_dw * (dR_dw)^{-1} * dR_dyt

        n = x.shape[0]
        nw = self.mtx.shape[0]
        nx = x.shape[1]
        ny = self.sol.shape[1]

        p = self.options["approx_order"]

        dy_dw = self._compute_prediction_mtx(x, 0)
        if self.full_dof2coeff is not None:
            dy_dw = dy_dw * self.full_dof2coeff
        dy_dw = dy_dw.todense()

        dR_dw = self.mtx

        dy_dyt = {}
        for kx in self.training_points[None]:
            nt = self.training_points[None][kx][0].shape[0]

            dR_dyt = np.zeros((nw, nt, ny))
            for ind_y in range(ny):
                yt_dict = self._get_yt_dict(ind_y)
                dR_dyt[:, :, ind_y] = self._opt_dgrad_dyt(
                    self.sol[:, ind_y], p, yt_dict, kx
                )

            solver = get_solver(self.options["derivative_solver"])
            solver._setup(dR_dw, self.printer)

            dw_dyt = np.zeros((nw, nt, ny))
            for ind_t in range(nt):
                for ind_y in range(ny):
                    solver._solve(
                        dR_dyt[:, ind_t, ind_y], dw_dyt[:, ind_t, ind_y], ind_y=ind_y
                    )
                    dw_dyt[:, ind_t, ind_y] *= -1.0

            if kx == 0:
                dy_dyt[None] = np.einsum("ij,jkl->ikl", dy_dw, dw_dyt)
            else:
                dy_dyt[kx - 1] = np.einsum("ij,jkl->ikl", dy_dw, dw_dyt)

        return dy_dyt


text:
#ifndef __MBED_NET_SOCKETS_V0_SOCKETADDR_H__
#define __MBED_NET_SOCKETS_V0_SOCKETADDR_H__

#include "sal/socket_types.h"

namespace mbed {
namespace Sockets {
namespace v0 {

class SocketAddr {
public:
    struct socket_addr * getAddr() {return &_addr;}
    const struct socket_addr * getAddr() const {return &_addr;}
    void setAddr(const struct socket_addr *addr);
    void setAddr(const SocketAddr *addr);
    size_t getAddrSize() const {return sizeof(_addr.ipv6be);}
    bool is_v4();

    int fmtIPv4(char *buf, size_t size);
    int fmtIPv6(char *buf, size_t size);
protected:
    struct socket_addr _addr;
};
} // namespace v0
} // namespace Sockets
} // namespace mbed
#endif // __MBED_NET_SOCKETS_V0_SOCKETADDR_H__

redpajama_set_name: RedPajamaGithub


text:
/**
 * Provides distance functions. Distance functions are useful for learning
 * algorithms such as clustering for determining the distance between two
 * objects.
 *
 * @author  Justin Basilico
 * @since   2.0
 */
@gov.sandia.cognition.annotation.Documentation
package gov.sandia.cognition.learning.function.distance;


text:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'chat-bubble',
  templateUrl: 'chat-bubble.html'
})
export class ChatBubbleComponent {

  @Input() content: string;
  @Input() position: string;
  @Input() time: string;
  @Input() name: string;
  @Input() avatar: string;

  constructor() { }
}


text:
void fd_usb_initialize(void);

uint16_t fd_usb_get_vendor_id(void);
uint16_t fd_usb_get_product_id(void);

bool fd_usb_is_powered(void);
bool fd_usb_is_connected(void);
bool fd_usb_is_safe_to_enter_em2(void);

void fd_usb_wake(void);
void fd_usb_sleep(void);

void fd_usb_transfer(void);

#endif


text:
'use strict';

var Q = require('q');
// var log = require('./log');
var sh = require('shelljs');
var spawn = require('cross-spawn');
var chalk = require('chalk');

var Errors = {
  'not.exists': '可执行文件不存在',
  'exec.error': '文件执行出错'
};
var reportError = function (error) {
  console.error(chalk.red(Errors[error.code]));
  console.error(chalk.red('  命令:' + error.cmd));
  console.error(chalk.red('  参数:' + JSON.stringify(error.params)));
  process.exit(1);
};

module.exports = function exec(cmd, params, cwd) {
  var deferred = Q.defer();
  if (!sh.which(cmd)) {
    var errorData = {code: 'not.exists', cmd: cmd, params: params};
    reportError(errorData);
    deferred.reject(errorData);
  } else {
    var child = spawn(cmd, params, {cwd: cwd, stdio: [process.stdin, process.stdout, process.stderr]});
    child.on('error', function (err) {
      reportError({code: 'exec.error', cmd: cmd, params: params});
    });
    child.on('close', function (code) {
      if (code) {
        deferred.reject(code);
      } else {
        deferred.resolve(code);
      }
    });
  }
  return deferred.promise;
};


text:
import uuid

from keystoneauth1 import adapter

from designateclient import exceptions

def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
    """Return a tuple containing the item properties.

    :param item: a single item resource (e.g. Server, Tenant, etc)
    :param fields: tuple of strings with the desired field names
    :param mixed_case_fields: tuple of field names to preserve case
    :param formatters: dictionary mapping field names to callables
        to format the values
    """
    if formatters is None:
        formatters = {}
    row = []

    for field in fields:
        if field in formatters:
            row.append(formatters[field](item))
        else:
            if field in mixed_case_fields:
                field_name = field.replace(' ', '_')
            else:
                field_name = field.lower().replace(' ', '_')
            if not hasattr(item, field_name) and \
                    (isinstance(item, dict) and field_name in item):
                data = item[field_name]
            else:
                data = getattr(item, field_name, '')
            if data is None:
                data = ''
            row.append(data)
    return tuple(row)

def get_columns(data):
    """
    Some row's might have variable count of columns, ensure that we have the
    same.

    :param data: Results in [{}, {]}]
    """
    columns = set()

    def _seen(col):
        columns.add(str(col))

    map(lambda item: map(_seen, list(item.keys())), data)
    return list(columns)

def find_resourceid_by_name_or_id(resource_client, name_or_id):
    """Find resource id from its id or name."""
    try:
        # Try to return an uuid
        return str(uuid.UUID(name_or_id))
    except ValueError:
        # Not an uuid => assume it is resource name
        pass

    resources = resource_client.list()
    candidate_ids = [r['id'] for r in resources if r.get('name') == name_or_id]
    if not candidate_ids:
        raise exceptions.ResourceNotFound(
            'Could not find resource with name "%s"' % name_or_id)
    elif len(candidate_ids) > 1:
        str_ids = ','.join(candidate_ids)
        raise exceptions.NoUniqueMatch(
            'Multiple resources with name "%s": %s' % (name_or_id, str_ids))
    return candidate_ids[0]

class AdapterWithTimeout(adapter.Adapter):
    """adapter.Adapter wraps around a Session.

    The user can pass a timeout keyword that will apply only to
    the Designate Client, in order:

    - timeout keyword passed to ``request()``
    - timeout keyword passed to ``AdapterWithTimeout()``
    - timeout attribute on keystone session
    """
    def __init__(self, *args, **kw):
        self.timeout = kw.pop('timeout', None)
        super(self.__class__, self).__init__(*args, **kw)

    def request(self, *args, **kwargs):
        if self.timeout is not None:
            kwargs.setdefault('timeout', self.timeout)

        return super(AdapterWithTimeout, self).request(*args, **kwargs)


text:
var __slice = [].slice;

(function($) {
  var SVGTracer;
  SVGTracer = (function() {
    SVGTracer.prototype.defaults = {
      duration: '1.3333s',
      easing: 'ease-in-out'
    };

    function SVGTracer(element, options) {
      var _this = this;
      this.options = $.extend({}, this.defaults, options);
      this.isVisible = false;
      this.$element = $(element);
      this.paths = this.$element.find('path, polygon');
      this.paths.each(function(i, path) {
        var length;
        length = _this._getLength(path);
        $(path).css('stroke-dashoffset', length).css('stroke-dasharray', "" + length + " " + length);
        return path.getBoundingClientRect();
      });
    }

    SVGTracer.prototype.play = function(instant) {
      var cssOpts,
        _this = this;
      cssOpts = {};
      cssOpts['transition'] = "stroke-dashoffset " + this.options.duration + " " + this.options.easing;
      cssOpts['stroke-dashoffset'] = '0';
      if (instant) {
        cssOpts['transition'] = 'none';
      }
      this.paths.each(function(i, path) {
        return $(path).css(cssOpts);
      });
      return this.isVisible = true;
    };

    SVGTracer.prototype.reverse = function(instant) {
      var cssOpts,
        _this = this;
      cssOpts = {};
      cssOpts['transition'] = "stroke-dashoffset " + this.options.duration + " " + this.options.easing;
      if (instant) {
        cssOpts['transition'] = 'none';
      }
      this.paths.each(function(i, path) {
        $(path).css(cssOpts);
        return _this._setOffsetToLength(path);
      });
      return this.isVisible = false;
    };

    SVGTracer.prototype.setDuration = function(time) {
      if ((time != null) && typeof time === 'string') {
        return this.options.duration = time;
      } else {
        return $.error("setDuration only accepts Strings, example: 2s");
      }
    };

    SVGTracer.prototype.setEasing = function(easing) {
      if ((easing != null) && typeof easing === 'string') {
        return this.options.easing = easing;
      } else {
        return $.error("setEasing only accepts Strings, example: ease-in-out");
      }
    };

    SVGTracer.prototype._setOffsetToLength = function(path) {
      return $(path).css('stroke-dashoffset', this._getLength(path));
    };

    SVGTracer.prototype._getLength = function(path) {
      var length;
      return length = path.getTotalLength();
    };

    return SVGTracer;

  })();
  return $.fn.extend({
    svgTracer: function() {
      var args, option;
      option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      return this.each(function() {
        var $this, data;
        $this = $(this);
        data = $this.data('svgTracer');
        if (!data) {
          return $this.data('svgTracer', (data = new SVGTracer(this, option)));
        } else if (typeof option === 'string') {
          return data[option].apply(data, args);
        }
      });
    }
  });
})(jQuery);

/*
//@ sourceMappingURL=SVGTracer.js.map
*/


text:
exports.run = (client, message, args) => {
  if (args[0] === "unlock"){
    message.channel.overwritePermissions(message.guild.id, {
      SEND_MESSAGES: null
    }).then(() => {
      message.channel.send("Lockdown lifted.");
    }).catch(error => {
      console.log(error);
    });
  }
  else {
    message.channel.overwritePermissions(message.guild.id, {
      SEND_MESSAGES: false
    }).then(() => {
      message.channel.send("Channel locked down")
        .catch(error => {
          console.log(error);
        });
    });
  }
};
exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ["ld"],
  permLevel: "Moderator"
};

exports.help = {
  name: "lockdown",
  description: "This will lock a channel down for the set duration, be it in hours, minutes or seconds.",
  usage: "lockdown",
  category: "Moderation"
};


text:
FurySim is a (yet another) approach to model fury warrior dps in World of Warcraft v1.12.1.

Given the random nature of rage generation, flurry uptime and procs, it was impossible (for me at least) to model warrior damage accurately in a mathematical way, such as in DPS spreadsheets throughout time.

Thus I set out to create this project to simulate the combat second by second (or centiseconds, rather) to get the most accurate results possible.

## Stuff already in, a.k.a. features

* Character importing from [RealmPlayers](http://www.realmplayers.com)
* Integrates with [wowapi](https://github.com/liekki/wowapi) to automatically calculate vital combat stats (ap/hit/crit/wepskill) from gear
* Simulating with custom item sets (possibility to change items in particular slots)
* Talents (unbridled wrath, flurry, ...), abilities (deathwish, bloodrage, ...), raid buffs, consumables, debuffs
* Enchants (partly), item sets (partly)
	* This needs to be added into [wowapi](https://github.com/liekki/wowapi).
* Preset simulations for +1 additional crit or hit etc. to get weights for additional stats. Great for improving your dibies.
* Combat log and damage composition for debugging purposes

## Stuff yet to be included

* Model procs such as [Crusader](http://db.vanillagaming.org/?spell=20087), [Ironfoe](http://db.vanillagaming.org/?spell=15494) and Crusader etc.
* Take GCD into account (should be fairly trivial)
* Ambient damage (extra rage)
* Multiple passes of actual boss fight simulation (i.e. include execute phase) in addition to free combat simulation

## Installation
Just clone this repo, `npm install`, `bower install` and run `build.sh` and you're done!


text:
// ----------------------------------------------------------------------------
// Copyright (c) Aleksey Nemiro, 2014-2015. All rights reserved.
//
// Licensed 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.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using Nemiro.OAuth;

namespace AspNetWebFormsCustomClient
{

  public class MyFacebookClient : OAuth2Client
  {

    ///
    /// Unique provider name: MyFacebook.
    ///
    public override string ProviderName
    {
      get
      {
        return "MyFacebook";
      }
    }

    ///
    /// Return URL.
    ///
    public override string ReturnUrl
    {
      get
      {
        if (String.IsNullOrEmpty(base.ReturnUrl))
        {
          // default return url
          return "https://www.facebook.com/connect/login_success.html";
        }
        return base.ReturnUrl;
      }
      set
      {
        base.ReturnUrl = value;
      }
    }

    ///
    /// Initializes a new instance of the <see cref="MyFacebookClient"/>.
    ///
    /// <param name="clientId">The App ID obtained from the <see href="https://developers.facebook.com/apps/">Facebook Developers</see>.</param>
    /// <param name="clientSecret">The App Secret obtained from the <see href="https://developers.facebook.com/apps/">Facebook Developers</see>.</param>
    public MyFacebookClient(string clientId, string clientSecret) : base
    (
      "https://www.facebook.com/dialog/oauth",
      "https://graph.facebook.com/oauth/access_token",
      clientId,
      clientSecret
    )
    {
      // scope list
      base.ScopeSeparator = ",";
      base.DefaultScope = "public_profile,email"; //,user_website,user_birthday
    }

    ///
    /// Gets the user details.
    ///
    /// <param name="accessToken">May contain an access token, which will have to be used in obtaining information about the user.</param>
    /// <remarks>
    /// <para>
    /// For more details, please see <see href="https://developers.facebook.com/docs/graph-api/reference/v2.0/user">User</see> method in Guide of Facebook Graph API.
    /// </para>
    /// </remarks>
    /// <returns>
    /// <para>Returns an instance of the <see cref="UserInfo"/> class, containing information about the user.</para>
    /// </returns>
    public override UserInfo GetUserInfo(AccessToken accessToken = null)
    {
      accessToken = base.GetSpecifiedTokenOrCurrent(accessToken);

      // query parameters
      var parameters = new NameValueCollection
      {
        { "access_token" , this.AccessToken["access_token"].ToString() }
      };

      // execute the request
      var result = OAuthUtility.Get("https://graph.facebook.com/me", parameters);

      // field mapping
      var map = new ApiDataMapping();
      map.Add("id", "UserId", typeof(string));
      map.Add("first_name", "FirstName");
      map.Add("last_name", "LastName");
      map.Add("name", "DisplayName");
      map.Add("email", "Email");
      map.Add("link", "Url"); // website
      map.Add("birthday", "Birthday", typeof(DateTime), @"MM\/dd\/yyyy");
      map.Add
      (
        "gender", "Sex",
        delegate(UniValue value)
        {
          if (value.HasValue)
          {
            if (value.Equals("male", StringComparison.OrdinalIgnoreCase))
            {
              return Sex.Male;
            }
            else if (value.Equals("female", StringComparison.OrdinalIgnoreCase))
            {
              return Sex.Female;
            }
          }
          return Sex.None;
        }
      );

      // parse the server response and returns the UserInfo instance
      return new UserInfo(result, map);
    }

  }

}


text:
import LinePlot from './LinePlot';

import LightPowerDist from './LightPowerDist';
import HumanEyeResponse from './HumanEyeResponse';
import MetaResponse from './MetaResponse';
import UserPlot from './UserPlot';

export default class GraphGenerator {
  constructor(parentElem = document.body, beforeElem) {
    this.parentElem = parentElem;
    this.beforeElem = beforeElem;

    // Create ×
    this.multOperator = document.createElement('span');
    this.multOperator.classList.add('operator');
    this.multOperator.innerHTML = '×';

    // Create =
    this.equalOperator = document.createElement('span');
    this.equalOperator.classList.add('operator');
    this.equalOperator.innerHTML = '=';

    // Create
...

    this.graphSetElem = document.createElement('section');
    this.graphSetElem.classList.add('graph');
    this.parentElem.insertBefore(this.graphSetElem, this.beforeElem);

    this.answerButton = document.createElement('button');
    this.answerButton.classList.add('modeButton');
    this.answerButton.textContent = 'Answer';
    this.answerButton.addEventListener('click', (e) => {
      e.preventDefault();

      this.answerButton.classList.add('modeSelected');
      this.drawButton.classList.remove('modeSelected');

      this.userPlot.hide();
      this.meta.show();
      this.meta.plot.refresh();
      this.meta.redraw();
    });

    this.drawButton = document.createElement('button');
    this.drawButton.classList.add('modeButton', 'modeSelected');
    this.drawButton.textContent = 'Draw';
    this.drawButton.addEventListener('click', (e) => {
      e.preventDefault();

      this.drawButton.classList.add('modeSelected');
      this.answerButton.classList.remove('modeSelected');

      this.meta.hide();
      this.userPlot.show();
      this.userPlot.plot.refresh();
    });

    this.modeSwitch = document.createElement('div');
    this.modeSwitch.classList.add('modeToggle');

    this.modeSwitch.appendChild(this.answerButton);
    this.modeSwitch.appendChild(this.drawButton);

    // Insert in the following order:
    // 1. Light Power Distribution Graph (includes dropdown selector)
    // 2. Multiply Sign
    // 3. Human Eye Response Graph
    // 4. Equal Sign
    // 5. Metamerism Response Graph (Hidden)
    // 6. User Drawing Canvas
    // 7. Mode Selector
    this.lpd = new LightPowerDist(this.graphSetElem);
    this.graphSetElem.appendChild(this.multOperator);

    this.her = new HumanEyeResponse(this.graphSetElem);
    this.graphSetElem.appendChild(this.equalOperator);

    this.meta = new MetaResponse(this.graphSetElem, this.lpd.selectorElem);
    this.meta.hide();

    this.userPlot = new UserPlot(this.graphSetElem);
    this.graphSetElem.appendChild(this.modeSwitch);

    // Group all the graphs to synchronize mouse events
    LinePlot.group([this.lpd.plot, this.her.plot, this.meta.plot]);

    return this;
  }
}


text:
ACCEPTED

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

#### Published in
Monogr. Biol. Soc. Pakistan 7: 175 (1978)

#### Original name
Peziza foliacea Schaeff.

### Remarks
null


text: OPAM integration for Coqoon


text:
var assert = requireNative('assert');
var AssertTrue = assert.AssertTrue;
var AssertFalse = assert.AssertFalse;
var utils = require('utils');

function testSuperClass() {
  function SuperClassImpl() {}

  SuperClassImpl.prototype = {
    attrA: 'aSuper',
    attrB: 'bSuper',
    func: function() { return 'func'; },
    superFunc: function() { return 'superFunc'; }
  };

  function SubClassImpl() {
    SuperClassImpl.call(this);
  }

  SubClassImpl.prototype = {
    __proto__: SuperClassImpl.prototype,
    attrA: 'aSub',
    attrC: 'cSub',
    func: function() { return 'overridden'; },
    subFunc: function() { return 'subFunc'; }
  };

  var SuperClass = utils.expose('SuperClass',
                                SuperClassImpl,
                                { functions: ['func', 'superFunc'],
                                  properties: ['attrA', 'attrB'] });

  var SubClass = utils.expose('SubClass',
                              SubClassImpl,
                              { superclass: SuperClass,
                                functions: ['subFunc'],
                                properties: ['attrC'] });

  var supe = new SuperClass();
  AssertTrue(supe.attrA == 'aSuper');
  AssertTrue(supe.attrB == 'bSuper');
  AssertFalse('attrC' in supe);
  AssertTrue(supe.func() == 'func');
  AssertTrue('superFunc' in supe);
  AssertTrue(supe.superFunc() == 'superFunc');
  AssertFalse('subFunc' in supe);
  AssertTrue(supe instanceof SuperClass);

  var sub = new SubClass();
  AssertTrue(sub.attrA == 'aSub');
  AssertTrue(sub.attrB == 'bSuper');
  AssertTrue(sub.attrC == 'cSub');
  AssertTrue(sub.func() == 'overridden');
  AssertTrue(sub.superFunc() == 'superFunc');
  AssertTrue('subFunc' in sub);
  AssertTrue(sub.subFunc() == 'subFunc');
  AssertTrue(sub instanceof SuperClass);
  AssertTrue(sub instanceof SubClass);

  function SubSubClassImpl() {}
  SubSubClassImpl.prototype = Object.create(SubClassImpl.prototype);
  SubSubClassImpl.prototype.subSubFunc = function() { return 'subsub'; }

  var SubSubClass = utils.expose('SubSubClass',
                                 SubSubClassImpl,
                                 { superclass: SubClass,
                                   functions: ['subSubFunc'] });
  var subsub = new SubSubClass();
  AssertTrue(subsub.attrA == 'aSub');
  AssertTrue(subsub.attrB == 'bSuper');
  AssertTrue(subsub.attrC == 'cSub');
  AssertTrue(subsub.func() == 'overridden');
  AssertTrue(subsub.superFunc() == 'superFunc');
  AssertTrue(subsub.subFunc() == 'subFunc');
  AssertTrue(subsub.subSubFunc() == 'subsub');
  AssertTrue(subsub instanceof SuperClass);
  AssertTrue(subsub instanceof SubClass);
  AssertTrue(subsub instanceof SubSubClass);
}

function fakeApiFunction(shouldSucceed, numberOfResults, callback) {
  if (shouldSucceed) {
    var result = [];
    for (var i = 0; i < numberOfResults; i++) {
      result.push(i);
    }
    $Function.apply(callback, null, result);
    return;
  }
  chrome.runtime.lastError = 'error message';
  callback();
  chrome.runtime.lastError = null;
}

function testPromiseNoResult() {
  utils.promise(fakeApiFunction, true, 0).then(function(result) {
    AssertTrue(result === undefined);
  }).catch(function(e) {
    AssertFalse(True);
  });
}

function testPromiseOneResult() {
  utils.promise(fakeApiFunction, true, 1).then(function(result) {
    AssertTrue(result === 0);
  }).catch(function(e) {
    AssertFalse(True);
  });
}

function testPromiseTwoResults() {
  utils.promise(fakeApiFunction, true, 2).then(function(result) {
    AssertTrue(result.length == 2);
    AssertTrue(result[0] == 0);
    AssertTrue(result[1] == 1);
  }).catch(function(e) {
    AssertFalse(True);
  });
}

function testPromiseError() {
  utils.promise(fakeApiFunction, false, 0).then(function(result) {
    AssertFalse(True);
  }).catch(function(e) {
    AssertTrue(e.message == 'error message');
  });
}

exports.testSuperClass = testSuperClass;
exports.testPromiseNoResult = testPromiseNoResult;
exports.testPromiseOneResult = testPromiseOneResult;
exports.testPromiseTwoResults = testPromiseTwoResults;
exports.testPromiseError = testPromiseError;


text:
<!--{ ids:[136], language:'JavaScript', type:'workshop', order: 10, name:'Identifiers', description:'Identifiers are unique names' } -->

### Exercise

There are six variables declared in the editor. Three of the variables have good identifiers and three of them do not. Determine the three poorly-named variables and remove their assignments.

```js
var AwFuL_Var_nAmE = "some value";
```

For example, if you think `AwFuL_Var_nAmE` is a bad identifier, then remove its assigned value and leave it like so:

```js
var AwFuL_Var_nAmE;
```


text:
package de.piba.bookkeeping.util;

import java.time.LocalDate;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * Adapter (for JAXB) to convert between the LocalDate and the ISO 8601
 * String representation of the date such as '2012-12-03'.
 *
 * @author Marco Jakob
 */
public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {

    @Override
    public LocalDate unmarshal(String v) throws Exception {
        return LocalDate.parse(v);
    }

    @Override
    public String marshal(LocalDate v) throws Exception {
        return v.toString();
    }
}


text:
@interface SettingCell : BaseTableViewCell

@end


text:
<?php

namespace Magento\ConfigurableProduct\Test\Unit\Model\Product\Type;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;

class VariationMatrixTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix */
    protected $model;

    /** @var ObjectManagerHelper */
    protected $objectManagerHelper;

    protected function setUp()
    {
        $this->objectManagerHelper = new ObjectManagerHelper($this);

        $this->model = $this->objectManagerHelper->getObject(
            '\Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix'
        );
    }

    public function testGetVariations()
    {
        $result = [
            [
                130 => [
                    'value' => '3',
                    'label' => 'red',
                    'price' => ['value_index' => '3', 'pricing_value' => '', 'is_percent' => '0', 'include' => '1',],
                ],
            ],
            [
                130 => [
                    'value' => '4',
                    'label' => 'blue',
                    'price' => ['value_index' => '4', 'pricing_value' => '', 'is_percent' => '0', 'include' => '1',],
                ],
            ],
        ];

        $input = [
            130 => [
                'values' => [
                    [
                        'value_index' => '3',
                        'pricing_value' => '',
                        'is_percent' => '0',
                        'include' => '1'
                    ],
                    [
                        'value_index' => '4',
                        'pricing_value' => '',
                        'is_percent' => '0',
                        'include' => '1'
                    ],
                ],
                'attribute_id' => '130',
                'options' => [['value' => '3', 'label' => 'red',], ['value' => '4', 'label' => 'blue',],],
            ],
        ];

        $this->assertEquals($result, $this->model->getVariations($input));
    }
}


text:
// Copyright 2002-2015, University of Colorado Boulder

/**
 * Determines the set of files to be preloaded before the simulation is run.
 * These files will be loaded via script tags in the generated HTML file.
 * As a side-effect, this modifies pkg.preload.
 * It does not modify the actual package.json file.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

// modules
var assert = require( 'assert' );
var fs = require( 'fs' );

var BUILD_INFO_FILENAME = '../chipper/build.json'; // contains build info, which identifies preloads needed by all sims
var LICENSE_INFO_FILENAME = '../sherpa/third-party-licenses.json'; // contains third-party license info

/*
 * @param grunt the grunt instance
 * @param {string} repositoryName name of the sim's repository
 * @param {Object} pkg package.json
 */
module.exports = function( grunt, pkg ) {
  'use strict';

  // Read build info
  assert( fs.existsSync( BUILD_INFO_FILENAME ), 'missing ' + BUILD_INFO_FILENAME );
  var buildInfo = grunt.file.readJSON( BUILD_INFO_FILENAME );

  // Read license info
  assert( fs.existsSync( LICENSE_INFO_FILENAME ), 'missing ' + LICENSE_INFO_FILENAME );

  // Add common preloads, as specified in build.json
  grunt.log.debug( 'Adding common preload files...' );
  assert( buildInfo.common && buildInfo.common.preload, BUILD_INFO_FILENAME + ' is missing common.preload' );
  var preload = buildInfo.common.preload;

  // Add sim-specific preloads, as specified in the (optional) preload field of package.json.
  if ( pkg.preload ) {
    grunt.log.debug( 'Adding sim-specific preload files...' );
    preload = preload.concat( pkg.preload );
  }

  // Add together (data collection) preloads, as specified in build.json
  if ( grunt.option( 'together' ) ) {
    grunt.log.debug( 'Adding together preload files...' );
    assert( buildInfo.together && buildInfo.together.preload, BUILD_INFO_FILENAME + ' is missing together.preload' );
    preload = preload.concat( buildInfo.together.preload );
    assert( pkg.name, 'package.json is missing name' );
    preload.push( '../together/js/api/' + pkg.name + '-api.js' );
  }

  // Modify pkg
  pkg.preload = preload;
  grunt.log.debug( 'pkg.preload = ' + pkg.preload.toString() );
};


text:
=head1 NAME

 -

=head1 VERSION

This documentation refers to <app name> version 0.0.1

=head1 SYNOPSIS

=head1 REQUIRED ARGUMENTS

=head1 OPTIONS

=head1 DESCRIPTION

=head1 DIAGNOSTICS

=head1 CONFIGURATION AND ENVIRONMENT

=head1 DEPENDENCIES

=head1 INCOMPATIBILITIES

=head1 BUGS AND LIMITATIONS

There are no known bugs in this app.
Please report problems to Quinn Weaver <quinn@fairpath.com>
Patches are welcome.

=head1 AUTHOR

Quinn Weaver <quinn@fairpath.com>

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2011 Quinn Weaver (<quinn@fairpath.com>). All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


text: <!DOCTYPE html>


text:
import fs from 'fs';
import { join } from 'path';
import promisify from './promisify';

const readdir = promisify(fs.readdir);
const lstat = promisify(fs.lstat);

export default function walkDir(dir, filter, fileCb) {
  return readdir(dir)
    .then(fileList => {
      let files = fileList.map(f => join(dir, f));
      files = filter ? filter(files) : files;

      const next = () => {
        if (files.length < 1) {
          return true;
        }

        const file = files.shift();

        if (!file) {
          return next();
        }

        return lstat(file)
          .then(stats => {
            if (stats.isDirectory()) {
              return walkDir(file, filter, fileCb).then(next);
            } else if (!stats.isSymbolicLink() && fileCb) {
              return fileCb(file).then(next);
            }

            return next();
          });
      };

      return next();
    });
}


text:
'use strict'

import React, { PropTypes } from 'react'
import LazyImg from './lazy-img'
import SvgIcon from './svg-icon'

const getMonth = (month) => {
  const months = [
    'Janeiro',
    'Fevereiro',
    'Março',
    'Abril',
    'Maio',
    'Junho',
    'Julho',
    'Agosto',
    'Setembro',
    'Outubro',
    'Novembro',
    'Dezembro'
  ]
  const m = months.indexOf(month) + 1
  return (m < 10 ? '0' : '') + m
}

const formatDate = ({ day, month, year }) => {
  return `${day}/${getMonth(month)}/${year}`
}

const EventListItem = ({
  title,
  image,
  link,
  date,
  price,
  location,
  shortDescription
}) => (

      <LazyImg src={image || 'svg/logo.svg'} alt={title} />

{title}

{shortDescription}

      {!!link &&

          <SvgIcon id='link' label='Link' />
          {link}

      }

          <SvgIcon id='date' label='Data' />
          {formatDate(date)}

          <SvgIcon id='price' label='Preço' />
          {price}

        {!!location.locationUrl &&

            <SvgIcon id='location' label='Local' />

              {`${location.address} - ${location.city}/${location.state}`}

        }

)

EventListItem.defaultProps = {
  date: {
    day: '00',
    month: 'xx',
    year: '0000'
  },
  price: 'Grátis',
  location: {
    locationUrl: ''
  },
  shortDescription: ''
}

EventListItem.propTypes = {
  title: PropTypes.string.isRequired,
  image: PropTypes.string,
  link: PropTypes.string,
  date: PropTypes.shape({
    day: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string
    ]).isRequired,
    month: PropTypes.string.isRequired,
    year: PropTypes.number.isRequired
  }).isRequired,
  price: PropTypes.string,
  location: PropTypes.shape({
    city: PropTypes.string,
    state: PropTypes.string,
    address: PropTypes.string,
    locationUrl: PropTypes.string
  }),
  shortDescription: PropTypes.string.isRequired
}

export default EventListItem


text:
package com.squarespace.less.cli;

import java.security.Permission;

/**
 * Unfortunately have to intercept System.exit() call as argparse4j's
 * ArgumentParserImpl is final.
 */
class NoExitSecurityManager extends SecurityManager {

  @Override
  public void checkPermission(Permission perm) {
  }

  @Override
  public void checkPermission(Permission perm, Object context) {
  }

  @Override
  public void checkExit(int status) {
    throw new ExitException(status);
  }

}


text:
<?php

namespace Administracion\ModeloBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ComandaRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ComandaRepository extends EntityRepository
{
    public function findComandasHoy($sucursal = null)
    {
         $em = $this->getEntityManager();

         $sql = 'SELECT c FROM ModeloBundle:Comanda c WHERE c.fecha >= :fecha';

         if($sucursal)
             $sql .= ' and c.sucursal = :sucursal';

         $consulta = $em->createQuery($sql);
	 $consulta->setParameter('fecha', new \DateTime('today'));

         if($sucursal)
             $consulta->setParameter('sucursal',$sucursal);

         return $consulta->getResult();
    }

    public function findComandas($sucursal = null)
    {
         $em = $this->getEntityManager();

         $sql = 'SELECT c FROM ModeloBundle:Comanda c ';

         if($sucursal)
             $sql .= ' WHERE c.sucursal = :sucursal';

         $consulta = $em->createQuery($sql);

         if($sucursal)
             $consulta->setParameter('sucursal',$sucursal);

         return $consulta->getResult();
    }

     public function findComandasByEstadoSucursal($estado, $sucursal )
    {
         $em = $this->getEntityManager();
	 $consulta = $em->createQuery('
		  SELECT c
		  FROM ModeloBundle:Comanda c
		  WHERE c.estado = :estado
		  AND c.sucursal = :sucursal
		  ORDER BY c.id DESC
		');
	 $consulta->setParameter('estado', $estado);
	 $consulta->setParameter('sucursal', $sucursal->getId());
	 return $consulta->getResult();
    }

    public function GenerarCodigoComanda($sucursal)
    {
        $em = $this->getEntityManager();
        $comandas = $em->getRepository('ModeloBundle:Comanda')->findBy(array('sucursal'=>$sucursal));
        if(count($comandas) > 0){
            $numero = count($comandas) + 1;
        } else{
            $numero = 1;
        }
        $codigo = strtoupper(substr($sucursal->getNombre(), 0, 2))."/";
        $codigo .= str_pad($numero, 6, '0', STR_PAD_LEFT);

        return $codigo;
    }

    public function CambiarEstadoComandaDemorada()
    {
        $em = $this->getEntityManager();
        $comandas = $em->getRepository('ModeloBundle:Comanda')->findBy(array('estado'=>2));
        foreach($comandas as $comanda){
            $creacion = $comanda->getHora();
            $ahora = new \DateTime('now');
            $intervalo = $creacion->diff($ahora);

            $diferenciaDias = $intervalo->format('%d');
            $diferenciaHoras = $intervalo->format('%h');
            $diferenciaMinutos = $intervalo->format('%i');

            $minutos = array('1'=>40, 2=>50, 3=>90 );

            $diferenciaMinutos += $diferenciaHoras > 0 ? $diferenciaHoras * 60 : 0;

            if($diferenciaDias > 0 || $minutos[$comanda->getTiempoDemora()] < $diferenciaMinutos ){
                $comanda->setEstado(4);
                $em->persist($comanda);
            }
        }

        $em->flush();
    }

}


text:
package enhacore.informatica;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Host extends JFrame {

	public JPanel contentPane;

	/**
	 * Create the frame.
	 */
	public Host() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 390, 257);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JButton btnNewButton = new JButton("Regresar");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
		btnNewButton.setBounds(275, 184, 89, 23);
		contentPane.add(btnNewButton);

		JLabel lblAnthropology = new JLabel("Host:");
		lblAnthropology.setFont(new Font("Tahoma", Font.PLAIN, 20));
		lblAnthropology.setBounds(155, 24, 63, 30);
		contentPane.add(lblAnthropology);

		JLabel lblAntropologa = new JLabel("Anfitrión");
		lblAntropologa.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblAntropologa.setBounds(155, 93, 63, 23);
		contentPane.add(lblAntropologa);
	}
}


text:
import { Schema } from 'mongoose'
import Duoshuo from 'duoshuo'
import moment from 'moment'

const User = new Schema({
  url: String,
  email: String,
  phone: String,
  avatar: String,
  nickname: String,
  password: String,
  email_notification: String,
  social_networks: {},
  created: {
    type: Date,
    default: Date.now
  },
  type: {
    type: String,
    default: 'normal'
  },
  threads: [{
    type: Schema.Types.ObjectId,
    ref: 'thread'
  }],
  duoshuo: {
    user_id: {
      type: String,
      unique: true
    },
    access_token: String
  }
})

User.static('read', id => {
  const query = {
    'duoshuo.user_id': id
  }

  return this.findOneAsync(query)
})

User.static('addThreadId', (id, tid) => {
  const query = {
    $push: {
      threads: tid
    }
  }

  return this.findByIdAndUpdateAsync(id, query)
})

User.static('sync', id => {
  const duoshuo = new Duoshuo(config)
  const typeMap = {
    admin: 'administrator',
    editor: 'editor',
    author: 'author',
    normal: 'user'
  }

  return this.findByIdAsync(id).then(user => {
    let ds = duoshuo.getClient(user.duoshuo.access_token)

    // Any other better choice ?
    return new Promise((res, rej) => {
      ds.join({
        info: {
          user_key: user._id,
          name: user.nickname,
          role: typeMap[user.type],
          avatar_url: user.avatar,
          url: user.url,
          created_at: moment(user.created).format('YYYY-MM-DD hh:MM:ss')
        }
      }, (err, ret) => {
        if (err)
          return rej(err)

        res(ret)
      })
    })
  })
})

User.virtual('admin').get(() => {
  return this.type === 'admin'
})

export default User


text:
package org.apache.gearpump.cluster.main

import akka.actor.{ActorSystem, Props}
import akka.testkit.TestProbe
import com.typesafe.config.Config
import org.apache.gearpump.cluster.TestUtil
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.Await
import scala.concurrent.duration._

class MasterWatcherSpec extends FlatSpec with Matchers {
  def config: Config = TestUtil.MASTER_CONFIG

  "MasterWatcher" should "kill itself when can not get a quorum" in {
    val system = ActorSystem("ForMasterWatcher", config)

    val actorWatcher = TestProbe()(system)

    val masterWatcher = system.actorOf(Props(classOf[MasterWatcher], "watcher"))
    actorWatcher watch masterWatcher
    actorWatcher.expectTerminated(masterWatcher, 5.seconds)
    system.terminate()
    Await.result(system.whenTerminated, Duration.Inf)
  }
}


text:
<!DOCTYPE html>

    <title>craigslist - apartments</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link type="text/css" rel="stylesheet" media="all" href="//www.craigslist.org/styles/cl.css?v=d76fe4376346bd1b2503fb10181051a7">

   CL

                    new york

                    >

apartments

        <input type="submit" value="go">

            post

            account

                 favorites

          <form class="unfavform js-only" method="POST" action="/favorites">

              <input type="hidden" class="lastLink" name="lastLink" value="">
              <input type="hidden" class="lastTitle" name="lastTitle" value="">
              <input type="hidden" class="unfaves" name="fl">
              <input type="hidden" name="uf" value="1">

                 hidden

          </form>

   CL

new york

    ...

Several ways to view apartment listings:

all apartments

                    (includes by-owner + no-fee broker + fee broker)

all no-fee apartments

                    (includes by-owner + no-fee broker

                by-owner apartments only

                (no brokers)

                registration fee

                (subscription-fee-based apt finding services)

        It is illegal to discriminate in the sale, rental or leasing of housing because of a person's race, color, creed, national origin, sexual orientation, marital status, familial status, or religion.

In New York City and in other municipalities in the state, it is also illegal to discriminate against people based on their source of income, including receipt of Section 8 or other public benefits.

It is furthermore also illegal to place housing advertisements containing discriminatory language on craigslist or any other site. Law enforcement officials survey craigslist for discriminatory advertisements and violators are subject to civil penalties (up to $10,000 per violation) and revocation of real estate license.

If you notice a discriminatory advertisement please flag it for removal, and follow the links below to file complaints with:

NYS Office of the Attorney General

NYS Division of Human Rights

NYS Licensing Department

©  craigslistCL

help

safety

privacy

feedback

cl jobs

terms

about

mobile

desktop


text:
<?php

function getParamString(ReflectionFunctionAbstract $rf) {
	$params = array();
	foreach ($rf->getParameters() as $param) {
		$p = '$'.$param->getName();
		if ($param->isPassedByReference()) {
			$p = '&'.$p;
		}
		if ($param->isDefaultValueAvailable()) {
			$p = ' = '.var_export($param->getDefaultValue(), true);
		}
		$params[] = $p;
	}
	return implode(', ', $params);
}

function getFunctionString(ReflectionFunctionAbstract $ref) {
	$name = $ref->getName().'(';
	if ($ref instanceof ReflectionMethod) {
		if ($ref->isStatic()) {
			$name = '::'.$name;
		} else {
			$name = '->'.$name;
		}
	}
	$name .= getParamString($ref);
	$name .= ')';
	return $name;
}


text:
package module4;

import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.marker.SimplePointMarker;
import processing.core.PGraphics;

/** Implements a visual marker for earthquakes on an earthquake map
 *
 * @author UC San Diego Intermediate Software Development MOOC team
 * @author Your name here
 *
 */
public abstract class EarthquakeMarker extends SimplePointMarker
{

	// Did the earthquake occur on land?  This will be set by the subclasses.
	protected boolean isOnLand;

	// The radius of the Earthquake marker
	// You will want to set this in the constructor, either
	// using the thresholds below, or a continuous function
	// based on magnitude.
	protected float radius;

	/** Greater than or equal to this threshold is a moderate earthquake */
	public static final float THRESHOLD_MODERATE = 5;
	/** Greater than or equal to this threshold is a light earthquake */
	public static final float THRESHOLD_LIGHT = 4;

	/** Greater than or equal to this threshold is an intermediate depth */
	public static final float THRESHOLD_INTERMEDIATE = 70;
	/** Greater than or equal to this threshold is a deep depth */
	public static final float THRESHOLD_DEEP = 300;

	// ADD constants for colors

	// abstract method implemented in derived classes
	public abstract void drawEarthquake(PGraphics pg, float x, float y);

	// constructor
	public EarthquakeMarker (PointFeature feature)
	{
		super(feature.getLocation());
		// Add a radius property and then set the properties
		java.util.HashMap<String, Object> properties = feature.getProperties();
		float magnitude = Float.parseFloat(properties.get("magnitude").toString());
		properties.put("radius", 2*magnitude );
		setProperties(properties);
		this.radius = 2.0f*getMagnitude();
	}

	// calls abstract method drawEarthquake and then checks age and draws X if needed
	public void draw(PGraphics pg, float x, float y) {
		// save previous styling
		pg.pushStyle();

		// determine color of marker from depth
		colorDetermine(pg);

		// call abstract method implemented in child class to draw marker shape
		drawEarthquake(pg, x, y);

		// draw X over marker if within past day
		if(getAge().equals("Past Day")) {
			pg.color(0, 0, 0);
			if(isOnLand()) {
				pg.line(x-radius/2, y-radius/2, x+radius/2, y+radius/2);
				pg.line(x-radius/2, y+radius/2, x+radius/2, y-radius/2);
			} else {
				pg.line(x, y, x+radius, y+radius);
				pg.line(x, y+radius, x+radius, y);
			}

		}

		// reset to previous styling
		pg.popStyle();

	}

	// determine color of marker from depth
	// We suggest: Deep = red, intermediate = blue, shallow = yellow
	// But this is up to you, of course.
	// You might find the getters below helpful.
	private void colorDetermine(PGraphics pg) {

		if(getDepth() < THRESHOLD_INTERMEDIATE){
			pg.fill(255, 255, 0); //yellow
		} else if (getDepth() < THRESHOLD_DEEP) {
			pg.fill(0, 0, 255); //blue
		} else{
			pg.fill(255, 0, 0); //red
		}
	}

	/*
	 * getters for earthquake properties
	 */

	public float getMagnitude() {
		return Float.parseFloat(getProperty("magnitude").toString());
	}

	public float getDepth() {
		return Float.parseFloat(getProperty("depth").toString());
	}

	public String getAge() { return getProperty("age").toString(); }

	public String getTitle() {
		return (String) getProperty("title");

	}

	public float getRadius() {
		return Float.parseFloat(getProperty("radius").toString());
	}

	public boolean isOnLand()
	{
		return isOnLand;
	}

}


text:
/*
 *
 * Licensed 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 com.comcast.cdn.traffic_control.traffic_router.core.loc;

import java.io.File;
import java.io.IOException;

public class DeepNetworkUpdater extends NetworkUpdater {

	public DeepNetworkUpdater() {
		sourceCompressed = false;
		tmpPrefix = "deepczf";
		tmpSuffix = ".json";
	}

	@Override
	public NetworkNode generateTree(final File dbFile, final boolean verifyOnly) throws IOException {
		return NetworkNode.generateTree(dbFile, verifyOnly, true);
	}

}


text:
var express = require('express');
var Twitter = require('twitter');
var bodyParser = require('body-parser');
var sentimentChecker = require(__dirname + '/../lib/sentiment/sentiment_checker.js');

var twitterRouter = module.exports = exports = express.Router();

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

twitterRouter.post('/twitter/timeline', bodyParser.urlencoded({extended: true}), function(req, res, next) {
  var params = {screen_name: req.body.text, count: 200};
  client.get('statuses/user_timeline.json', params, function(err, tweets, response) {
    if(err) throw err;
    res.tweets = '';
    for(var i = 0; i < tweets.length; i++) {
      res.tweets += tweets[i].text;
    }

    next();
  });
});

twitterRouter.post('/twitter/timeline', function(req, res) {
  res.tweetSentiment = (sentimentChecker(res.tweets));
  res.send(res.tweetSentiment);

});

twitterRouter.post('/twitter/hashtag', bodyParser.urlencoded({extended: true}), function(req, res, next) {
  var params = {q: req.body.text, count: 100};
  client.get('search/tweets.json', params, function(err, tweets, response) {
    if(err) throw err;
    res.tweets = '';
    for(var i = 0; i < tweets.statuses.length; i++) {
      res.tweets += tweets.statuses[i].text;
    }

    next();
  });
});

twitterRouter.post('/twitter/hashtag', function(req, res) {
  res.tweetSentiment = (sentimentChecker(res.tweets));
  res.send(res.tweetSentiment);

});


text:
import pytest
pytest.importorskip('numpy')

import numpy as np
import dill
from dask.array.core import Array
from dask.array.random import random, exponential, normal
import dask.array as da
import dask
from dask.multiprocessing import get as mpget

def test_RandomState():
    state = da.random.RandomState(5)
    x = state.normal(10, 1, size=10, chunks=5)
    assert (x.compute() == x.compute()).all()

    state = da.random.RandomState(5)
    y = state.normal(10, 1, size=10, chunks=5)
    assert (x.compute() == y.compute()).all()

def test_concurrency():
    state = da.random.RandomState(5)
    x = state.normal(10, 1, size=10, chunks=2)

    state = da.random.RandomState(5)
    y = state.normal(10, 1, size=10, chunks=2)
    assert (x.compute(get=mpget) == y.compute(get=mpget)).all()

def test_doc_randomstate():
    assert 'mean' in da.random.RandomState(5).normal.__doc__

def test_serializability():
    state = da.random.RandomState(5)
    x = state.normal(10, 1, size=10, chunks=5)

    y = dill.loads(dill.dumps(x))

    assert (x.compute() == y.compute()).all()

def test_determinisim_through_dask_values():
    samples_1 = da.random.RandomState(42).normal(size=1000, chunks=10)
    samples_2 = da.random.RandomState(42).normal(size=1000, chunks=10)

    assert [v for k, v in sorted(samples_1.dask.items())] ==\
           [v for k, v in sorted(samples_2.dask.items())]

def test_random():
    a = random((10, 10), chunks=(5, 5))
    assert isinstance(a, Array)
    assert isinstance(a.name, str) and a.name
    assert a.shape == (10, 10)
    assert a.chunks == ((5, 5), (5, 5))

    x = set(np.array(a).flat)

    assert len(x) > 90

def test_parametrized_random_function():
    a = exponential(1000, (10, 10), chunks=(5, 5))
    assert isinstance(a, Array)
    assert isinstance(a.name, str) and a.name
    assert a.shape == (10, 10)
    assert a.chunks == ((5, 5), (5, 5))

    x = np.array(a)
    assert 10 < x.mean() < 100000

    y = set(x.flat)
    assert len(y) > 90

def test_kwargs():
    a = normal(loc=10.0, scale=0.1, size=(10, 10), chunks=(5, 5))
    assert isinstance(a, Array)
    x = np.array(a)
    assert 8 < x.mean() < 12

def test_unique_names():
    a = random((10, 10), chunks=(5, 5))
    b = random((10, 10), chunks=(5, 5))

    assert a.name != b.name

def test_docs():
    assert 'exponential' in exponential.__doc__
    assert 'exponential' in exponential.__name__

def test_can_make_really_big_random_array():
    x = normal(10, 1, (1000000, 1000000), chunks=(100000, 100000))

def test_random_seed():
    da.random.seed(123)
    x = da.random.normal(size=10, chunks=5)
    y = da.random.normal(size=10, chunks=5)

    da.random.seed(123)
    a = da.random.normal(size=10, chunks=5)
    b = da.random.normal(size=10, chunks=5)

    assert (x.compute() == a.compute()).all()
    assert (y.compute() == b.compute()).all()


text:
<?php
namespace keeko\tools\command;

use keeko\tools\ui\EmberUI;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateEmberCommand extends AbstractEmberCommand {

	protected function configure() {
		$this
			->setName('generate:ember')
			->setDescription('Run all ember generators');

		parent::configure();
	}

	protected function interact(InputInterface $input, OutputInterface $output) {
		$ui = new EmberUI($this);
		$ui->show();
	}

	protected function execute(InputInterface $input, OutputInterface $output) {
		$args = [
			'--package' => $input->getOption('package')
		];

		$this->runCommand('generate:ember:model', $args);
		$this->runCommand('generate:ember:abilities', $args);
		$this->runCommand('generate:ember:serializer', $args);
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Niek van Ulzen">

    <title>Veni Vidi Fietsie - Wielrennen in de Dolomieten</title>
    <meta name="description" content=
        "Veni Vidi Fietsie verzorgt wielrenvakanties voor groepen vanuit hotel Lory in Molveno, een bergdorpje in de Dolomieten
	dichtbij het Gardameer. Op de racefiets je eigen Giro d'Italia compleet met ploegentactiek, kopmannen en etappes. Of gewoon genieten van wielrennen over
	schitterende passen, rustige wegen en fietspaden tussen olijfboomgaarden en wijnvelden met tussendoor tijd voor een pasta."
    >

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

    <link rel="icon" href="img/logo/favicon.png">

    <link href="css/freelancer.css" rel="stylesheet">
    <link href="css/owl.theme.css" rel="stylesheet">
    <link href="css/owl.carousel.css" rel="stylesheet">
    <link href="css/venividifietsie.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

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

                </button>
                Veni Vidi Fietsie

                        *Giroweek*

                        Over

                        Aanbod

Giro di Molveno

Pas op, voor pasta

                        Locatie

                        Team

                        Contact

                        Linkeballen in de Dolomieten

Over Veni Vidi Fietsie

                            Wielrennen in de bergen maar dan anders

                            Veni Vidi Fietsie verzorgt competitieve en recreatieve fietsvakanties voor groepen vanuit Molveno, een prachtig bergdorp in de Brenta Dolomieten.
                            In de vorm van een heuse Giro d'Italia compleet met ploegentactiek, kopmannen, klassementen en bergetappes.
                            Of gewoon relaxed een pas op, over rustige wegen en mooie fietspaden, met onderweg tijd voor een lekker bord pasta of echt Italiaanse gelato.

Op maat, passend bij niveau en ambitie van de groep

Mythische beklimmingen en superstrakke afdalingen

Genieten van mooie wijnvelden en uitgestrekte olijfboomgaarden

Met bergetappes, klimtijdritten, rangen en standen

Ontspannen met een wijnproeverij bij Francesco Moser

Met als toetje een heerlijke gelato aan het Gardameer

Aanbod

                            Le morte o i gladioli

                    Giro di Molveno

                    Pas op, voor pasta

Giro di Molveno

                            Ploegentactiek, linkeballen en la maglia rosa...

                            Je eigen Giro d'Italia met ploegen, kopmannen & knechten, een proloog, tijdrit, sprint- en bergetappes en dagelijks bijgehouden klassementen.
                            In de jacht op het roze kunnen de renners tijdens de Giro di Molveno hun klimmerscapaciteiten ten enenmale etaleren aan het Italiaanse volk.
                            Aanschouw de andere pedaalridders en overwin door een uitgekiende ploegentactiek!

Sella Andalo

 14.30 km

 793 m

Gemiddeld 5.4%

Maximaal 10.2%

Monte Bondone

 17.47 km

 1372 m

Gemiddeld 7.9%

Maximaal 13%

Passo Daone

 8.40 km

 775 m

Gemiddeld 9.2%

Maximaal 14%

Pas op, voor Pasta

                            Eerst enkele passen op en dan pasta. Of wijn. Of ijs.

                            Veni Vidi Fietsie wijst de weg, over schitterende passen en rustige fietspaden. En na een fikse klim
                            is er tijd voor de lokale pasta of Italiaans ijs aan het Gardameer. Aanschouw het prachtige landschap,
                            bedwing de mooiste passen en laaf u aan de cucina tipica.

Locatie

                            Tussen de Passo dello Stelvio en het Gardameer

Molveno

Hotel

Route

                                        Uitvalsbasis is Molveno, een Italiaans bergdorpje in de regio Trentino-Südtirol ingeklemd tussen het
                                        gelijknamige meer en de Brenta Dolomieten. Het ligt op een hoogte van 834 meter, zo'n 50 km ten noorden
                                        van het Gardameer. Vanuit Molveno zijn tal van passen te beklimmen zoals de Passo del Ballino,
                                        Monte Bondone, Passo Daone, Passo Duron en de Sella di Andalo.

Vanuit hotel Lory zullen de renners dagelijks de omgeving verkennen dan wel hun concurrenten de pas(ta) afsnijden.

                                        Hotel Lory beschikt naast ruime kamers over een groot terras met uitzicht op het meer, en over een gezellige bar waar het tot laat in de avond goed toeven is (met de vermoeide beentjes omhoog).

                                                1074 km vanaf Utrecht. Door Duitsland en Oostenrijk.
                                                Brennerpas over. Bij Mezzocorona de snelweg af. En
                                                dan 40 minuten omhoog tegen 6.3% gemiddeld.

                                               De internationale treinen vanuit Nederland stoppen in
                                               Bolzano. Dan is het nog 45 minuten naar Mezzocorona,
                                               het dichtstbijzijnde treinstation.

                                                De vliegvelden van Verona en Innsbruck liggen op
                                                respectievelijk 130 km en 180 km van Molveno.

Team

                            Even voorstellen... de meesterknechten

Niek

aka Jalabert

Kent de Dolomietjes op zijn duimpje

Alwin

aka Frigo

Met voorliefde voor de grote molen

Roelof

aka Garzelli

Pijn is tijdelijk, opgeven voor altijd

Karen

aka Paastacchi

Staat altijd voor u klaar

Maurice

aka Paastacchi

Staat ook altijd voor u klaar

Drie bewegingswetenschappers en twee hoteleigenaren. Alle vijf met een voorliefde voor wielrennen, bergen en Italië.

                                In 2014 verzorgden ze voor een groep van 50 Nederlandse wielrenners een tweedaags arrangement met de mooiste klimmetjes,
                                een etappe met aankomst bergop en een lunch met pasta en risotto. Om het voor elk niveau leuk te houden werd
                                de groep in drieën opgedeeld met voor elke wielerformatie een uitdagende route...

                                Dit leidde tot zoveel enthousiasme dat ze hebben besloten het niet bij één keer te houden.
                                Zodoende is het idee voor Veni Vidi Fietsie ontstaan. Alwin, Roelof en Niek kennen de omgeving door er gewoond, gewerkt
                                en vooral veel gefietst te hebben. Karen en Maurice runnen sinds 2010 hun eigen hotel in Molveno. En gezamenlijk zijn zij uw
                                meesterknechten!

                        Meer

Contact

                            Telefoneren: een demarrage die je al van verre aan ziet komen

                            Vragen? Stuur ons een berichtje of een e-mail. We denken graag met u mee!

                             Direct een offerte? Vul dan het volledige contactformulier in.

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

                                Naam
                                <input type="text" class="form-control" placeholder="Naam" id="name" required data-validation-required-message="Vul uw naam in.">

                                E-mail adres
                                <input type="email" class="form-control" placeholder="E-mail adres" id="email" required data-validation-required-message="Vul uw e-mail adres in.">

                                Telefoonnummer
                                <input type="tel" class="form-control" placeholder="Telefoonnummer" id="phone" required data-validation-required-message="Vul uw telefoonnummer in.">

                                Bericht
                                <textarea rows="4" class="form-control" placeholder="Bericht" id="message" required data-validation-required-message="Schrijf hier uw bericht of vraag."></textarea>

                            Wilt u direct een offerte? Vul dan ook onderstaande vragen en aankomstdatum in (alleen beschikbaar in de maanden juni en september).

                                Waarin bent u geïnteresseerd?
                                <select type="text" class="form-control" placeholder="Aanbod" id="aanbod">
                                  <option value="" disabled selected hidden>Kies een optie</option>
                                  <option value="Giro di Molveno">Giro di Molveno</option>
                                  <option value="Pas op, voor pasta">Pas op, voor pasta</option>
                                </select>

                                Dag
                                <input type="text" class="form-control" placeholder="Dag" id="dag">

                                Maand
                                <select type="text" class="form-control" placeholder="Maand" id="maand">
                                  <option value="" disabled selected hidden>Maand</option>
                                  <option value="Juni">Juni</option>
                                  <option value="September">September</option>
                                </select>

                                Jaar
                                <input type="text" class="form-control" placeholder="Jaar" id="jaar">

                                Aantal dagen
                                <input type="text" class="form-control" placeholder="Aantal dagen" id="dagen">

                                Aantal personen
                                <input type="text" class="form-control" placeholder="Aantal personen" id="groepsgrootte">

                                <button type="submit" class="btn btn-lg vvf-btn">Verzend</button>

                    </form>

                    <button class="btn btn-lg vvf-btn-2" disabled>info@venividifietsie.com</button>

                        Copyright © Veni Vidi Fietsie 2015

Hoe & Wat

Giro di Molveno

Het peloton wordt opgedeeld in gelijkwaardige teams

Het team bestaat één of meerdere kopmannen, klimgeiten, sprinters en/of knechten

Een dag bestaat uit een bepaalde route met verschillende soorten etappes

Tijdens de etappes wordt om (berg)punten en/of tijd gestreden

Tussen de etappes wordt er en groupe naar de volgende etappe gereden

Veni Vidi Fietsie verzorgt de routes, start- en eindpunten en neemt de tijd/aankomsten waar

Aan het einde van de dag wordt de balans opgemaakt en worden de truien uitgedeeld

Hoe een dag eruit kan zien

                                                Omdat de vorige avond niemand iets snapte van de ploegentactiek wordt deze tijdens het
                                                volledig verzorgde ontbijt nog wat aangescherpt.De vertrektijd komt rap dichterbij en de bandjes worden nog snel op spanning gezet.
                                                Gelletjes ingeladen, bidonnetjes gevuld.

                                                Het peloton fietst en group richting het startpunt van de eerste etappe; een vlakke rit over 15 km bij uitstek geschikt voor  rasavonturiers en vroege vluchters.
                                                Zodra alle renners de meet zijn gepasseerd wordt kort gerecapituleerd.

                                                Dan op weg naar de start van de middagetappe: een bergetappe naar de top van de Monte Bondone.
                                                Er volgt een waar schouwspel op de flanken van deze illustere berg. Knechten worden opgebrand, kopmannen uitgespeeld.

                                                Aan de streep krijgen de benen eindelijk rust... maar die is van korte duur. Molveno roept en de renners maken zich klaar om de lange valsplatte route langs het meer te trotseren.
                                                De laatste finish van de dag ligt na een venijne slotklim bij het terras van hotel Lory, onder toeziend oog van de koersdirecteur en meegereisde fans.

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>

Wie & Waar

Voor groepen

Van minimaal 10 tot maximaal 40 renners

Die niet terug deinzen voor 80-150km per dag

Die wel vaker in de bergen hebben gefietst

Die een fiks aantal hoogtemeters durven weg te tikken

Standplaats Molveno

                                            Decors voor de Giro di Molveno zijn de bergen tussen het Gardameer en de Passo di Gavia.
                                            De koersdirectie heeft een tocht uitgestippeld over hoge pieken en door glooiende dalen.
                                            Onder andere de Monte Bondone, Passo Daone en Passo del Ballino staan op het program,
                                            maar ook peddelt het peloton door de Altopiano della Paganella en de vallei der meren en
                                            zien de renners een glimp van het Gardameer.

                                                Uitvalsbasis voor dit spektakel: Hotel Lory, Molveno.

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>

Kosten & Zo

                                Een Giro wordt altijd op maat aangeboden, de mogelijkheden zijn talloos en onder andere afhankelijk van groepsgrootte, verblijfsduur,
                                niveau en specifieke wensen van de renners.

Prijsvoorbeeld 20 renners/4 overnachtingen/3 Girodagen

                                            Inclusief

4 overnachtingen, inclusief ontbijt en diner

3 dagen fietsen

Routeboek en routes in gpx

Begeleiding per auto of fiets

Up-to-date rangen en standen

Bijbehorende leiderstruien

 350,- per persoon

Exclusief

Vervoer Nederland-Italië en terug

Racefiets

Lunch en eten/drinken voor onderweg

Helm, reparatiesetje, etc

Optioneel

Lunch: Picnic of pasta

Pastabuffet in hotel

Bezoek museum en wijnproeverij Francesco Moser

Dagje Stelvio of Gavia/Mortirolo

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>

Hoe & Wat

Pas op voor Pasta

                                                Pas op voor Pasta kenmerkt zich door een combinatie van het op eigen tempo bedwingen van dolomietentoppen
                                                en genieten van de Italiaanse omgeving, gastvrijheid en keuken. Per minimaal 10 wielrenners wijzen één of meerdere ervaren gidsen
                                                de weg over mooie toppen, door glooiende dalen en terug naar het hotel. Eenmaal terug in het hotel kan men weer op krachten komen,
                                                genietend van een welverdiend wijntje of biertje. Wie nog puf heeft, kan proberen een recordje neer te zetten op de
                                                klimtijdrit naar bar-ristorante Erica. Na een geheel verzorgde avondmaaltijd gaat een ieder zijn eigen gang of
                                                komt bijeen aan de gezellige hotelbar.

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>

Wie & Waar

Voor groepen

Van minimaal 10 tot maximaal 40 renners

Die wel vaker in de bergen hebben gefietst

Die mooie passen willen bedwingen

Die naast de inspanning niet terug deizen voor ontspanning

Standplaats Molveno

                                            Decors voor de Giro di Molveno zijn de bergen tussen het Gardameer en de Passo di Gavia.
                                            De koersdirectie heeft een tocht uitgestippeld over hoge pieken en door glooiende dalen.
                                            Onder andere de Monte Bondone, Passo Daone en Passo del Ballino staan op het program,
                                            maar ook peddelt het peloton door de Altopiano della Paganella en de vallei der meren en
                                            zien de renners een glimp van het Gardameer.

                                                Uitvalsbasis voor dit spektakel: Hotel Lory, Molveno.

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>

Kosten & Zo

                                Pas op voor Pasta wordt altijd op maat aangeboden, de mogelijkheden zijn talloos en onder andere afhankelijk van
                                groepsgrootte, verblijfsduur, niveau en specifieke wensen van de renners.

Prijsvoorbeeld 20 renners/4 overnachtingen/3 Pastadagen

                                            Inclusief

4 overnachtingen, inclusief ontbijt en diner

3 dagen fietsen

Routeboek en routes in gpx

Eén of meerdere gidsen die u de weg wijzen

 320,- per persoon

Exclusief

Vervoer Nederland-Italië en terug

Racefiets

Lunch en eten/drinken voor onderweg

Helm, reparatiesetje, etc

Optioneel

Lunch: Picnic of pasta

Pastabuffet in hotel

Bezoek museum en wijnproeverij Francesco Moser

Dagje Stelvio of Gavia/Mortirolo

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>


text:
package barqsoft.footballscores;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import barqsoft.footballscores.activity.AboutActivity;
import barqsoft.footballscores.fragment.PagerFragment;
import barqsoft.footballscores.util.LogUtil;
import barqsoft.footballscores.util.SyncUtils;

public class MainActivity extends AppCompatActivity{
    public static final String CURRENT_PAGER_ITEM = "Pager_Current";
    public static final String SELECTED_MATCH_ID = "Selected_match";
    public static final String EXTRA_SELECTION_FROM_WIDGET = "selection_from_widget";
    public static int sSelectedMatchId;
//    public static int sCurrentFragment = 2;
    private final String SAVE_TAG = "Save Test";
    private PagerFragment myMain;
    private LogUtil mLog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().setIcon(R.drawable.ic_launcher);

        mLog = new LogUtil.Builder().setLogTag(MainActivity.class).build();
        mLog.d("Reached MainActivity onCreate");

        if (savedInstanceState == null) {
            myMain = new PagerFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, myMain)
                    .commit();

            SyncUtils.TriggerRefresh();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_about) {
            Intent start_about = new Intent(this, AboutActivity.class);
            startActivity(start_about);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}