text:
package org.apache.ambari.server.controller.internal;

import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.ResourcePredicateEvaluator;

/**
 * The default predicate evaluator.
 */
public class DefaultResourcePredicateEvaluator implements ResourcePredicateEvaluator {
  @Override
  public boolean evaluate(Predicate predicate, Resource resource) {
    return predicate.evaluate(resource);
  }
}

redpajama_set_name: RedPajamaGithub


text:
// http://davidscottlyons.com/threejs/presentations/frontporch14/offline-extended.html#slide-79
export default (color, color2=0xAAAAAA) => {
    /*eslint no-console: 0 */
    const _ = {sphereObject: null}
    if (color) {
        _.material = new THREE.MeshPhongMaterial({color});
    } else {
        _.material = new THREE.MeshNormalMaterial({
            transparent: false,
            wireframe: false,
            opacity: 0.8,
        });
    }
    _.material.transparent = true;

    function create() {
        const tj = this.threejsPlugin;
        if (!_.sphereObject) {
            const r = this._.proj.scale() - (this.__plugins('3d').length>0 ? 5 : 0);
            const geometry = new THREE.SphereGeometry(r, 30, 30);
            if (color) {
                const ambient= new THREE.AmbientLight(color2);
                const mesh   = new THREE.Mesh(geometry, _.material);
                _.sphereObject = new THREE.Group();
                _.sphereObject.add( ambient );
                _.sphereObject.add(mesh);
            } else {
                _.sphereObject = new THREE.Mesh(geometry, _.material);
            }
            _.sphereObject.name = _.me.name;
        }
        tj.addGroup(_.sphereObject);
    }

    return {
        name: 'oceanThreejs',
        onInit(me) {
            _.me = me;
        },
        onCreate() {
            create.call(this);
        },
        sphere() {
            return _.sphereObject;
        }
    }
}


text:
package cmd

import (
	"fmt"

	"github.com/mod/kaigara/pkg/core"
	"github.com/mod/kaigara/pkg/log"
	"github.com/mod/kaigara/pkg/metadata"
	"github.com/mod/kaigara/pkg/resource"
	"github.com/spf13/cobra"
)

var configmap string

// renderCmd represents the render command
var renderCmd = &cobra.Command{
	Use:   "render TEMPLATE",
	Short: "Generate a file on STDOUT from a TEMPLATE",
	Long: `Read metadata files for rendering resource pipeline

In local development it is recommended to mount default.yml
using -v default.yml:/etc/kaigara/default.yml

Example: kaigara render server.conf > /etc/server.conf`,

	Run: func(cmd *cobra.Command, args []string) {

		if len(args) > 0 {
			data, err := metadata.Parse()
			template := fmt.Sprintf("%s/%s.tmpl", core.Get("core.path.resources"), args[0])

			if err != nil {
				log.Fatal(err.Error())
			}

			output, err := resource.Render(template, data)
			if err != nil {
				log.Fatal(err.Error())
			}
			fmt.Print(output)
		} else {
			log.Error("No template given")
		}
	},
}

func init() {
	RootCmd.AddCommand(renderCmd)
}


text: R CMD REMOVE --library=$PREFIX/lib/R/library/ msd16s


text:
require 'benchmark'
require 'optparse'
#require 'nmatrix'
require 'numo/narray'
require 'numo/linalg'
require 'npy'
require 'expcalc'

#require 'pp'
#############################################################################
## METHODS
##############################################################################

def load_matrix_file(input_file, splitChar = "\t")
	matrix = nil
	counter = 0
	File.open(input_file).each do |line|
	    	line.chomp!
    		row = line.split(splitChar).map{|c| c.to_f }
    		if matrix.nil?
    			matrix = Numo::DFloat.zeros(row.length, row.length)
    		end
    		row.each_with_index do |val, i|
    			matrix[counter, i] = val
    		end
    		counter += 1
	end
	return matrix
end

def load_pair_file(source, byte_format = :float32)
	connections = {}
	source.each do |line|
		node_a, node_b, weight = line.chomp.split("\t")
		weight.nil? ? weight = 1.0 : weight = weight.to_f
		add_pair(node_a, node_b, weight, connections)
		add_pair(node_b, node_a, weight, connections)
	end
	matrix, names = connections.to_wmatrix
	return matrix, names
end

def add_pair(node_a, node_b, weight, connections)
	query = connections[node_a]
	if !query.nil?
		query[node_b] = weight
	else
		subhash = Hash.new(0.0)
		subhash[node_b] = weight
		connections[node_a] = subhash
	end
end

def get_stats(matrix)
	stats = []
	#TODO: trnasform to Numo::Array operations
	primary_stats = get_primary_stats(matrix)
	#stats << ['Matrix - Symmetric?', matrix.symmetric?]
	stats << ['Matrix - Dimensions', matrix.shape.join('x')]
	stats << ['Matrix - Elements', primary_stats[:count]]
	stats << ['Matrix - Elements Non Zero', primary_stats[:countNonZero]]
	stats << ['Matrix - Non Zero Density', primary_stats[:countNonZero].fdiv(primary_stats[:count])]
	stats << ['Weigth - Max', primary_stats[:max]]
	stats << ['Weigth - Min', primary_stats[:min]]
	stats << ['Weigth - Average', primary_stats[:average]]
	stats << ['Weigth - Variance', primary_stats[:variance]]
	stats << ['Weigth - Standard Deviation', primary_stats[:standardDeviation]]
	stats << ['Weigth - Q1', primary_stats[:q1]]
	stats << ['Weigth - Median', primary_stats[:median]]
	stats << ['Weigth - Q3', primary_stats[:q3]]
	stats << ['Weigth - Min Non Zero', primary_stats[:minNonZero]]
	stats << ['Weigth - Average Non Zero', primary_stats[:averageNonZero]]
	stats << ['Weigth - Variance Non Zero', primary_stats[:varianceNonZero]]
	stats << ['Weigth - Standard Deviation Non Zero', primary_stats[:standardDeviationNonZero]]
	stats << ['Weigth - Q1 Non Zero', primary_stats[:q1NonZero]]
	stats << ['Weigth - Median Non Zero', primary_stats[:medianNonZero]]
	stats << ['Weigth - Q3 Non Zero', primary_stats[:q3NonZero]]
	connections = get_connection_number(matrix)
	connection_stats = get_primary_stats(connections)
	stats << ['Node - Elements', connection_stats[:count]]
	stats << ['Node - Elements Non Zero', connection_stats[:countNonZero]]
	stats << ['Node - Non Zero Density', connection_stats[:countNonZero].fdiv(connection_stats[:count])]
	stats << ['Edges - Max', connection_stats[:max]]
	stats << ['Edges - Min', connection_stats[:min]]
	stats << ['Edges - Average', connection_stats[:average]]
	stats << ['Edges - Variance', connection_stats[:variance]]
	stats << ['Edges - Standard Deviation', connection_stats[:standardDeviation]]
	stats << ['Edges - Q1', connection_stats[:q1]]
	stats << ['Edges - Median', connection_stats[:median]]
	stats << ['Edges - Q3', connection_stats[:q3]]
	stats << ['Edges - Min Non Zero', primary_stats[:minNonZero]]
	stats << ['Edges - Average Non Zero', connection_stats[:averageNonZero]]
	stats << ['Edges - Variance Non Zero', connection_stats[:varianceNonZero]]
	stats << ['Edges - Standard Deviation Non Zero', connection_stats[:standardDeviationNonZero]]
	stats << ['Edges - Q1 Non Zero', connection_stats[:q1NonZero]]
	stats << ['Edges - Median Non Zero', connection_stats[:medianNonZero]]
	stats << ['Edges - Q3 Non Zero', connection_stats[:q3NonZero]]
	return stats
end

def get_connection_number(matrix)
	rows, cols = matrix.shape
	connections = Numo::DFloat.zeros(1, cols)
	cols.times do |i|
		column = matrix[true, i]
		count = 0
		column.each do |value|
			count += 1 if value != 0
		end
		connections[0, i] = count - 1 # the connection with self is removed
	end
	return connections
end

def transform_keys(hash)
	new_hash = {}
	hash.each do |key, val|
		new_key = yield(key)
		new_hash[new_key] = val
	end
	return new_hash
end

def get_primary_stats(matrix)
	stats = Hash.new(0)
	max = matrix[0, 0] # Initialize max value
	min = matrix[0, 0] # Initialize min value
	min_non_zero = matrix[0, 0] # Initialize min value
	matrix.each do |value|
		stats[:count] += 1
		stats[:countNonZero] += 1 if value != 0
		stats[:sum] += value
		max = value if value > max
		min = value if value < min
		min_non_zero = value if value != 0 && value < min
	end
	stats[:max] = max
	stats[:min] = min
	stats[:minNonZero] = min_non_zero
	values = matrix.to_a
	values.flatten! if values.first.class == Array
	values.sort!
	quartile_stats = get_quartiles(values, stats[:count])
	stats.merge!(transform_keys(quartile_stats){|k| k.to_sym})
	values.select!{|v| v != 0}
	quartile_stats_non_zero = get_quartiles(values, stats[:countNonZero])
	stats.merge!(transform_keys(quartile_stats_non_zero){|k| (k + 'NonZero').to_sym})
	get_composed_stats(stats, matrix)
	return stats
end

def get_quartiles(values, n_items)
	stats = {}
	q1_coor = n_items * 0.25 - 1
	median = n_items * 0.5 - 1
	q3_coor = n_items * 0.75 - 1
	if n_items % 2 == 0
		stats['q1'] = (values[q1_coor.to_i] + values[q1_coor.to_i + 1]).fdiv(2)
		stats['median'] = (values[median.to_i] + values[median.to_i + 1]).fdiv(2)
		stats['q3'] = (values[q3_coor.to_i] + values[q3_coor.to_i + 1]).fdiv(2)
	else
		stats['q1'] = values[q1_coor.ceil]
		stats['median'] = values[median.ceil]
		stats['q3'] = values[q3_coor.ceil]
	end
	return stats
end

def get_composed_stats(stats, matrix)
	average = stats[:sum].fdiv(stats[:count])
	average_non_zero = stats[:sum].fdiv(stats[:countNonZero])
	stats[:average] = average
	stats[:averageNonZero] = average_non_zero
	matrix.each do |value|
		stats[:sumDevs] = (value - average) ** 2
		stats[:sumDevsNonZero] = (value - average_non_zero) ** 2 if value != 0
	end
	stats[:variance] = stats[:sumDevs].fdiv(stats[:count])
	stats[:varianceNonZero] = stats[:sumDevsNonZero].fdiv(stats[:countNonZero])
	stats[:standardDeviation] = stats[:variance] ** 0.5
	stats[:standardDeviationNonZero] = stats[:varianceNonZero] ** 0.5
end

#############################################################################
## OPTPARSE
##############################################################################
options = {}

optparse = OptionParser.new do |opts|
    options[:input_file] = nil
    opts.on( '-i', '--input_file PATH', 'Input file' ) do |opt|
        options[:input_file] = opt
    end

    options[:output_matrix_file] = nil
    opts.on( '-o', '--output_matrix_file PATH', 'Output matrix file' ) do |opt|
        options[:output_matrix_file] = opt
    end

    options[:byte_format] = :float64
    opts.on( '-b', '--byte_format STRING', 'Format of the numeric values stored in matrix. Default: float64, warning set this to less precission can modify computation results using this matrix.' ) do |opt|
        options[:byte_format] = opt.to_sym
    end

    options[:input_type] = 'pair'
    opts.on( '-t', '--input_type STRING', 'Set input format file. "pair" or "matrix"' ) do |opt|
        options[:input_type] = opt
    end

    options[:set_diagonal] = false
    opts.on( '-d', '--set_diagonal', 'Set to 1.0 the main diagonal' ) do
        options[:set_diagonal] = true
    end

    options[:binarize] = nil
    opts.on( '-B', '--binarize FLOAT', 'Binarize matrix changin x >= thr to one and any other to zero into matrix given' ) do |opt|
        options[:binarize] = opt.to_f
    end

    options[:cutoff] = nil
    opts.on( '-c', '--cutoff FLOAT', 'Cutoff matrix values keeping just x >= and setting any other to zero into matrix given' ) do |opt|
        options[:cutoff] = opt.to_f
    end

    options[:stats] = false
    opts.on( '-s', '--get_stats', 'Get stats from the processed matrix' ) do
        options[:stats] = true
    end

    options[:output_type] = 'bin'
    opts.on( '-O', '--output_type STRING', 'Set output format file. "bin" for binary (default) or "mat" for tabulated text file matrix' ) do |opt|
        options[:output_type] = opt
    end

   opts.banner = "Usage: #{File.basename(__FILE__)} [options] \n\n"

    opts.on( '-h', '--help', 'Display this screen' ) do
            puts opts
            exit
    end
end

optparse.parse!

################################################################################
## MAIN
###############################################################################
if options[:input_file] == '-'
	source = STDIN
else
	source = File.open(options[:input_file])
end

if options[:input_type] == 'bin'
	matrix = Npy.load(options[:input_file])
	#matrix = Marshal.load(File.binread(options[:input_file])) # the method needs a path not a IO object
elsif options[:input_type] == 'matrix'
	matrix = load_matrix_file(source)
elsif options[:input_type] == 'pair'
	matrix, names = load_pair_file(source, options[:byte_format])
	File.open(options[:output_matrix_file]+'.lst', 'w'){|f| f.print names.join("\n")}
end

if options[:set_diagonal]
	elements = matrix.shape.last
	elements.times do |n|
		matrix[n, n] = 1.0
	end
end

if !options[:binarize].nil? && options[:cutoff].nil?
	elements = matrix.shape.last
	elements.times do |i|
		elements.times do |j|
			matrix[i,j] = matrix[i,j] >= options[:binarize] ? 1 : 0
		end
	end
end

if !options[:cutoff].nil? && options[:binarize].nil?
	elements = matrix.shape.last
	elements.times do |i|
		elements.times do |j|
			matrix[i,j] = matrix[i,j] >= options[:cutoff] ? matrix[i,j] : 0
		end
	end
end

if options[:stats]
	stats = get_stats(matrix)
	stats.each do |stat|
		puts stat.join("\t")
	end
end

if options[:output_type] == 'bin'
	#File.binwrite(options[:output_matrix_file], Marshal.dump(matrix))
	Npy.save(options[:output_matrix_file], matrix)
elsif options[:output_type] == 'mat'
	File.open(options[:output_matrix_file], 'w') do |f|
		matrix.each_over_axis(0) do |r|
			f.puts r.to_a.join("\t")
		end
	end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Stapler</servlet-name>
        <servlet-class>org.kohsuke.stapler.Stapler</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Stapler</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>net.joinedminds.staplertest.WebAppMain</listener-class>
    </listener>

    <display-name>Archetype Created Web Application</display-name>
</web-app>


text:
from . import api
from flask import jsonify
from ..models import Comment

@api.route('/comments/')
def get_comments():
    comments = Comment.query.all()
    return jsonify({'comments':[comment.to_json() for comment in comments]})

@api.route('/comments/<int:id>')
def get_comment(id):
    comment = Comment.query.get_or_404(id)
    return jsonify(comment.to_json())


text:
package com.iceblue.appbaseutils.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;

/**
 * Created by AntonioTorres on 20/05/15.
 */
public class AppSessionStore {

    private static AppSessionStore mInstance = null;
    public static String KEY = "Base_app_name";
    private Context context = null;

    private AppSessionStore(Context contextIn){
        this.context = contextIn;
    }

    public synchronized static AppSessionStore getInstance(Context contextIn){
        if(mInstance == null)
        {
            mInstance = new AppSessionStore(contextIn);
        }
        return mInstance;
    }

    public void resetPreferences(){
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.clear().commit();
    }

    public boolean save(Map<String,String> data){
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            editor.putString(entry.getKey(), entry.getValue());
        }
        return editor.commit();
    }

    public  boolean save(String key, String value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putString(key, value);
        return editor.commit();
    }

    public  boolean save( String key, int value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putInt(key, value);
        return editor.commit();
    }

    public  boolean save( String key, Boolean value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }

    public  boolean save( String key, float value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putFloat(key, value);
        return editor.commit();
    }

    public  boolean save( String key, long value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putLong(key, value);
        return editor.commit();
    }

    public  String restore( String key) {
        SharedPreferences savedSession = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return savedSession.getString(key, null);
    }

    public  String restore( String key , String defaultValue) {
        SharedPreferences savedSession = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return savedSession.getString(key, defaultValue);
    }

    public static String restore(Context context,  String key) {
        SharedPreferences savedSession = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return savedSession.getString(key, null);
    }

    public  boolean restoreBoolean( String key) {
        SharedPreferences savedSession = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return savedSession.getBoolean(key, false);
    }

    public  int restoreInteger( String key) {
        SharedPreferences savedSession = context.getSharedPreferences(
                KEY, Context.MODE_PRIVATE);
        return savedSession.getInt(key, 0);
    }

    public  int restoreInteger( String key, Integer defaultValue) {
        SharedPreferences savedSession = context.getSharedPreferences(
                KEY, Context.MODE_PRIVATE);
        return savedSession.getInt(key, defaultValue);
    }

    public  float restoreFloat( String key) {
        SharedPreferences savedSession = context.getSharedPreferences(
                KEY, Context.MODE_PRIVATE);
        return savedSession.getFloat(key, 0f);
    }

    public  long restoreLong( String key) {
        SharedPreferences savedSession = context.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return savedSession.getLong(key, 0L);
    }

}


text:
<!DOCTYPE html>

    <title>Prométhée preview resize on mobile is supposed to display a smaller srcset image</title>

      <button id="resize_button">Resize</button>
      <button id="destroy_srcset">Destroy srcset</button>

Witness :


text:
#ifndef TUDAT_KERNELDENSITYDISTRIBUTION_H
#define TUDAT_KERNELDENSITYDISTRIBUTION_H

#include <map>
#include <boost/make_shared.hpp>
#include <memory>

#include "Tudat/Mathematics/Statistics/continuousProbabilityDistributions.h"
#include "Tudat/Mathematics/Statistics/boostProbabilityDistributions.h"
namespace tudat
{

namespace statistics
{

//! Class for Probability distribution using a single Epanechnikov kernel
class EpanechnikovKernelDistribution: public tudat::statistics::ContinuousProbabilityDistribution< double >
{
public:

    //! Constructor
    /*!
     * Constructor
     * \param mean Kernel mean
     * \param bandWidth Kernel bandwidth
     */
    EpanechnikovKernelDistribution( const double mean, const double bandWidth ):
        mean_( mean ), bandWidth_( bandWidth ){ }

    //! Function to evaluate pdf of distribution
    /*!
     *  Function to evaluate probability distribution function at given independentVariable value.
     *  \param independentVariable Value of independent variable
     *  \return Evaluated pdf
     */
    double evaluatePdf( const double& independentVariable );

    //! Function to evaluate cdf of distribution
    /*!
     *  Function to evaluate cumulative distribution function at given independentVariable value.
     *  \param independentVariable Value of independent variable
     *  \return Evaluated cdf
     */
    double evaluateCdf( const double& independentVariable );

protected:

private:

    //! Mean of the kernel
    double mean_;

    //! Bandwidth of the kernel
    double bandWidth_;
};

//! Kernel type that is used in the Kernel Density Estimate
enum KernelType
{
    gaussian_kernel = 0,
    epanechnikov_kernel = 1
};

//! Class that uses random samples to generate a multivariate probability distribution using Kernel Density distribution.
/*!
 *  Class that uses random samples to generate a multivariate probability distribution using Kernel Density distribution.
 *  The bandwidth of the kernels may be supplied by the user, or an optimal distrubution may be computed by this class
 *  At present, the user has the choice of a Gaussian or Epanechnikov distribution for the kernels.
 */
class KernelDensityDistribution: public tudat::statistics::ContinuousProbabilityDistribution< Eigen::VectorXd >
{

public:

    //! Constructor
    /*!
     * Constructor
     * \param samples Data samples from which the empirical distribution is to be created.
     * \param bandWidthFactor Factor by which to multiply the computed bandwidth values of the kernels.
     * \param kernel_type Type of distribution to be used for the kernels in the distribution.
     * \param manualStandardDeviation Standard deviations with which to scale the entries of each sample. By default this
     * vector is empty and not used. If it is provided, it is used to scale the entry i of each sample by
     * manualStandardDeviation( i ) / sampleStandardDeviation( i ), where sampleStandardDeviation is the standard
     * deviation computed from the samples/
     * \param manualBandwidth Vector of bandwidths for each dimension that is to be used in the kernels. By default this
     * vector is empty and not used. Optimal bandwidths (scaled by bandWidthFactor) are used in this default case.
     */
    KernelDensityDistribution(
            const std::vector< Eigen::VectorXd >& samples,
            const double bandWidthFactor = 1.0,
            const KernelType kernel_type = KernelType::gaussian_kernel,
            const Eigen::VectorXd& manualStandardDeviation = Eigen::VectorXd::Zero( 0 ),
            const Eigen::VectorXd& manualBandwidth = Eigen::VectorXd::Zero( 0 ) );

    //! Function to evaluate pdf of distribution
    /*!
     *  Function to evaluate probability distribution function at given independentVariable value.
     *  \param independentVariables Values of independent variable
     *  \return Evaluated pdf
     */
    double evaluatePdf( const Eigen::VectorXd& independentVariables );

    //! Function to evaluate cdf of distribution
    /*!
     *  Function to evaluate cumulative distribution function at given independentVariable value.
     *  \param independentVariables Values of independent variable
     *  \return Evaluated cdf
     */
    double evaluateCdf( const Eigen::VectorXd& independentVariables );

    //! Function to evaluate probability density of marginal (in one or more dimensions) distribution.
    /*!
     * Function to evaluate probability density of marginal (in one or more dimensions) distribution,
     * \param marginalDimensions Dimensions over which the marginal probaility is to be computed
     * \param independentVariables Values of independent variables (in marginalDimensions) at which marginal
     * probability is to be computed
     * \return Probability density of marginal distribution.
     */
    double evaluateMarginalProbabilityDensity(
            const std::vector< int >& marginalDimensions, const Eigen::VectorXd& independentVariables );

    //! Function to evaluate marginal distribution density at single dimension.
    /*!
     * Function to evaluate marginal distribution density at single dimension.
     *  \param marginalDimension Dimension in which the marginal distribution is to be computed
     *  \param independentVariable Value of independent variable in dimension marginalDimension
     *  \return Probability density of marginal distribution at given dimension and independent variable.
     */
    double evaluateMarginalProbabilityDensity( const int marginalDimension, const double independentVariable );

    //! Function to evaluate cumulative probability of marginal distribution at single dimension.
    /*!
     *  Function to evaluate cumulative probability of marginal distribution at single dimension.
     *  \param marginalDimension Dimension in whihc the marginal distribution is to be computed
     *  \param independentVariable Value of independent variable in dimension marginalDimension
     *  \return cumulative probability of marginal distribution at given dimension and independent variable.
     */
    double evaluateCumulativeMarginalProbability( const int marginalDimension, const double independentVariable );

    //! Function to evaluate cumulative probability of marginal distribution of conditional distribution at single dimension
    /*!
     * Function to evaluate cumulative probability of marginal distribution of conditional distribution at single dimension,
     * given conditions of cdf on other dimensions
     * \param conditionDimensions List of dimensions in which cdf is given
     * \param conditions Independent variables at which values of cdf, in dimensions listed in conditionDimensions,
     * are to be computed.
     * \param marginalDimension Dimension in which the marginal cdf is to be computed
     * \param independentVariable Independent variable at which conditional marginal cdf is to be computed
     * \return Cumulative conditional probability of marginal distribution at given settings.
     */
    double evaluateCumulativeConditionalMarginalProbability(
            const std::vector< int >& conditionDimensions,
            const std::vector< double >& conditions,
            const int marginalDimension, const double independentVariable );

    //! Function to evaluate probability density of marginal distribution of conditional distribution at single dimension
    /*!
     * Function to evaluate probability density of marginal distribution of conditional distribution at single dimension,
     * given conditions of cdf on other dimensions
     * \param conditionDimensions List of dimensions in which pdf is given
     * \param conditions Independent variables at which values of pdf, in dimensions listed in conditionDimensions,
     * are to be computed.
     * \param marginalDimension Dimension in which the marginal pdf is to be computed
     * \param independentVariable Independent variable at which conditional marginal pdf is to be computed
     * \return Conditional pdf of marginal distribution at given settings.
     */
    double evaluateConditionalMarginalProbabilityDensity(
            const std::vector< int >& conditionDimensions,
            const std::vector< double >& conditions,
            const int marginalDimension, const double independentVariable );

    //! Compute optimal bandwidth using the provided samples.
    void computeOptimalBandWidth( );

    //! Function to retrieve the optimal bandwidth
    /*!
     * Function to retrieve the optimal bandwidth
     * \return Optimal bandwidth
     */
    Eigen::VectorXd getOptimalBandWidth( )
    {
        return optimalBandwidth_;
    }

    //! Function to retrieve the bandwidth
    /*!
     * Function to retrieve the bandwidth
     * \return Bandwidth
     */
    Eigen::VectorXd getBandWidth( )
    {
        return bandWidth_;
    }

    //! Function to retrieve the data samples used to generate kernel density distribution.
    /*!
     * Function to retrieve the data samples used to generate kernel density distribution.
     * \return Data samples used to generate kernel density distribution.
     */
    std::vector< Eigen::VectorXd > getSamples( )
    {
        return dataSamples_;
    }

    //! Function to manually reset the bandwidth
    /*!
     * Function to manually reset the bandwidth. Calling this function automatically recomputes the kernels.
     * \param bandWidth New bandwidth to be used for each dimension.
     */
    void setBandWidth( const Eigen::VectorXd& bandWidth )
    {
        bandWidth_ = bandWidth;
        generateKernelPointerMatrix( ); // Reset kernels
    }

    //! Function to retrieve the sample mean.
    /*!
     * Function to retrieve the sample mean.
     * \return Sample mean.
     */
    Eigen::VectorXd getSampleMean( )
    {
        return sampleMean_;
    }

    //! Function to retrieve the sample variance.
    /*!
     * Function to retrieve the sample variance.
     * \return Sample variance.
     */
    Eigen::VectorXd getSampleVariance( )
    {
        return sampleVariance_;
    }

    //! Function to retrieve the sample standard deviation.
    /*!
     * Function to retrieve the sample standard deviation.
     * \return Sample standard deviation.
     */
    Eigen::VectorXd getSampleStandardDeviation( )
    {

        return sampleStandardDeviation_;
    }

    //! Function to retrieve the number of samples.
    /*!
     * Function to retrieve the number of samples.
     * \return Number of samples.
     */
    int getNumberOfSamples( )
    {
        return numberOfSamples_;
    }

protected:

private:

    //! Function that constructs a single kernel.
    /*!
     * Function that constructs a single kernel, called iteratively to construct the full multivariate kernel density.
     * \param mean Mean value of kernel that is to be created.
     * \param bandWidth Bandwidth of kernel thatr is to be created.
     * \return Probability distribution for single kernel.
     */
    std::shared_ptr< ContinuousProbabilityDistribution< double > > constructKernel(
            const double mean, const double bandWidth )
    {
        std::shared_ptr< ContinuousProbabilityDistribution< double > > kernelPointer;

        // Check kernel type and create selected kernel.
        if( kernelType_ == KernelType::epanechnikov_kernel )
        {
            kernelPointer = std::make_shared< EpanechnikovKernelDistribution >( mean, bandWidth );
        }
        else if( kernelType_ == KernelType::gaussian_kernel )
        {
            kernelPointer = createBoostRandomVariable(
                        normal_boost_distribution, { mean, bandWidth } );
        }
        else
        {
            throw std::runtime_error( "Error when constructing probability kernels, kernel type not recognized" );
        }

        return kernelPointer;
    }

    //! Function that generates the kernel density distribution based on the samples and kernel type that is provided
    /*!
     *  Function that generates the kernel density distribution based on the samples and kernel type that is provided.
     *  This function iteratively calls the constructKernel function to create a kernel for each entry in each sample.
     */
    void generateKernelPointerMatrix( );

    //! Function that computes and sets the sample mean.
    /*!
     *  Function that computes and sets the sample mean (sampleMean_ variable).
     */
    void computeSampleMean( );

    //! Function that computes and sets the sample variance and standard deviation.
    /*!
     *  Function that computes and sets the sample variance and standard deviation
     *  (sampleVariance_ and sampleStandardDeviation_ variable).
     */
    void computeSampleVariance( );

    //! Function to scale the samples to the required standard deviation
    /*!
     *  Function to scale the samples to the required standard deviation
     *  \param standardDeviation New standard deviation that the data is to have.
     */
    void scaleSamplesWithVariance( const Eigen::VectorXd& standardDeviation );

    //! Function to retrieve the sample set median
    /*!
     * Function to retrieve the sample set median
     * \param samples Set of samples from which the (per entry) median is to be computed.
     * \return Sample set median
     */
    Eigen::VectorXd getMedian( const std::vector< Eigen::VectorXd >& samples );

    //! Datasamples
    std::vector< Eigen::VectorXd > dataSamples_;

    //! Sample mean (per entry)
    Eigen::VectorXd sampleMean_;

    //! Sample variance (per entry)
    Eigen::VectorXd sampleVariance_;

    //! Sample standard deviation (per entry)
    Eigen::VectorXd sampleStandardDeviation_;

    //! Kernel type
    KernelType kernelType_;

    //! Bandwidth of Kernels
    Eigen::VectorXd bandWidth_;

    //! Optimal bandwidth of Kernels.
    Eigen::VectorXd optimalBandwidth_;

    //! Number of dimensions of the samples and distribution.
    int dimensions_;

    //! Number of datasamples
    int numberOfSamples_;

    //! Matrix (vector of vectors) of 1D kernel pointers that define full kernel density distribution.
    std::vector< std::vector< std::shared_ptr< ContinuousProbabilityDistribution< double > > > > kernelPointersMatrix_;

};

//! Pointer to Kernel Density distribution class
typedef std::shared_ptr< KernelDensityDistribution > KernelDensityDistributionPointer;

} // namespace statistics

} // namespace tudat

#endif // TUDAT_KERNELDENSITYDISTRIBUTION_H


text:
/* eslint max-lines: 0 */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { GoogleMap, withGoogleMap, Marker, InfoWindow } from "react-google-maps";
import MarkerClusterer from "react-google-maps/lib/components/addons/MarkerClusterer";
import classNames from "classnames";
import {
	AppbaseChannelManager as manager,
	AppbaseSensorHelper as helper,
	PoweredBy
} from "@appbaseio/reactivebase";
import _ from "lodash";
import SearchAsMove from "../addons/SearchAsMove";
import { MapStyles, mapStylesCollection } from "../addons/MapStyles";
import * as ReactiveMapHelper from "../helper/ReactiveMapHelper";

const MapComponent = (withGoogleMap((props) => {
	const { children, onMapMounted, ...allProps } = props;

	return (
		<GoogleMap ref={onMapMounted} {...allProps}>
			{children}
		</GoogleMap>
	);
}));

export default class ReactiveMap extends Component {
	constructor(props) {
		super(props);
		this.state = {
			markers: [],
			selectedMarker: null,
			streamingStatus: "Initializing..",
			defaultCenter: this.props.defaultCenter ? this.props.defaultCenter : { lat: 37.74, lon: -122.45 },
			center: this.props.defaultCenter,
			query: {},
			rawData: {
				hits: {
					hits: []
				}
			},
			currentData: [],
			externalData: {},
			mapBounds: null
		};
		this.geoRelatedEvents = ["onDragend", "onZoomChanged"];
		this.previousSelectedSensor = {};
		this.searchAsMoveChange = this.searchAsMoveChange.bind(this);
		this.mapStyleChange = this.mapStyleChange.bind(this);
		this.geoCustomQuery = this.geoCustomQuery.bind(this);
		this.handleMarkerClose = this.handleMarkerClose.bind(this);
		this.queryStartTime = 0;
		this.reposition = false;
		this.mapDefaultHeight = "700px";
	}

	componentDidMount() {
		this.streamProp = this.props.stream;
		this.sizeProp = this.props.size;
		this.initialize();
	}

	componentWillReceiveProps(nextProps) {
		if (!_.isEqual(this.props.react, nextProps.react)) {
			this.setReact(nextProps);
			manager.update(this.channelId, this.react, nextProps.size, nextProps.from, nextProps.stream);
		}

		if (nextProps.defaultMapStyle !== this.props.defaultMapStyle) {
			this.mapStyleChange(this.getMapStyle(nextProps.defaultMapStyle));
		}
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		this.removeChannel();
	}

	removeChannel() {
		if (this.channelId) {
			manager.stopStream(this.channelId);
			this.channelId = null;
		}
		if (this.channelListener) {
			this.channelListener.remove();
		}
	}

	initialize(updateExecute = false) {
		this.setGeoQueryInfo();
		this.setReact(this.props);
		this.createChannel(updateExecute);
		const currentMapStyle = this.getMapStyle(this.props.defaultMapStyle);
		this.initialMapBoundQuery = !!this.props.defaultCenter;
		this.applyGeoQuery = this.props.applyGeoQuery ? this.props.applyGeoQuery : this.props.setSearchAsMove;
		this.setState({
			currentMapStyle
		});
	}

	getMapStyle(styleName) {
		const selectedStyle = mapStylesCollection.filter(style => style.key === styleName);

		if (selectedStyle.length) {
			return selectedStyle[0].value;
		}
		return null;
	}

	setReact(props) {
		// Set the actuate - add self aggregation query as well with actuate
		const react = Object.assign({}, props.react);
		const reactOr = ["geoQuery"];
		const reactAnd = ["streamChanges"];
		this.react = helper.setupReact(react, reactAnd);
		this.react = ReactiveMapHelper.setupOrReact(this.react, reactOr);
	}

	// Create a channel which passes the actuate and receive results whenever actuate changes
	createChannel() {
		// create a channel and listen the changes
		const channelObj = manager.create(this.context.appbaseRef, this.context.type, this.react, this.props.size, this.props.from, this.props.stream);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(channelObj.channelId, (res) => {
			const data = res.data;
			// implementation to prevent initialize query issue if old query response is late then the newer query
			// then we will consider the response of new query and prevent to apply changes for old query response.
			// if queryStartTime of channel response is greater than the previous one only then apply changes

			function checkAndGo() {
				if (res.mode === "historic" && res.startTime > this.queryStartTime) {
					this.afterChannelResponse(res);
				} else if (res.mode === "streaming") {
					this.afterChannelResponse(res);
				}
			}

			function initialize() {
				if (res.error && res.startTime > this.queryStartTime) {
					if (this.props.onAllData) {
						const modifiedData = helper.prepareResultData(res);
						this.props.onAllData(modifiedData.res, modifiedData.err);
					}
				} else if (res.appliedQuery) {
					if (!this.state.mapBounds) {
						checkAndGo.call(this);
					} else if (this.props.autoMapRender) {
						checkAndGo.call(this);
					} else if (data.hits.hits.length) {
						checkAndGo.call(this);
					}
				}
			}

			initialize.call(this);
		});
		const obj = {
			key: "streamChanges",
			value: ""
		};
		helper.selectedSensor.set(obj, true);
	}

	afterChannelResponse(res) {
		const getResult = ReactiveMapHelper.afterChannelResponse(res, this.state.rawData, this.props.dataField, this.state.markersData);
		this.reposition = true;
		this.streamFlag = getResult.streamFlag;
		this.queryStartTime = getResult.queryStartTime ? getResult.queryStartTime : 0;
		this.setState({
			rawData: getResult.rawData,
			markersData: getResult.markersData
		}, () => {
			if (this.props.onAllData) {
				// Pass the historic or streaming data in index method
				res.allMarkers = getResult.rawData;
				let modifiedData = JSON.parse(JSON.stringify(res));
				modifiedData.newData = getResult.newData;
				modifiedData.currentData = getResult.currentData;
				delete modifiedData.data;
				modifiedData = helper.prepareResultData(modifiedData, res.data);
				if (this.props.onAllData) {
					if (modifiedData.res) {
						modifiedData.res.mapRef = this.mapRef;
					}
					const generatedData = this.props.onAllData(modifiedData.res, modifiedData.err);
					this.setState({
						externalData: generatedData
					});
				}
			}
			if (this.streamFlag) {
				this.streamMarkerInterval();
			}
		});
	}

	// set the query type and input data
	setGeoQueryInfo() {
		const obj = {
			key: "geoQuery",
			value: {
				queryType: "geo_bounding_box",
				inputData: this.props.dataField,
				customQuery: this.geoCustomQuery
			}
		};
		const obj1 = {
			key: "updateExecute",
			value: {
				queryType: "random",
				inputData: this.props.dataField
			}
		};

		helper.selectedSensor.setSensorInfo(obj);
		helper.selectedSensor.setSensorInfo(obj1);
	}

	geoCustomQuery(value) {
		let query = null;
		if (value && (this.initialMapBoundQuery || this.searchAsMove)) {
			query = {
				geo_bounding_box: {
					[this.props.dataField]: value
				}
			};
			if (this.geoRelatedEventsChange) {
				this.geoRelatedEventsChange = false;
			} else if (this.applyGeoQuery) {
				this.applyGeoQuery = false;
			}
			this.initialMapBoundQuery = false;
		}
		return query;
	}

	updateExecute() {
		setTimeout(() => {
			const obj = {
				key: "updateExecute",
				value: Math.random()
			};
			helper.selectedSensor.set(obj, true);
		}, 1000);
	}

	// Show InfoWindow and re-renders component
	handleMarkerClick(marker) {
		marker.showInfo = true;
		this.reposition = false;
		this.setState({
			rerender: true
		}, () => {
			if (this.props.popoverTTL) {
				this.watchPopoverTTL(marker);
			}
		});
	}

	// Close info window
	handleMarkerClose(marker) {
		marker.showInfo = false;
		this.reposition = false;
		this.setState(this.state);
	}

	// watch and close popover on timeout
	watchPopoverTTL(marker) {
		this.popoverTTLStore = this.popoverTTLStore ? this.popoverTTLStore : {};
		if (this.popoverTTLStore[marker._type + marker._id]) {
			this.clearTTL(marker._type + marker._id);
		} else {
			this.popoverTTLStore[marker._type + marker._id] = setTimeout(() => {
				this.handleMarkerClose(marker);
				this.clearTTL(marker._type + marker._id);
			}, this.props.popoverTTL * 1000);
		}
	}

	clearTTL(id) {
		clearTimeout(this.popoverTTLStore[id]);
		delete this.popoverTTLStore[id];
	}

	// render info window
	renderInfoWindow(ref, marker) {
		const onPopoverTrigger = this.props.onPopoverTrigger ? this.props.onPopoverTrigger(marker) : "Popver";
		return (
			<InfoWindow
				zIndex={500}
				key={`${ref}_info_window`}
				onCloseClick={() => this.handleMarkerClose(marker)}
			>

					{onPopoverTrigger}

			</InfoWindow>
		);
	}

	// Handle function which is fired when map is moved and reaches to idle position
	handleOnIdle() {
		const mapBounds = this.mapRef ? this.mapRef.getBounds() : null;
		if (mapBounds) {
			const north = mapBounds.getNorthEast().lat();
			const south = mapBounds.getSouthWest().lat();
			const east = mapBounds.getNorthEast().lng();
			const west = mapBounds.getSouthWest().lng();
			const boundingBoxCoordinates = {
				top_left: [west, north],
				bottom_right: [east, south]
			};
			const stateObj = {
				mapBounds
			};
			if (this.props.onIdle) {
				const generatedData = this.props.onIdle(this.mapRef, {
					boundingBoxCoordinates,
					mapBounds
				});
				stateObj.externalData = generatedData;
			}
			if (this.initialMapBoundQuery || (this.applyGeoQuery || (this.geoRelatedEventsChange && this.searchAsMove && !this.searchQueryProgress))) {
				const flag = this.initialMapBoundQuery ? true : (this.applyGeoQuery ? this.applyGeoQuery : this.searchAsMove);
				this.setValue(boundingBoxCoordinates, flag);
			}
			if (!_.isEqual({ mapBounds: this.state.mapBounds }, stateObj)) {
				this.setState(stateObj);
			}
		}
	}

	// Handle function which is fired when map is dragged
	handleOnDrage() {
		this.storeCenter = null;
	}

	// set value
	setValue(value, isExecuteQuery = false) {
		const obj = {
			key: "geoQuery",
			value
		};
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	// on change of selecting
	searchAsMoveChange(value) {
		this.searchAsMove = value;
		if (value && this.mapRef) {
			this.geoRelatedEventsChange = true;
			this.handleOnIdle();
		}
	}

	// mapStyle changes
	mapStyleChange(style) {
		this.setState({
			currentMapStyle: style
		});
	}

	// Handler function for bounds changed which udpates the map center
	handleBoundsChanged() {
		if (!this.searchQueryProgress) {
			// this.setState({
			//   center: this.mapRef.getCenter()
			// });
		} else {
			setTimeout(() => {
				this.searchQueryProgress = false;
			}, 1000 * 1);
		}
	}

	// Check if stream data exists in markersData
	// and if exists the call streamToNormal.
	streamMarkerInterval() {
		const markersData = this.state.markersData;
		const isStreamData = markersData.filter(hit => hit.stream && hit.streamStart);
		if (isStreamData.length) {
			this.isStreamDataExists = true;
			setTimeout(() => this.streamToNormal(), this.props.streamTTL * 1000);
		} else {
			this.isStreamDataExists = false;
		}
	}

	// Check the difference between current time and attached stream time
	// if difference is equal to streamTTL then delete stream and starStream property of marker
	streamToNormal() {
		let markersData = this.state.markersData;
		const isStreamData = markersData.filter(hit => hit.stream && hit.streamStart);
		if (isStreamData.length) {
			markersData = markersData.map((hit) => {
				if (hit.stream && hit.streamStart) {
					const currentTime = new Date();
					const timeDiff = (currentTime.getTime() - hit.streamStart.getTime()) / 1000;
					if (timeDiff >= this.props.streamTTL) {
						delete hit.stream;
						delete hit.streamStart;
					}
				}
				return hit;
			});
			this.setState({
				markersData
			});
		} else {
			this.isStreamDataExists = false;
		}
	}

	getIcon(hit) {
		return hit.stream ? this.props.streamMarkerImage : this.props.defaultMarkerImage;
	}

	chooseIcon(hit) {
		let icon = hit.external_icon ? hit.external_icon : this.getIcon(hit);
		icon = this.props.onData ? this.props.onData(hit) : icon;
		const isSvg = !!(typeof icon === "object" && ("path" in icon));
		if (isSvg) {
			icon = JSON.parse(JSON.stringify(icon));
			if (this.props.autoMarkerPosition) {
				const deg = hit.angleDeg ? hit.angleDeg : 0;
				icon.rotation = deg;
			}
		}
		return icon;
	}

	// here we accepts marker props which we received from onAllData and apply those external props in Marker component
	combineProps(hit) {
		let externalProps;
		const markerProp = {};
		if (this.state.externalData && this.state.externalData.markers && this.state.externalData.markers[hit._id]) {
			externalProps = this.state.externalData.markers[hit._id];
			Object.keys(externalProps).forEach((externalP) => {
				hit[`external_${externalP}`] = externalProps[externalP];
				markerProp[externalP] = externalProps[externalP];
			});
		}
		markerProp.icon = this.chooseIcon(hit);
		return markerProp;
	}

	generateMarkers() {
		const self = this;
		let markersData = this.state.markersData;
		const response = {
			markerComponent: [],
			defaultCenter: null,
			convertedGeo: []
		};
		if (markersData && markersData.length) {
			markersData = markersData.filter(hit => ReactiveMapHelper.identifyGeoData(hit._source[self.props.dataField]));
			response.markerComponent = markersData.map((hit, index) => {
				const field = ReactiveMapHelper.identifyGeoData(hit._source[self.props.dataField]);
				response.convertedGeo.push(field);
				const position = {
					position: field
				};
				const ref = `marker_ref_${index}`;
				let popoverEvent;
				if (this.props.showPopoverOn) {
					popoverEvent = {};
					let eventName = this.props.showPopoverOn.split("");
					eventName[0] = eventName[0].toUpperCase();
					eventName = eventName.join("");
					popoverEvent[`on${eventName}`] = this.handleMarkerClick.bind(this, hit);
				} else {
					popoverEvent = {};
					popoverEvent.onClick = this.handleMarkerClick.bind(this, hit);
				}
				const defaultFn = function () {};
				const events = {
					onClick: this.props.markerOnClick ? this.props.markerOnClick : defaultFn,
					onDblClick: this.props.markerOnDblClick ? this.props.markerOnDblClick : defaultFn,
					onMouseOver: this.props.onMouseOver ? this.props.onMouseOver : defaultFn,
					onMouseOut: this.props.onMouseOut ? this.props.onMouseOut : defaultFn
				};
				return (
					<Marker
						{...position}
						key={hit._id}
						zIndex={1}
						ref={ref}
						{...self.combineProps(hit)}
						onClick={() => events.onClick(hit._source)}
						onDblClick={() => events.onDblClick(hit._source)}
						onMouseOver={() => events.onMouseOver(hit._source)}
						onMouseOut={() => events.onMouseOut(hit._source)}
						{...popoverEvent}
					>
						{hit.showInfo ? self.renderInfoWindow(ref, hit) : null}
					</Marker>
				);
			});
			if (response.convertedGeo[0]) {
				response.defaultCenter = {
					lat: response.convertedGeo[0].lat,
					lng: response.convertedGeo[0].lng
				};
			}
		}
		if (!this.props.showMarkers) {
			response.markerComponent = [];
		}
		return response;
	}

	externalData() {
		let recordList = [];
		if (this.state.externalData) {
			Object.keys(this.state.externalData).forEach((record) => {
				if (record !== "markers") {
					recordList = recordList.concat(this.state.externalData[record]);
				}
			});
		}
		return recordList;
	}

	mapEvents(eventName) {
		if (this.geoRelatedEvents.indexOf(eventName) > -1) {
			this.geoRelatedEventsChange = true;
		}
		if (this.props[eventName]) {
			const externalData = this.props[eventName](this.mapRef);
			if (externalData) {
				this.setState({
					externalData
				});
			}
		}
	}

	getStoreCenter() {
		return this.storeCenter ? this.storeCenter : this.state.center;
	}

	render() {
		let markerComponent,
			showSearchAsMove,
			showMapStyles;
		let title = null,
			center = null;
		const centerComponent = {};
		const generatedMarkers = this.generateMarkers();
		if (this.props.setMarkerCluster) {
			markerComponent = (<MarkerClusterer averageCenter enableRetinaIcons gridSize={60} >
				{generatedMarkers.markerComponent}
			</MarkerClusterer>);
		} else {
			markerComponent = generatedMarkers.markerComponent;
		}
		// Auto center using markers data
		let streamCenterFlag = true;
		if (this.channelMethod === "streaming" && !this.props.streamAutoCenter) {
			streamCenterFlag = false;
		}
		if (this.props.autoCenter && this.reposition && streamCenterFlag) {
			center = generatedMarkers.defaultCenter ? generatedMarkers.defaultCenter : this.getStoreCenter();
			this.storeCenter = center;
			this.reposition = false;
			centerComponent.center = ReactiveMapHelper.normalizeCenter(center);
		} else if (this.storeCenter) {
			center = this.storeCenter;
			centerComponent.center = ReactiveMapHelper.normalizeCenter(center);
		} else {
			center = null;
		}

		// include searchasMove component
		if (this.props.showSearchAsMove) {
			showSearchAsMove = <SearchAsMove searchAsMoveDefault={this.props.setSearchAsMove} searchAsMoveChange={this.searchAsMoveChange} />;
		}
		// include mapStyle choose component
		if (this.props.showMapStyles) {
			showMapStyles = <MapStyles defaultSelected={this.props.defaultMapStyle} mapStyleChange={this.mapStyleChange} />;
		}
		// include title if exists
		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title
		}, this.props.className);

		return (
			<div className={`rbc rbc-reactivemap col s12 col-xs-12 card thumbnail ${cx}`} style={ReactiveMapHelper.mapPropsStyles(this.props.style, "component")}>
				{title}
				{showMapStyles}
				<MapComponent
					onMapMounted={(ref) => {
						this.mapRef = ref;
					}}
					containerElement={
}
					mapElement={
}
					{...centerComponent}
					{...ReactiveMapHelper.normalizeProps(this.props)}
					options={{
						styles: this.state.currentMapStyle
					}}
					defaultCenter={ReactiveMapHelper.normalizeCenter(this.state.defaultCenter)}
					onDragStart={() => {
						this.handleOnDrage();
						this.mapEvents("onDragStart");
					}}
					onIdle={() => this.handleOnIdle()}
					onClick={() => this.mapEvents("onClick")}
					onDblClick={() => this.mapEvents("onDblClick")}
					onDrag={() => this.mapEvents("onDrag")}
					onDragEnd={() => this.mapEvents("onDragEnd")}
					onMouseMove={() => this.mapEvents("onMouseMove")}
					onMouseOut={() => this.mapEvents("onMouseOut")}
					onMouseOver={() => this.mapEvents("onMouseOver")}
					onResize={() => this.mapEvents("onResize")}
					onRightClick={() => this.mapEvents("onRightClick")}
					onTilesLoaded={() => this.mapEvents("onTilesLoaded")}
					onBoundsChanged={() => this.mapEvents("onBoundsChanged")}
					onCenterChanged={() => this.mapEvents("onCenterChanged")}
					onProjectionChanged={() => this.mapEvents("onProjectionChanged")}
					onTiltChanged={() => this.mapEvents("onTiltChanged")}
					onZoomChanged={() => this.mapEvents("onZoomChanged")}
				>
					{markerComponent}
					{this.externalData()}
				</MapComponent>
				{showSearchAsMove}
				<PoweredBy />

		);
	}
}

ReactiveMap.propTypes = {
	dataField: PropTypes.string.isRequired,
	onIdle: PropTypes.func,
	onAllData: PropTypes.func,
	onData: PropTypes.func,
	onPopoverTrigger: PropTypes.func,
	setMarkerCluster: PropTypes.bool,
	autoMarkerPosition: PropTypes.bool,
	showMarkers: PropTypes.bool,
	streamTTL: ReactiveMapHelper.validation.streamTTL,
	popoverTTL: ReactiveMapHelper.validation.popoverTTL,
	size: helper.sizeValidation,
	from: ReactiveMapHelper.validation.fromValidation,
	autoMapRender: PropTypes.bool,
	style: PropTypes.object,
	autoCenter: PropTypes.bool,
	showSearchAsMove: PropTypes.bool,
	setSearchAsMove: PropTypes.bool,
	defaultMapStyle: PropTypes.oneOf(["Standard", "Blue Essence", "Blue Water", "Flat Map", "Light Monochrome", "Midnight Commander", "Unsaturated Browns"]),
	title: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.element
	]),
	streamAutoCenter: PropTypes.bool,
	defaultMarkerImage: PropTypes.string,
	streamMarkerImage: PropTypes.string,
	stream: PropTypes.bool,
	defaultZoom: ReactiveMapHelper.validation.defaultZoom,
	applyGeoQuery: PropTypes.bool,
	showPopoverOn: PropTypes.oneOf(["click", "mouseover"]),
	defaultCenter: PropTypes.shape({
		lat: ReactiveMapHelper.validation.validCenter,
		lon: ReactiveMapHelper.validation.validCenter
	}),
	react: PropTypes.object,
	markerOnClick: PropTypes.func,
	markerOnDblClick: PropTypes.func,
	onMouseOver: PropTypes.func,
	onMouseOut: PropTypes.func,
	showMapStyles: PropTypes.bool,
	className: PropTypes.string
};

ReactiveMap.defaultProps = {
	setMarkerCluster: true,
	autoCenter: true,
	showSearchAsMove: true,
	setSearchAsMove: false,
	showMapStyles: true,
	defaultMapStyle: "Standard",
	from: 0,
	size: 100,
	streamTTL: 5,
	streamAutoCenter: false,
	autoMarkerPosition: false,
	showMarkers: true,
	autoMapRender: true,
	defaultMarkerImage: "https://opensource.appbase.io/reactivemaps/dist/images/historic-pin.png",
	streamMarkerImage: "https://opensource.appbase.io/reactivemaps/dist/images/stream-pin.png",
	style: {},
	stream: false,
	applyGeoQuery: false,
	defaultZoom: 13
};

ReactiveMap.contextTypes = {
	appbaseRef: PropTypes.any.isRequired,
	type: PropTypes.any.isRequired
};


text:
#pragma once

#include "paddle/phi/core/meta_tensor.h"
#include "paddle/phi/core/tensor_meta.h"

namespace phi {
namespace sparse {

void FusedAttentionGradInferMeta(const MetaTensor& query,
                                 const MetaTensor& key,
                                 const MetaTensor& value,
                                 const MetaTensor& softmax,
                                 const MetaTensor& out_grad,
                                 MetaTensor* query_grad,
                                 MetaTensor* key_grad,
                                 MetaTensor* value_grad);

}  // namespace sparse
}  // namespace phi


text:
import {CONST} from 'facade/lang';
import {DOM} from 'facade/dom';
import {Element} from 'facade/dom';
import {View} from './view';

export class ShadowDomStrategy {
  @CONST() constructor() {}
  attachTemplate(el:Element, view:View){}
}

export class EmulatedShadowDomStrategy extends ShadowDomStrategy {
  @CONST() constructor() {}
  attachTemplate(el:Element, view:View){
    DOM.clearNodes(el);
    moveViewNodesIntoParent(el, view);
  }
}

export class NativeShadowDomStrategy extends ShadowDomStrategy {
  @CONST() constructor() {}
  attachTemplate(el:Element, view:View){
    moveViewNodesIntoParent(el.createShadowRoot(), view);
  }
}

function moveViewNodesIntoParent(parent, view) {
  for (var i = 0; i < view.nodes.length; ++i) {
    DOM.appendChild(parent, view.nodes[i]);
  }
}


text:
namespace MGR.CommandLineParser.UnitTests.Extensions
{
    public partial class ConverterExtensionsTests
    {
        private static readonly string SourceParameterName = "source";
    }
}


text:
var socketClient = require('socket.io-client'),
    fs = require('fs'),
    path = require('path');

var BingoClient = function(options) {
  var _game = 'BINGO';
  var _client = null;
  var _slots = null;

  var _checkColumn = function(row, column) {
    for (var slotPropertyName in _slots) {
      if (_slots.hasOwnProperty(slotPropertyName)
        && slotPropertyName !== _game[row]) {
        if (_slots[slotPropertyName][column] != null) {
          console.info('Not yet, because of ' + slotPropertyName + column);
          return false;
        }
      }
    }
    return true;
  };

  var _checkRow = function(row, column) {
    for (var index = 0; index < _slots[_game[row]].length; index++) {
      if (index !== column) {
        if (_slots[_game[row]][index] != null) {
          console.info('Not yet, because of ' + _game[row] + index);
          return false;
        }
      }
    }
    return true;
  };

  var _checkDiagonal1 = function(row, column) {
    if (row !== column) {
      return false;
    }
    for (var index = 0; index < _game.length; index++) {
      if (index !== column) {
        if (_slots[_game[index]][index] != null) {
          console.info('Not yet, because of ' + _game[index] + index);
          return false;
        }
      }
    }
    return true;
  };

  var _checkDiagonal2 = function(row, column) {
    if (row !== (_game.length - column - 1)) {
      return false;
    }
    for (var index = 0; index < _game.length; index++) {
      if (index !== row) {
        if (_slots[_game[index]][_game.length - index - 1] != null) {
          console.info('Not yet, because of ' + _game[index] + (_game.length - index - 1));
          return false;
        }
      }
    }
    return true;
  };

  var _checkWin = function(row, column) {
    return _checkColumn(row, column)
      || _checkRow(row, column)
      || _checkDiagonal1(row, column)
      || _checkDiagonal2(row, column);
  };

  var _connect = function() {
    console.info('connect handler');
  };

  var _disconnect = function() {
    console.info('disconnect handler');
  };

  var _card = function(payload) {
    console.info('card handler');
    console.log('New card has been issued');
    console.dir(payload.slots);
    _slots = payload.slots;
  };

  var _number =function(number) {
    console.info('number handler');
    console.log('New card: ' + number);
    var match = /([BINGO])(\d+)/.exec(number);
    var slot = match[1];
    var number = parseInt(match[2]);

    var slotRow = _slots[slot];
    for (var index = 0; index <= slotRow.length; index++) {
      if (slotRow[index] === number) {
        slotRow[index] = null;
        if (_checkWin(_game.indexOf(slot), index)) {
          console.info('I won, emitting message to server...');
          _client.emit('bingo');
        }
        console.dir(_slots);
      }
    }
  };

  var _win = function(message) {
    console.info('win handler');
    console.log(message);
  };

  var _lose = function(message) {
    console.info('lose handler');
    console.log(message);
  };

  this.start = function() {
    if (_client) {
      throw new Error('Client already started');
    }
    _client = socketClient.connect('ws://yahoobingo.herokuapp.com');
    _client.on('connect', _connect);
    _client.on('disconnect', _disconnect);
    _client.on('card', _card);
    _client.on('number', _number);
    _client.on('win', _win);
    _client.on('lose', _lose);
    _client.emit('register', options);
  };
};

var readOptions = function(callback) {
  fs.readFile(path.join(__dirname, 'package.json'), function(err, data) {
    if (err) {
      callback(err, null);
    } else {
      var packageInfo = JSON.parse(data);
      var options = {
        name: packageInfo.author.name,
        email: packageInfo.author.email,
        url: packageInfo.homepage
      }
      callback(null, options);
    }
  });
};

var startClient = function() {
  readOptions(function(err, options) {
    if (err) {
      console.error(err);
    } else {
      console.info('Got options:');
      console.info(options)
      console.log('Starting client...');
      var client = new BingoClient(options);
      client.start();
    };
  })
};

startClient();


text:
class CreateTouchstoneCampaignSignups < ActiveRecord::Migration

  def change

    column = Touchstone.association_name + "_id"

    create_table :campaign_signups do |t|
      t.integer column.to_sym
      t.integer :campaign_id
      t.timestamps
    end
  end

end


text:
package it.cosenonjaviste.daggermock.modulemethodsvisibility;

public class MyService {
}


text:
Originally published: 2008-05-07 17:33:26
Last updated: 2008-05-07 17:33:26
Author: Bill Bell

I live in a geographical area whose daylight savings time provisions seem to fool software. I would therefore like to avoid mentioning time zone when I create a timestamp in RFC822 format. I have looked for but could not find an elegant way of expressing what I want. In hopes that someone will see this and be aghast at my ignorance, then provide something nice, I humbly offer the following.

It takes a datetime and gives back an RFC822 timestamp (I think).


text:
package com.sleroux.bank.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sleroux.bank.business.BusinessServiceAbstract;
import com.sleroux.bank.domain.ImportReport;
import com.sleroux.bank.presenter.common.ConsoleAppHeader;
import com.sleroux.bank.service.extract.ExtractService;
import com.sleroux.bank.service.extract.ImportReportPresenter;
import com.sleroux.bank.service.importer.ImportService;
import com.sleroux.bank.service.importer.ImportType;

@Component
public class ImportController extends BusinessServiceAbstract {

	@Autowired
	ImportService	importService;

	@Autowired
	ExtractService	extractService;

	@Override
	public void run() throws Exception {

		ConsoleAppHeader.printAppHeader("Import");

		ImportReport reportCMB = importService.importFiles(ImportType.CMB, extractService.getFilesCMB());
		ImportReportPresenter.displayReport(reportCMB);

		ImportReport reportEdenred = importService.importFiles(ImportType.EDENRED, extractService.getFilesEdenred());
		ImportReportPresenter.displayReport(reportEdenred);

		ConsoleAppHeader.printAppHeader("Balances");
		importService.updateBalances(extractService.getBalanceFiles());
	}

}


text:
import React, {Component} from 'react'
import { Button, Icon } from 'semantic-ui-react'

class SingleCar extends Component{
  render(){
    return(

Ford KA

                $ 349.56
                 USD

                Km ilimitado

7 dias de renta

                  Consectetur adipiscing elit, sed do eiusm
  incididunt ut labore et dolore magna.

              5

              5

              SI

              5

              5

      <Button primary className='buttonCotizar'>Reservar</Button>

    )
  }
}

export default SingleCar


text:
package de.craften.plugins.rpgplus.scripting.api.entities;

import de.craften.plugins.rpgplus.components.entitymanager.RpgPlusEntity;
import de.craften.plugins.rpgplus.components.entitymanager.traits.VillagerTrait;
import de.craften.plugins.rpgplus.scripting.api.entities.events.EntityEventManager;
import de.craften.plugins.rpgplus.scripting.util.ScriptUtil;
import org.bukkit.entity.Villager;
import org.luaj.vm2.LuaValue;

class VillagerEntityWrapper extends EntityWrapper<Villager> {
    VillagerEntityWrapper(RpgPlusEntity<Villager> entity, EntityEventManager entityEventManager) {
        super(entity, entityEventManager);
    }

    @Override
    public LuaValue rawget(LuaValue key) {
        if (key.isstring()) {
            switch (key.checkjstring()) {
                case "profession":
                    return LuaValue.valueOf(entity.getEntity().getProfession().toString());
            }
        }
        return super.rawget(key);
    }

    @Override
    public void rawset(LuaValue key, LuaValue value) {
        if (key.isstring()) {
            switch (key.checkjstring()) {
                case "profession":
                    getVillagerTrait().setProfession(ScriptUtil.enumValue(value, Villager.Profession.class));
                    break;
            }
        }
        super.rawset(key, value);
    }

    private VillagerTrait getVillagerTrait() {
        return entity.getNpc().getTrait(VillagerTrait.class);
    }
}


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>basic form validate</title>
</head>
<body>

<form>
    <input required>
    <input type="submit" value="submit">
    <input type="button" value="validate" id="validate">
</form>
<script src="components/jquery/dist/jquery.js"></script>
<script src="components/jquery-validate/dist/jquery.validate.js"></script>
<script>
    $(document).ready(function() {
        $("form").validate();

        $("#validate").on("click", function() {
            alert("valide() => " + $("form").valid());
        });

    });

</script>

</body>
</html>


text:
Want to hack on Kubernetes? Yay!

## Developer Guide

We have a [Developer's Guide](docs/devel/README.md) that outlines everything
you need to know from setting up your dev environment to how to get faster Pull
Request reviews. If you find something undocumented or incorrect along the way,
please feel free to send a Pull Request.

## Filing issues

If you have a question about Kubernetes or have a problem using it, please
start with the [troubleshooting guide](docs/troubleshooting.md).  If that
doesn't answer your questions, or if you think you found a bug, please [file an
issue](https://github.com/kubernetes/kubernetes/issues/new).

## How to become a contributor and submit your own code

### Contributor License Agreements

We'd love to accept your patches! Before we can take them, we have to jump a
couple of legal hurdles.

Please fill out either the individual or corporate Contributor License
Agreement (CLA).  As of Q4 2016, we're transitioning from Google's CLA to the
Cloud Native Computing Foundation (CNCF) CLA.

Google:
  * If you are an individual writing original source code and you're sure you
    own the intellectual property, then you'll need to sign an [individual
    CLA](http://code.google.com/legal/individual-cla-v1.0.html).
  * If you work for a company that wants to allow you to contribute your work,
    then you'll need to sign a [corporate
    CLA](http://code.google.com/legal/corporate-cla-v1.0.html).

CNCF:
  * To contribute as an individual or as am employee of a signed organization,
    [go here](https://identity.linuxfoundation.org/projects/cncf).
  * To sign up as an organization, [go
    here](https://identity.linuxfoundation.org/node/285/organization-signup).

Once you are CLA'ed, we'll be able to accept your pull requests.

***NOTE***: Only original source code from you and other people that have
signed the CLA can be accepted into the repository. This policy does not
apply to [third_party](third_party/) and [vendor](vendor/).

### Finding Things That Need Help

If you're new to the project and want to help, but don't know where to start,
we have a semi-curated list of issues that have should not need deep knowledge
of the system.  [Have a look and see if anything sounds
interesting](https://github.com/kubernetes/kubernetes/issues?q=is%3Aopen+is%3Aissue+label%3Ahelp-wanted).

Alternatively, read some of the many docs on the system, for example [the
architecture](docs/design/architecture.md), and pick a component that seems
interesting.  Start with `main()` (look in the [cmd](cmd/) directory) and read
until you find something you want to fix.  The best way to learn is to hack!
There's always code that can be clarified and variables or functions that can
be renamed or commented.

### Contributing A Patch

If you're working on an existing issue, such as one of the `help-wanted` ones
above, simply respond to the issue and express interest in working on it.  This
helps other people know that the issue is active, and hopefully prevents
duplicated efforts.

If you want to work on a new idea of relatively small scope:

1. Submit an issue describing your proposed change to the repo in question.
1. The repo owners will respond to your issue promptly.
1. If your proposed change is accepted, and you haven't already done so, sign a
   Contributor License Agreement (see details above).
1. Fork the repo, develop, and test your changes.
1. Submit a pull request.

If you want to work on a bigger idea, we STRONGLY recommend that you start with
some bugs or smaller features.  We have a [feature development
process](https://github.com/kubernetes/features/blob/master/README.md), but
navigating the Kubernetes system as a newcomer can be very challenging.

### Protocols for Collaborative Development

Please read [this doc](docs/devel/collab.md) for information on how we're
running development for the project.  Also take a look at the [development
guide](docs/devel/development.md) for information on how to set up your
environment, run tests, manage dependencies, etc.

### Adding dependencies

If your patch depends on new packages, add that package with
[`godep`](https://github.com/tools/godep).  Follow the [instructions to add a
dependency](docs/devel/development.md#godep-and-dependency-management).

### Community Expectations

Please see our [expectations](docs/devel/community-expectations.md) for members
of the Kubernetes community.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/CONTRIBUTING.md?pixel)]()


text:
#pragma once

#include <functional>

#include "mcrouter/lib/fbi/cpp/sfrlock.h"
#include "mcrouter/CallbackPool.h"

namespace facebook { namespace memcache { namespace mcrouter {

/**
 * Wrapper for Data that allows to register callbacks that will be called
 * on each Data change.
 */
template<class Data>
class Observable {
 public:
  /**
   * Callback function for this Observable. It has two arguments:
   * oldData and newData.
   *
   * @param oldData - value before update
   * @param newData - value after update
   */
  typedef typename CallbackPool<const Data&, const Data&>::OnUpdateFunc
  OnUpdateOldNew;

  /**
   * Callback handle for this Observable. Once it is destroyed corresponding
   * callback will be unsubscribed.
   */
  typedef typename CallbackPool<const Data&, const Data&>::CallbackHandle
  CallbackHandle;

  explicit Observable(Data data = Data());

  /**
   * Adds one more callback function. This callback will be called next time
   * the data is updated. The callback is unsubscribed when returned
   * CallbackHandle is destroyed.
   * NOTE: callbacks can run in parallel. It is up to user to synchronize
   * callbacks.
   */
  inline CallbackHandle subscribe(OnUpdateOldNew callback);

  /**
   * Same as subscribe, but immediatelly calls the callback with
   * Data() as oldData and stored data as newData.
   */
  inline CallbackHandle subscribeAndCall(OnUpdateOldNew callback);

  /**
   * Update stored data. Both data change and callback calls are processed under
   * write lock on data. So one can assume data change and callback calls is an
   * atomic operation.
   */
  inline void set(Data data);

  /**
   * Same as set, but constructs Data inside.
   *
   * @param Args arguments for Data constructor
   */
  template<typename... Args>
  inline void emplace(Args&&... args);

  /**
   * @return copy of stored data
   */
  inline Data get();

 private:
  CallbackPool<const Data&, const Data&> pool_;
  Data data_;

  SFRLock dataLock_;
};

}}} // facebook::memcache::mcrouter

#include "Observable-inl.h"


text:
#ifndef __ASM_MEMORY_H
#define __ASM_MEMORY_H

#include <linux/compiler.h>
#include <linux/const.h>
#include <linux/types.h>
#include <asm/bug.h>
#include <asm/sizes.h>

/*
 * Allow for constants defined here to be used from assembly code
 * by prepending the UL suffix only with actual C code compilation.
 */
#define UL(x) _AC(x, UL)

/*
 * Size of the PCI I/O space. This must remain a power of two so that
 * IO_SPACE_LIMIT acts as a mask for the low bits of I/O addresses.
 */
#define PCI_IO_SIZE		SZ_16M

/*
 * Log2 of the upper bound of the size of a struct page. Used for sizing
 * the vmemmap region only, does not affect actual memory footprint.
 * We don't use sizeof(struct page) directly since taking its size here
 * requires its definition to be available at this point in the inclusion
 * chain, and it may not be a power of 2 in the first place.
 */
#define STRUCT_PAGE_MAX_SHIFT	6

/*
 * VMEMMAP_SIZE - allows the whole linear region to be covered by
 *                a struct page array
 */
#define VMEMMAP_SIZE (UL(1) << (VA_BITS - PAGE_SHIFT - 1 + STRUCT_PAGE_MAX_SHIFT))

/*
 * PAGE_OFFSET - the virtual address of the start of the linear map (top
 *		 (VA_BITS - 1))
 * KIMAGE_VADDR - the virtual address of the start of the kernel image
 * VA_BITS - the maximum number of bits for virtual addresses.
 * VA_START - the first kernel virtual address.
 * TASK_SIZE - the maximum size of a user space task.
 * TASK_UNMAPPED_BASE - the lower boundary of the mmap VM area.
 */
#define VA_BITS			(CONFIG_ARM64_VA_BITS)
#define VA_START		(UL(0xffffffffffffffff) << VA_BITS)
#define PAGE_OFFSET		(UL(0xffffffffffffffff) << (VA_BITS - 1))
#define KIMAGE_VADDR		(MODULES_END)
#define MODULES_END		(MODULES_VADDR + MODULES_VSIZE)
#define MODULES_VADDR		(VA_START + KASAN_SHADOW_SIZE)
#define MODULES_VSIZE		(SZ_128M)
#define VMEMMAP_START		(PAGE_OFFSET - VMEMMAP_SIZE)
#define PCI_IO_END		(VMEMMAP_START - SZ_2M)
#define PCI_IO_START		(PCI_IO_END - PCI_IO_SIZE)
#define FIXADDR_TOP		(PCI_IO_START - SZ_2M)
#define TASK_SIZE_64		(UL(1) << VA_BITS)

#ifdef CONFIG_COMPAT
#define TASK_SIZE_32		UL(0x100000000)
#define TASK_SIZE		(test_thread_flag(TIF_32BIT) ? \
				TASK_SIZE_32 : TASK_SIZE_64)
#define TASK_SIZE_OF(tsk)	(test_tsk_thread_flag(tsk, TIF_32BIT) ? \
				TASK_SIZE_32 : TASK_SIZE_64)
#else
#define TASK_SIZE		TASK_SIZE_64
#endif /* CONFIG_COMPAT */

#define TASK_UNMAPPED_BASE	(PAGE_ALIGN(TASK_SIZE / 4))

#define KERNEL_START      _text
#define KERNEL_END        _end

/*
 * The size of the KASAN shadow region. This should be 1/8th of the
 * size of the entire kernel virtual address space.
 */
#ifdef CONFIG_KASAN
#define KASAN_SHADOW_SIZE	(UL(1) << (VA_BITS - 3))
#else
#define KASAN_SHADOW_SIZE	(0)
#endif

/*
 * Physical vs virtual RAM address space conversion.  These are
 * private definitions which should NOT be used outside memory.h
 * files.  Use virt_to_phys/phys_to_virt/__pa/__va instead.
 */
#define __virt_to_phys(x) ({						\
	phys_addr_t __x = (phys_addr_t)(x);				\
	__x & BIT(VA_BITS - 1) ? (__x & ~PAGE_OFFSET) + PHYS_OFFSET :	\
				 (__x - kimage_voffset); })

#define __phys_to_virt(x)	((unsigned long)((x) - PHYS_OFFSET) | PAGE_OFFSET)
#define __phys_to_kimg(x)	((unsigned long)((x) + kimage_voffset))

/*
 * Convert a page to/from a physical address
 */
#define page_to_phys(page)	(__pfn_to_phys(page_to_pfn(page)))
#define phys_to_page(phys)	(pfn_to_page(__phys_to_pfn(phys)))

/*
 * Memory types available.
 */
#define MT_DEVICE_nGnRnE	0
#define MT_DEVICE_nGnRE		1
#define MT_DEVICE_GRE		2
#define MT_NORMAL_NC		3
#define MT_NORMAL		4
#define MT_NORMAL_WT		5

/*
 * Memory types for Stage-2 translation
 */
#define MT_S2_NORMAL		0xf
#define MT_S2_DEVICE_nGnRE	0x1

#ifdef CONFIG_ARM64_4K_PAGES
#define IOREMAP_MAX_ORDER	(PUD_SHIFT)
#else
#define IOREMAP_MAX_ORDER	(PMD_SHIFT)
#endif

#ifdef CONFIG_BLK_DEV_INITRD
#define __early_init_dt_declare_initrd(__start, __end)			\
	do {								\
		initrd_start = (__start);				\
		initrd_end = (__end);					\
	} while (0)
#endif

#ifndef __ASSEMBLY__

#include <linux/bitops.h>
#include <linux/mmdebug.h>

extern s64			memstart_addr;
/* PHYS_OFFSET - the physical address of the start of memory. */
#define PHYS_OFFSET		({ VM_BUG_ON(memstart_addr & 1); memstart_addr; })

/* the virtual base of the kernel image (minus TEXT_OFFSET) */
extern u64			kimage_vaddr;

/* the offset between the kernel virtual and physical mappings */
extern u64			kimage_voffset;

/*
 * Allow all memory at the discovery stage. We will clip it later.
 */
#define MIN_MEMBLOCK_ADDR	0
#define MAX_MEMBLOCK_ADDR	U64_MAX

/*
 * PFNs are used to describe any physical page; this means
 * PFN 0 == physical address 0.
 *
 * This is the PFN of the first RAM page in the kernel
 * direct-mapped view.  We assume this is the first page
 * of RAM in the mem_map as well.
 */
#define PHYS_PFN_OFFSET	(PHYS_OFFSET >> PAGE_SHIFT)

/*
 * Note: Drivers should NOT use these.  They are the wrong
 * translation for translating DMA addresses.  Use the driver
 * DMA support - see dma-mapping.h.
 */
#define virt_to_phys virt_to_phys
static inline phys_addr_t virt_to_phys(const volatile void *x)
{
	return __virt_to_phys((unsigned long)(x));
}

#define phys_to_virt phys_to_virt
static inline void *phys_to_virt(phys_addr_t x)
{
	return (void *)(__phys_to_virt(x));
}

/*
 * Drivers should NOT use these either.
 */
#define __pa(x)			__virt_to_phys((unsigned long)(x))
#define __va(x)			((void *)__phys_to_virt((phys_addr_t)(x)))
#define pfn_to_kaddr(pfn)	__va((pfn) << PAGE_SHIFT)
#define virt_to_pfn(x)      __phys_to_pfn(__virt_to_phys(x))

/*
 *  virt_to_page(k)	convert a _valid_ virtual address to struct page *
 *  virt_addr_valid(k)	indicates whether a virtual address is valid
 */
#define ARCH_PFN_OFFSET		((unsigned long)PHYS_PFN_OFFSET)

#ifndef CONFIG_SPARSEMEM_VMEMMAP
#define virt_to_page(kaddr)	pfn_to_page(__pa(kaddr) >> PAGE_SHIFT)
#define virt_addr_valid(kaddr)	pfn_valid(__pa(kaddr) >> PAGE_SHIFT)
#else
#define __virt_to_pgoff(kaddr)	(((u64)(kaddr) & ~PAGE_OFFSET) / PAGE_SIZE * sizeof(struct page))
#define __page_to_voff(kaddr)	(((u64)(page) & ~VMEMMAP_START) * PAGE_SIZE / sizeof(struct page))

#define page_to_virt(page)	((void *)((__page_to_voff(page)) | PAGE_OFFSET))
#define virt_to_page(vaddr)	((struct page *)((__virt_to_pgoff(vaddr)) | VMEMMAP_START))

#define virt_addr_valid(kaddr)	pfn_valid((((u64)(kaddr) & ~PAGE_OFFSET) \
					   + PHYS_OFFSET) >> PAGE_SHIFT)
#endif
#endif

#include <asm-generic/memory_model.h>

#endif


text:
title: IRC
category: Connectors
connector_type: Chat
logo: https://raw.githubusercontent.com/factor-io/connector-irc/master/logo.png
---

# Authentication
To authenticate to the server you need to specify the server address and user. These are to be obtained from the IRC provider.

**connectors.yml**

```yaml
---
irc:
  server: irc.freenode.net
  user: factorbot
```

# Messages

## Send a message
### irc::messages::send

### Parameters

ID | Default | Description
--- | --- | ---
channel | (required) | The IRC Channel for sending the message (e.g. #factortest)
message | (required) | Message to send to the channel
nick | (same value as user) | The nickname you would like to identify the bot

### Output
Nothing. If it succeeded it will return.


text:
<!-- a sample buildfile -->
<project name="sharkbuilder" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce">
  <property environment="env" />
  <import file="${basedir}/shark.xml" />
</project>


text:
from setuptools import setup, find_packages

import os
import opencanary

setup(
    name='opencanary',
    version=opencanary.__version__,
    url='http://www.thinkst.com/',
    author='Thinkst Applied Research',
    author_email='info@thinkst.com',
    description='OpenCanary daemon',
    long_description='A low interaction honeypot intended to be run on internal networks.',
    install_requires=[
        'Twisted==14.0.2',
        'pyasn1==0.1.7',
        'pycrypto==2.6.1',
        'simplejson==3.6.5',
        'wsgiref==0.1.2',
        'zope.interface==4.1.1',
        'PyPDF2==1.23',
        'fpdf==1.7',
        'passlib==1.6.2',
        'Jinja2>=2.4',
        'ntlmlib==0.67'
    ],
    setup_requires=[
        'setuptools_git'
    ],
    license='BSD',
    packages = find_packages(exclude='test'),
    scripts=['bin/opencanaryd','bin/opencanary.tac'],
    platforms='any',
    include_package_data=True
)


text:
ALTER TABLE build_item DROP PRIMARY KEY DROP INDEX;
ALTER TABLE build_item DROP CONSTRAINT build_item_uk;
DROP INDEX build_item_uk;
ALTER TABLE build_item DROP COLUMN id;
ALTER TABLE build_item DROP COLUMN creation_date;
ALTER TABLE build_item DROP COLUMN comments;
ALTER TABLE build_item ADD CONSTRAINT build_item_pk PRIMARY KEY (host_id, service_instance_id);

ALTER TABLE host_cluster_member DROP COLUMN creation_date;

ALTER TABLE clstr_allow_per DROP COLUMN creation_date;

ALTER TABLE cluster_service_binding DROP COLUMN creation_date;
ALTER TABLE cluster_service_binding DROP COLUMN comments;

ALTER TABLE service_list_item DROP PRIMARY KEY DROP INDEX;
ALTER TABLE service_list_item DROP CONSTRAINT svc_list_svc_uk;
DROP INDEX svc_list_svc_uk;
ALTER TABLE service_list_item DROP COLUMN id;
ALTER TABLE service_list_item DROP COLUMN creation_date;
ALTER TABLE service_list_item DROP COLUMN comments;
ALTER TABLE service_list_item ADD CONSTRAINT service_list_item_pk PRIMARY KEY (service_id, archetype_id);

ALTER TABLE personality_service_list_item DROP COLUMN creation_date;
ALTER TABLE personality_service_list_item DROP COLUMN comments;

QUIT;


text:
using System;
using System.Reactive.Disposables;
using Avalonia.Platform;
using Gdk;

namespace Avalonia.Gtk
{
    using Gtk = global::Gtk;
    public class WindowImpl : WindowImplBase
    {
        private Gtk.Window _window;
        private Gtk.Window Window => _window ?? (_window = (Gtk.Window) Widget);

        public WindowImpl(Gtk.WindowType type) : base(new PlatformHandleAwareWindow(type))
        {
            Init();
        }

        public WindowImpl()
            : base(new PlatformHandleAwareWindow(Gtk.WindowType.Toplevel) {DefaultSize = new Gdk.Size(900, 480)})
        {
            Init();
        }

        void Init()
        {
            Window.FocusActivated += OnFocusActivated;
            Window.ConfigureEvent += OnConfigureEvent;
            _lastClientSize = ClientSize;
            _lastPosition = Position;
        }
        private Size _lastClientSize;
        private Point _lastPosition;
        void OnConfigureEvent(object o, Gtk.ConfigureEventArgs args)
        {
            var evnt = args.Event;
            args.RetVal = true;
            var newSize = new Size(evnt.Width, evnt.Height);

            if (newSize != _lastClientSize)
            {
                Resized(newSize);
                _lastClientSize = newSize;
            }

            var newPosition = new Point(evnt.X, evnt.Y);

            if (newPosition != _lastPosition)
            {
                PositionChanged(newPosition);
                _lastPosition = newPosition;
            }
        }

        public override Size ClientSize
        {
            get
            {
                int width;
                int height;
                Window.GetSize(out width, out height);
                return new Size(width, height);
            }

            set
            {
                Window.Resize((int)value.Width, (int)value.Height);
            }
        }

        public override void SetTitle(string title)
        {
            Window.Title = title;
        }

        void OnFocusActivated(object sender, EventArgs eventArgs)
        {
            Activated();
        }

        public override void BeginMoveDrag()
        {
            int x, y;
            ModifierType mod;
            Window.Screen.RootWindow.GetPointer(out x, out y, out mod);
            Window.BeginMoveDrag(1, x, y, 0);
        }

        public override void BeginResizeDrag(Controls.WindowEdge edge)
        {
            int x, y;
            ModifierType mod;
            Window.Screen.RootWindow.GetPointer(out x, out y, out mod);
            Window.BeginResizeDrag((Gdk.WindowEdge)(int)edge, 1, x, y, 0);
        }

        public override Point Position
        {
            get
            {
                int x, y;
                Window.GetPosition(out x, out y);
                return new Point(x, y);
            }
            set
            {
                Window.Move((int)value.X, (int)value.Y);
            }
        }

        public override IDisposable ShowDialog()
        {
            Window.Modal = true;
            Window.Show();

            return Disposable.Empty;
        }

        public override void SetSystemDecorations(bool enabled) => Window.Decorated = enabled;

        public override void SetIcon(IWindowIconImpl icon)
        {
            Window.Icon = ((IconImpl)icon).Pixbuf;
        }
    }
}


text:
class BasicInteraction
  class Logger
    def log(message)
      puts Time.now.strftime("%F %T ") + message
      $stdout.flush
    end
  end

  class Asker
    def ask(prompt = nil, echo = true)
      print "#{prompt} " if prompt
      $stdout.flush

      system "stty -echo" if not echo
      response = $stdin.gets.sub(/\n$/, "")
      system "stty echo" if not echo
      puts if not echo

      response
    end

    def ask_yesno(*args)
      while true
        case ask(*args)
        when /^ye?s?/i
          return true
        when /^no?/i
          return false
        end
      end
    end
  end
end


text:
fluens.core.FluensScopes = function() {

    var DEFAULT_SCOPE = "default";

    var map = {};

    this.processor = function(scopeType, phaseType, processor) {
        if (!processor) {
            return map[scopeType] && map[scopeType][phaseType] ?
                map[scopeType][phaseType] : (map[DEFAULT_SCOPE][phaseType] ?
                map[DEFAULT_SCOPE][phaseType] : null);
        }

        if (!map[scopeType]) {
            map[scopeType] = {};
        }

        if (map[scopeType][phaseType]) {
            grunt.verbose.writeln("Fluens: Overriding processor for scope '"+
                scopeType+"' and phase '"+ phaseType +"'.");
        }

        map[scopeType][phaseType] = processor;
        return undefined;
    };
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:showDividers="middle"
    android:divider="?dividerHorizontal"
    android:padding="12dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:showDividers="middle"
        android:divider="?dividerVertical"
        android:paddingTop="24dp"
        android:paddingBottom="24dp">

        <TextView
            android:id="@+id/version_info"
            android:drawableTop="@mipmap/app_logo"
            android:drawablePadding="12dp"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/version_info"
            android:gravity="center_horizontal"
            android:layout_gravity="center"
            />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawablePadding="4dp"
            android:drawableTop="@drawable/main_page_url"
            android:layout_gravity="center"
            android:gravity="center_horizontal"
            android:text="@string/let_your_friend_download"/>

    </LinearLayout>

    <Button
        android:id="@+id/check_version"
        android:text="@string/check_version"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start|center_vertical"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:background="?attr/selectableItemBackground"/>

    <Button
        android:id="@+id/forward_to_website"
        android:text="@string/forward_to_website"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start|center_vertical"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:background="?attr/selectableItemBackground"/>

    <Button
        android:id="@+id/share_to_friend"
        android:text="@string/share_to_friend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start|center_vertical"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:background="?attr/selectableItemBackground"/>

    <LinearLayout
        android:id="@+id/new_version_tip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_horizontal">

        <TextView
            android:layout_gravity="center_horizontal"
            android:layout_margin="12dp"
            android:id="@+id/check_version_information"
            android:text="@string/last_check_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/new_version_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/version_info"
            android:layout_gravity="center_horizontal"
            />
        <Button
            android:id="@+id/new_version_download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/download"/>
    </LinearLayout>

</LinearLayout>


text:
require "spec_helper"
require "chef/mixin/unformatter"

class Chef::UnformatterTest
  include Chef::Mixin::Unformatter

  def foo; end

end

describe Chef::Mixin::Unformatter do
  let(:unformatter) { Chef::UnformatterTest.new }
  let(:message) { "Test Message" }

  describe "#write" do
    context "with a timestamp" do
      it "sends foo to itself when the message is of severity foo" do
        expect(unformatter).to receive(:foo).with(message)
        unformatter.write("[time] foo: #{message}")
      end

      it "sends foo to itself when the message is of severity FOO" do
        expect(unformatter).to receive(:foo).with(message)
        unformatter.write("[time] FOO: #{message}")
      end
    end

    context "without a timestamp" do
      it "sends foo to itself when the message is of severity foo" do
        expect(unformatter).to receive(:foo).with(message)
        unformatter.write("foo: #{message}")
      end

      it "sends foo to itself when the message is of severity FOO" do
        expect(unformatter).to receive(:foo).with(message)
        unformatter.write("FOO: #{message}")
      end
    end

  end

end


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

<title>org.ietf.jgss (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="org.ietf.jgss package">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.ietf.jgss

Interfaces

GSSContext

GSSCredential

GSSName

Classes

ChannelBinding

GSSManager

MessageProp

Oid

Exceptions

GSSException


text:
<?php
/**
 * Created by PhpStorm.
 * User: tmtbe
 * Date: 16-7-15
 * Time: 下午1:44
 */

namespace Server\Models;

use Server\CoreBase\Model;

class TestModel extends Model
{
    public function test()
    {
        return 123456;
    }

    public function test_coroutine()
    {
        $mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 10303)->coroutineSend();
        $result = yield $mySqlCoroutine;
        $redisCoroutine = $this->redis_pool->coroutineSend('get', 'test');
        $result = yield $redisCoroutine;
        return $result;
    }

    public function test_coroutineII($callback)
    {
        $this->redis_pool->get('test', function ($uid) use ($callback) {
            $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', $uid);
            $this->mysql_pool->query(function ($result) use ($callback) {
                call_user_func($callback, $result);
            });
        });
    }

    public function test_exception()
    {
        throw new \Exception('test');
    }

    public function test_exceptionII()
    {
        $mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 10303)->coroutineSend();
        $result = yield $mySqlCoroutine;
        throw new \Exception('test');
    }
}


text:
<!DOCTYPE html>

    <meta content='text/html;charset=utf-8' http-equiv='Content-Type'>
    <meta content='width=device-width, initial-scale=1.0' name='viewport'>
    <link href='https://www.w3.org/StyleSheets/TR/base' rel='stylesheet' type='text/css'>

    <title>
      I18N
    </title>

I18N

Copyright © 2010 <acronym title="World Wide Web Consortium">W3C</acronym>® (<acronym title="Massachusetts Institute of Technology">MIT</acronym>, <acronym title="European Research Consortium for Informatics and Mathematics">ERCIM</acronym>, Keio), All Rights Reserved. W3C liability, trademark, and document use rules apply.

Abstract

This page describes W3C SPARQL Working Group's SPARQL1.0 test suite.

Contributing Tests

The test manifests and entries are built automatically from manifest.ttl using a Rake task. Tests may be contributed via pull request to https://github.com/w3c/rdf-tests with suitable changes to the manifest.ttl and referenced files.

Distribution

Distributed under both the W3C Test Suite License and the W3C 3-clause BSD License. To contribute to a W3C Test Suite, see the policies and contribution forms.

Disclaimer

UNDER BOTH MUTUALLY EXCLUSIVE LICENSES, THIS DOCUMENT AND ALL DOCUMENTS, TESTS AND SOFTWARE THAT LINK THIS STATEMENT ARE PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
        COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.

        Test Descriptions

            http://www.w3.org/2001/sw/DataAccess/tests/data-r2/i18n/manifest#kanji-1:

          kanji-01

type

mf:QueryEvaluationTest

approval

dawgt:Approved

approvedBy

              http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0047/31-dawg-minutes

action

query

                  kanji-01.rq

data

                  kanji.ttl

result

              kanji-01-results.ttl

            http://www.w3.org/2001/sw/DataAccess/tests/data-r2/i18n/manifest#kanji-2:

          kanji-02

type

mf:QueryEvaluationTest

approval

dawgt:Approved

approvedBy

              http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0047/31-dawg-minutes

action

query

                  kanji-02.rq

data

                  kanji.ttl

result

              kanji-02-results.ttl

            http://www.w3.org/2001/sw/DataAccess/tests/data-r2/i18n/manifest#normalization-1:

          normalization-01

type

mf:QueryEvaluationTest

approval

dawgt:Approved

approvedBy

              http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0118/04-dawg-minutes.html

action

query

                  normalization-01.rq

data

                  normalization-01.ttl

result

              normalization-01-results.ttl

            http://www.w3.org/2001/sw/DataAccess/tests/data-r2/i18n/manifest#normalization-2:

          normalization-02

Example 1 from http://lists.w3.org/Archives/Public/public-rdf-dawg/2005JulSep/0096

type

mf:QueryEvaluationTest

approval

dawgt:Approved

approvedBy

              http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0047/31-dawg-minutes

action

query

                  normalization-02.rq

data

                  normalization-02.ttl

result

              normalization-02-results.ttl

            http://www.w3.org/2001/sw/DataAccess/tests/data-r2/i18n/manifest#normalization-3:

          normalization-03

Example 2 from http://lists.w3.org/Archives/Public/public-rdf-dawg/2005JulSep/0096

type

mf:QueryEvaluationTest

approval

dawgt:Approved

approvedBy

              http://lists.w3.org/Archives/Public/public-rdf-dawg/2007JulSep/att-0047/31-dawg-minutes

action

query

                  normalization-03.rq

data

                  normalization-03.ttl

result

              normalization-03-results.ttl

Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). W3C® liability, trademark and document use rules apply.