text:
#include <sstream>
#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include <v4r/io/filesystem.h>
#include <v4r/io/eigen.h>
//#include <v4r/ml/svmWrapper.h>
#include <v4r/segmentation/pcl_segmentation_methods.h>
#include <v4r/ml/svmWrapper.h>

#include <pcl/io/pcd_io.h>
#include <pcl/features/esf.h>
#include <pcl/common/centroid.h>
#include <pcl/visualization/cloud_viewer.h>

namespace po = boost::program_options;
typedef pcl::PointXYZ PointT;

int main(int argc, char** argv){

    //    v4r::svmClassifier::Parameter paramSVM;
    po::options_description desc("Calculates one point cloud for classification\n======================================\n**Allowed options");
    std::string path, input;
    v4r::PCLSegmenter<pcl::PointXYZRGB>::Parameter seg_param;
    bool visualize = false;
    desc.add_options()
            ("help,h", "produce help message")
            ("path,p", po::value<std::string>(&path)->required(), "Path to folders with training files")
            ("file,f", po::value<std::string>(&input)->required(),"file to be classified")
            //
            ("chop_z,z", po::value<double>(&seg_param.chop_at_z_ )->default_value(seg_param.chop_at_z_, boost::str(boost::format("%.2e") % seg_param.chop_at_z_)), "")
            ("seg_type,t", po::value<int>(&seg_param.seg_type_ )->default_value(seg_param.seg_type_), "")
            ("min_cluster_size", po::value<int>(&seg_param.min_cluster_size_ )->default_value(seg_param.min_cluster_size_), "")
            ("max_vertical_plane_size", po::value<int>(&seg_param.max_vertical_plane_size_ )->default_value(seg_param.max_vertical_plane_size_), "")
            ("num_plane_inliers,i", po::value<int>(&seg_param.num_plane_inliers_ )->default_value(seg_param.num_plane_inliers_), "")
            ("max_angle_plane_to_ground", po::value<double>(&seg_param.max_angle_plane_to_ground_ )->default_value(seg_param.max_angle_plane_to_ground_), "")
            ("sensor_noise_max", po::value<double>(&seg_param.sensor_noise_max_ )->default_value(seg_param.sensor_noise_max_), "")
            ("table_range_min", po::value<double>(&seg_param.table_range_min_ )->default_value(seg_param.table_range_min_), "")
            ("table_range_max", po::value<double>(&seg_param.table_range_max_ )->default_value(seg_param.table_range_max_), "")
            ("angular_threshold_deg", po::value<double>(&seg_param.angular_threshold_deg_ )->default_value(seg_param.angular_threshold_deg_), "")
            //
            ("visualize,v", po::bool_switch(&visualize), "visualize classified cluster")
            ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help"))
    {
        std::cout << desc << std::endl;
        return false;
    }

    try
    {
        po::notify(vm);
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
        return false;
    }

    std::vector<int> matched_models;
    size_t num_total,num_examples = 0, num_correct = 0;
    std::string path_check = input;
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>());
    v4r::PCLSegmenter<pcl::PointXYZRGB> seg(seg_param);
    std::vector<pcl::PointIndices> found_clusters;
    std::vector<std::string> model_names;
    v4r::svmClassifier::Parameter paramSVM;
    paramSVM.knn_ = 1;
    v4r::svmClassifier classifier(paramSVM);
    std::vector<std::string> objects;
    std::string classinput;
    Eigen::MatrixXf emptym;
    Eigen::VectorXi emptyv;
    int filesToSkip = 0;
    char end = path.back();
    if(end!='/')
        path.append("/");
    objects = v4r::io::getFoldersInDirectory(path);
    objects.erase(find(objects.begin(),objects.end(),"svm"));
    classinput = path;
    classinput.append("svm/Class.model");
    classifier.setInFilename(classinput);
    classifier.train(emptym,emptyv);
    end = path_check.back();
    if(end!='/')
        path_check.append("/");
    Eigen::MatrixXi Checkmatrix;
    Checkmatrix.resize(objects.size(),objects.size());
    Checkmatrix.setZero();
    std::vector<std::string> files = v4r::io::getFilesInDirectory(path_check.append("pcd_binary/"),".*.pcd",false);
    std::cout << filesToSkip << " files skipped!" << std::endl;
    for(size_t k=filesToSkip; k<files.size();k++){
        num_examples++;
        num_total = files.size();
        std::string ft = path_check;
        ft.append(files[k]);
        //ft.append("tt_hmrr89.pcd");
        std::cout<<"File classified: "<<files[k]<<std::endl;

        pcl::io::loadPCDFile(ft, *cloud);
        //        if(found_clusters.size()==0)
        //            continue;
        //        else
        //            num_examples++;

        seg.set_input_cloud(*cloud);
        seg.do_segmentation(found_clusters);

        int min_id=-1;
        double min_centroid = std::numeric_limits<double>::max();

        for(size_t i=0; i < found_clusters.size(); i++)
        {
            typename pcl::PointCloud<PointT>::Ptr clusterXYZ (new pcl::PointCloud<PointT>());
            pcl::copyPointCloud(*cloud, found_clusters[i], *clusterXYZ);
            Eigen::Vector4f centroid;
            pcl::compute3DCentroid (*clusterXYZ, centroid);

            //            double dist = centroid[0]*centroid[0] + centroid[1]*centroid[1] + centroid[2]*centroid[2];

            if (centroid[2] < min_centroid) {
                min_centroid = centroid[2];
                min_id = i;
            }
        }

        if (min_id >= 0) {
            std::vector<pcl::PointIndices> closest_cluster;
            closest_cluster.push_back( found_clusters[min_id] );
            found_clusters = closest_cluster;
        }

        pcl::PointCloud<pcl::PointXYZ>::Ptr clusterXYZ(new pcl::PointCloud<pcl::PointXYZ>);
        pcl::copyPointCloud(*cloud, found_clusters[0], *clusterXYZ);

        pcl::ESFEstimation<pcl::PointXYZ, pcl::ESFSignature640> esf;
        esf.setInputCloud(clusterXYZ);
        pcl::PointCloud<pcl::ESFSignature640>::Ptr query_sig(new pcl::PointCloud<pcl::ESFSignature640>);
        esf.compute(*query_sig);

        Eigen::MatrixXf query = query_sig.get()->getMatrixXfMap();
        Eigen::MatrixXf predicted_label;

        int temp;
        predicted_label.resize(640,3);
        predicted_label(0,0) = 1;
        classifier.predict(query.transpose(), predicted_label);
        //std::cout << predicted_label << std::endl;
        for (size_t c=0; c<predicted_label.cols();c++)
        {
            temp = 0;
            for (size_t n=0; n < predicted_label.rows();n++)
                temp += predicted_label(n,c);
            temp/=predicted_label.rows();
            matched_models.push_back(temp);

        }

        std::vector<std::string> model_names = objects;
        std::vector<std::string> models_name;
        std::string model,matched_model;
        std::vector<int> numbers;
        std::vector<std::string>::iterator it;
        for(size_t t=0; t<matched_models.size(); t++){
            model = model_names[matched_models[t]];
            if(std::find(models_name.begin(),models_name.end(),model)==models_name.end()){
                models_name.push_back(model);
                numbers.push_back(0);
            }
            it = std::find(models_name.begin(),models_name.end(),model);
            numbers[std::distance(models_name.begin(),it)]++;

        }

        int test = std::distance(numbers.begin(),std::max_element(numbers.begin(),numbers.end()));
        matched_model = models_name[std::distance(numbers.begin(),std::max_element(numbers.begin(),numbers.end()))];

        it = std::find(model_names.begin(),model_names.end(),matched_model);
        int matched_index = std::distance(model_names.begin(), it);
        matched_models.clear();
        std::string instream;
        std::string inputfile,item;
        inputfile = input;
        inputfile.append("/annotation/");
        inputfile.append(files[k]);
        inputfile.erase(inputfile.end()-3,inputfile.end());
        inputfile.append("anno");
        std::ifstream myfile (inputfile);

        if (myfile.is_open())
        {
            getline (myfile,instream);
        }

        std::istringstream iss(instream);

        std::vector<std::string> elements{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
        std::string correct_model;
        if(elements.size()>5){
        correct_model = elements[elements.size()-2];
        correct_model.append("_");
        correct_model.append(elements[elements.size()-1]);
        }
        else
            correct_model = elements[elements.size()-1];

        it = std::find(model_names.begin(),model_names.end(),correct_model);
        int correct_index = std::distance(model_names.begin(), it);

        if(!correct_model.compare(matched_model)){
            num_correct++;
            std::cout<< "Objects Should: " << correct_model << ". Classified: " << matched_model <<". CORRECT" <<  std::endl;
        }
        else
            std::cout<< "Objects Should: " << correct_model << ". Classified: " << matched_model <<  std::endl;
        Checkmatrix(correct_index,matched_index)++;

        std::cout<<std::endl;

        //        for (size_t k=0; k<matched_models.size();k++)
        //            std::cout<<model_names[matched_models[k]]<<std::endl;

        /*std::cout<<"Total number of examples classified: "<< num_examples<<std::endl;

        std::cout<<"Total number of correct examples: "<<num_correct<<std::endl;*/
        std::cout<<std::endl;
        if(visualize){
            pcl::visualization::CloudViewer viewer ("Simple Cloud Viewer");
            viewer.showCloud (clusterXYZ);

            while (!viewer.wasStopped ())
            {
            }

        }
    }

    std::cout << "Total number of examples classified: "<< num_examples<<std::endl;

    std::cout << "Total number of correct examples: " << num_correct<<std::endl;
    std::cout << std::endl;
    std::cout << Checkmatrix << std::endl;
    for (int k=0;k<objects.size();k++)
        std::cout << objects[k] << std::endl;

}


text:
go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var EndState = vumigo.states.EndState;
    var Q = require('q');

    var GoApp = App.extend(function(self) {
        App.call(self, 'states_start');
        var $ = self.$;

        self.init = function() {
            self.env = self.im.config.env;
            self.metric_prefix = [self.env, self.im.config.name].join('.');
            self.store_name = [self.env, self.im.config.name].join('.');
        };

        self.states.add('states_start', function() {
            switch (self.im.msg.content.split(" ")[0].replace(/\W/g, '').toUpperCase()) {
                case "RUN":
                    return self.states.create("states_opt_out_run");
                default: // Logs a support ticket
                    return self.states.create("states_default");
            }
        });

        self.states.add('states_opt_out_run', function(name) {
            var msisdns = self.im.config.opt_outs;

            return Q.all(msisdns.map(function(msisdn) { self.im.api_request('optout.optout', {
                        address_type: "msisdn",
                        address_value: msisdn,
                        message_id: self.im.msg.message_id
                    });
                }))
                .then(function() {
                    return self.states.create('states_opt_out_complete');
                });
        });

        self.states.add('states_opt_out_complete', function(name) {
            return new EndState(name, {
                text: $('Thank you. Opt outs run.'),

                next: 'states_start'
            });
        });

        self.states.add('states_default', function(name) {
            return new EndState(name, {
                text: "Command not recognised",

                next: 'states_start'
            });
        });

    });

    return {
        GoApp: GoApp
    };
}();

redpajama_set_name: RedPajamaGithub


text:
package org.mifmi.commons4j.util;

/**
 * Helper methods for working with Enum instances.
 *
 * @author mozq
 */
public final class EnumUtilz {

	private EnumUtilz() {
		// NOP
	}

	public static <E extends Enum<E>> E valueOf(Class<E> enumType, String name) {
		return valueOf(enumType, name, null);
	}

	public static <E extends Enum<E>> E valueOf(Class<E> enumType, String name, E defaultValue) {
		if (name == null || name.isEmpty()) {
			return defaultValue;
		}

		E enumValue;
		try {
			enumValue = Enum.valueOf(enumType, name);
		} catch (IllegalArgumentException e) {
			return defaultValue;
		}

		return enumValue;
	}

	public static <E extends Enum<E>> boolean hasValue(Class<E> enumType, String name) {
		return valueOf(enumType, name, null) != null;
	}
}


text:
class AddDataUsageAndTesterToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :data_usage, :text
    add_column :users, :tester, :boolean
  end
end


text:
const bcrypt = require('bcrypt');
const _ = require('lodash');

const sanitizeOptions = (logger, opts) => {
  const options = _.isUndefined(opts) ? {} : opts;

  if (!_.isPlainObject(options)) {
    // eslint-disable-next-line max-len
    logger.fatal({'options passed': options}, 'The options passed in were not a plain object (e.g. created via {}');
    return null;
  }

  return _.cloneDeep(options);
};

module.exports = function (logger, passedOptions) {
  const minSaltRounds = 10;
  const log = logger;
  const options = sanitizeOptions(logger, passedOptions);

  if (_.isNull(options)) {
    throw new Error(`Invalid options passed to module: ${passedOptions}`);
  }

  if (!options.saltRounds || !Number.isInteger(options.saltRounds)) {
    // eslint-disable-next-line max-len
    log.info({ 'passed options': options }, `Salt rounds not specified in options, or not an integer, setting to ${minSaltRounds}`);
    options.saltRounds = 10;
  }

  if (options.saltRounds < minSaltRounds) {
    // eslint-disable-next-line max-len
    log.warn(options, `Insufficient number of salt rounds passed in options, setting to ${minSaltRounds}`);
    options.saltRounds = minSaltRounds;
  }

  return {
    hash: (sourceValue, cb) => {
      bcrypt.hash(sourceValue, options.saltRounds, cb);
    },
    compare: bcrypt.compare,
    saltRounds: options.saltRounds,
  };
};


text:
package com.infinities.keystone4j.admin.v3;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.infinities.keystone4j.cert.controller.SimpleCertV3Controller;

//keystone.contrib.simple_cert.routers 20141129
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SimpleCertResource {

	private final SimpleCertV3Controller simpleCertV3Controller;

	@Inject
	public SimpleCertResource(SimpleCertV3Controller simpleCertV3Controller) {
		this.simpleCertV3Controller = simpleCertV3Controller;
	}

	@GET
	@Path("/ca")
	public Response getCaCertficate() {
		return simpleCertV3Controller.getCaCertificate();
	}

	@GET
	@Path("/certificates")
	public Response listCertificates() {
		return simpleCertV3Controller.listCertificate();
	}

}


text:
/*
 * register-class.js
 */

const { describe, it, mustThrow, expect } = require('./__common__')

const gi = require('..')
const GObject = gi.require('GObject')
const Gtk = gi.require('Gtk', '3.0'); Gtk.init([])

describe('registerClass', () => {

  it('works', (done) => {

    class CustomWidget extends Gtk.Widget {
      static GTypeName = 'NodeGTKCustomWidget'
      focus() {}
    }
    class DerivedWidget extends CustomWidget {
      focus() {}
    }

    gi.registerClass(CustomWidget)
    gi.registerClass(DerivedWidget)

    const custom = new CustomWidget()
    const derived = new DerivedWidget()
    console.log(custom)
    console.log(derived)
    expect(custom instanceof Gtk.Widget, true)
    expect(derived instanceof Gtk.Widget, true)
    expect(GObject.typeName(custom.__gtype__), CustomWidget.GTypeName)
    expect(GObject.typeName(derived.__gtype__), DerivedWidget.name)
  })

  it('fails with invalid GTypeName',
    mustThrow('GTypeName value is invalid: Invalid Gtype Name #$%^&', () => {
      class CustomClass extends Gtk.Widget {
        static GTypeName = 'Invalid Gtype Name #$%^&'
      }
      gi.registerClass(CustomClass)
    }))

  it('fails with already registered GTypeName',
    mustThrow('GType name already registerd: GtkWidget', () => {
      class CustomClass extends Gtk.Widget {
        static GTypeName = 'GtkWidget'
      }
      gi.registerClass(CustomClass)
    }))

  it('fails with non-GObject classes',
    mustThrow('Invalid base class (InvalidClass)', () => {
      class InvalidClass {}
      class InvalidSubclass extends InvalidClass {}
      gi.registerClass(InvalidSubclass)
    }))
})


text:
package org.apache.flink.streaming.api.operators.co;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.util.KeyedTwoInputStreamOperatorTestHarness;
import org.apache.flink.streaming.util.TestHarnessUtil;
import org.apache.flink.util.Collector;
import org.apache.flink.util.FlinkException;

import org.apache.flink.shaded.guava30.com.google.common.collect.Iterables;
import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

/** Tests for {@link IntervalJoinOperator}. Those tests cover correctness and cleaning of state */
@RunWith(Parameterized.class)
public class IntervalJoinOperatorTest {

    private final boolean lhsFasterThanRhs;

    @Parameters(name = "lhs faster than rhs: {0}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {{true}, {false}});
    }

    public IntervalJoinOperatorTest(boolean lhsFasterThanRhs) {
        this.lhsFasterThanRhs = lhsFasterThanRhs;
    }

    @Test
    public void testImplementationMirrorsCorrectly() throws Exception {

        long lowerBound = 1;
        long upperBound = 3;

        boolean lowerBoundInclusive = true;
        boolean upperBoundInclusive = false;

        setupHarness(lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(1, 2),
                        streamRecordOf(1, 3),
                        streamRecordOf(2, 3),
                        streamRecordOf(2, 4),
                        streamRecordOf(3, 4))
                .noLateRecords()
                .close();

        setupHarness(-1 * upperBound, upperBoundInclusive, -1 * lowerBound, lowerBoundInclusive)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(2, 1),
                        streamRecordOf(3, 1),
                        streamRecordOf(3, 2),
                        streamRecordOf(4, 2),
                        streamRecordOf(4, 3))
                .noLateRecords()
                .close();
    }

    @Test // lhs - 2 <= rhs <= rhs + 2
    public void testNegativeInclusiveAndNegativeInclusive() throws Exception {

        setupHarness(-2, true, -1, true)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(2, 1),
                        streamRecordOf(3, 1),
                        streamRecordOf(3, 2),
                        streamRecordOf(4, 2),
                        streamRecordOf(4, 3))
                .noLateRecords()
                .close();
    }

    @Test // lhs - 1 <= rhs <= rhs + 1
    public void testNegativeInclusiveAndPositiveInclusive() throws Exception {

        setupHarness(-1, true, 1, true)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(1, 1),
                        streamRecordOf(1, 2),
                        streamRecordOf(2, 1),
                        streamRecordOf(2, 2),
                        streamRecordOf(2, 3),
                        streamRecordOf(3, 2),
                        streamRecordOf(3, 3),
                        streamRecordOf(3, 4),
                        streamRecordOf(4, 3),
                        streamRecordOf(4, 4))
                .noLateRecords()
                .close();
    }

    @Test // lhs + 1 <= rhs <= lhs + 2
    public void testPositiveInclusiveAndPositiveInclusive() throws Exception {

        setupHarness(1, true, 2, true)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(1, 2),
                        streamRecordOf(1, 3),
                        streamRecordOf(2, 3),
                        streamRecordOf(2, 4),
                        streamRecordOf(3, 4))
                .noLateRecords()
                .close();
    }

    @Test
    public void testNegativeExclusiveAndNegativeExlusive() throws Exception {

        setupHarness(-3, false, -1, false)
                .processElementsAndWatermarks(1, 4)
                .andExpect(streamRecordOf(3, 1), streamRecordOf(4, 2))
                .noLateRecords()
                .close();
    }

    @Test
    public void testNegativeExclusiveAndPositiveExlusive() throws Exception {

        setupHarness(-1, false, 1, false)
                .processElementsAndWatermarks(1, 4)
                .andExpect(
                        streamRecordOf(1, 1),
                        streamRecordOf(2, 2),
                        streamRecordOf(3, 3),
                        streamRecordOf(4, 4))
                .noLateRecords()
                .close();
    }

    @Test
    public void testPositiveExclusiveAndPositiveExlusive() throws Exception {

        setupHarness(1, false, 3, false)
                .processElementsAndWatermarks(1, 4)
                .andExpect(streamRecordOf(1, 3), streamRecordOf(2, 4))
                .noLateRecords()
                .close();
    }

    @Test
    public void testStateCleanupNegativeInclusiveNegativeInclusive() throws Exception {

        setupHarness(-1, true, 0, true)
                .processElement1(1)
                .processElement1(2)
                .processElement1(3)
                .processElement1(4)
                .processElement1(5)
                .processElement2(1)
                .processElement2(2)
                .processElement2(3)
                .processElement2(4)
                .processElement2(5) // fill both buffers with values
                .processWatermark1(1)
                .processWatermark2(1) // set common watermark to 1 and check that data is cleaned
                .assertLeftBufferContainsOnly(2, 3, 4, 5)
                .assertRightBufferContainsOnly(1, 2, 3, 4, 5)
                .processWatermark1(4) // set common watermark to 4 and check that data is cleaned
                .processWatermark2(4)
                .assertLeftBufferContainsOnly(5)
                .assertRightBufferContainsOnly(4, 5)
                .processWatermark1(
                        6) // set common watermark to 6 and check that data all buffers are empty
                .processWatermark2(6)
                .assertLeftBufferEmpty()
                .assertRightBufferEmpty()
                .close();
    }

    @Test
    public void testStateCleanupNegativePositiveNegativeExlusive() throws Exception {
        setupHarness(-2, false, 1, false)
                .processElement1(1)
                .processElement1(2)
                .processElement1(3)
                .processElement1(4)
                .processElement1(5)
                .processElement2(1)
                .processElement2(2)
                .processElement2(3)
                .processElement2(4)
                .processElement2(5) // fill both buffers with values
                .processWatermark1(1)
                .processWatermark2(1) // set common watermark to 1 and check that data is cleaned
                .assertLeftBufferContainsOnly(2, 3, 4, 5)
                .assertRightBufferContainsOnly(1, 2, 3, 4, 5)
                .processWatermark1(4) // set common watermark to 4 and check that data is cleaned
                .processWatermark2(4)
                .assertLeftBufferContainsOnly(5)
                .assertRightBufferContainsOnly(4, 5)
                .processWatermark1(
                        6) // set common watermark to 6 and check that data all buffers are empty
                .processWatermark2(6)
                .assertLeftBufferEmpty()
                .assertRightBufferEmpty()
                .close();
    }

    @Test
    public void testStateCleanupPositiveInclusivePositiveInclusive() throws Exception {
        setupHarness(0, true, 1, true)
                .processElement1(1)
                .processElement1(2)
                .processElement1(3)
                .processElement1(4)
                .processElement1(5)
                .processElement2(1)
                .processElement2(2)
                .processElement2(3)
                .processElement2(4)
                .processElement2(5) // fill both buffers with values
                .processWatermark1(1)
                .processWatermark2(1) // set common watermark to 1 and check that data is cleaned
                .assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
                .assertRightBufferContainsOnly(2, 3, 4, 5)
                .processWatermark1(4) // set common watermark to 4 and check that data is cleaned
                .processWatermark2(4)
                .assertLeftBufferContainsOnly(4, 5)
                .assertRightBufferContainsOnly(5)
                .processWatermark1(
                        6) // set common watermark to 6 and check that data all buffers are empty
                .processWatermark2(6)
                .assertLeftBufferEmpty()
                .assertRightBufferEmpty()
                .close();
    }

    @Test
    public void testStateCleanupPositiveExlusivePositiveExclusive() throws Exception {
        setupHarness(-1, false, 2, false)
                .processElement1(1)
                .processElement1(2)
                .processElement1(3)
                .processElement1(4)
                .processElement1(5)
                .processElement2(1)
                .processElement2(2)
                .processElement2(3)
                .processElement2(4)
                .processElement2(5) // fill both buffers with values
                .processWatermark1(1)
                .processWatermark2(1) // set common watermark to 1 and check that data is cleaned
                .assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
                .assertRightBufferContainsOnly(2, 3, 4, 5)
                .processWatermark1(4) // set common watermark to 4 and check that data is cleaned
                .processWatermark2(4)
                .assertLeftBufferContainsOnly(4, 5)
                .assertRightBufferContainsOnly(5)
                .processWatermark1(
                        6) // set common watermark to 6 and check that data all buffers are empty
                .processWatermark2(6)
                .assertLeftBufferEmpty()
                .assertRightBufferEmpty()
                .close();
    }

    @Test
    public void testRestoreFromSnapshot() throws Exception {

        // config
        int lowerBound = -1;
        boolean lowerBoundInclusive = true;
        int upperBound = 1;
        boolean upperBoundInclusive = true;

        // create first test harness
        OperatorSubtaskState handles;
        List<StreamRecord<Tuple2<TestElem, TestElem>>> expectedOutput;

        try (TestHarness testHarness =
                createTestHarness(
                        lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {

            testHarness.setup();
            testHarness.open();

            // process elements with first test harness
            testHarness.processElement1(createStreamRecord(1, "lhs"));
            testHarness.processWatermark1(new Watermark(1));

            testHarness.processElement2(createStreamRecord(1, "rhs"));
            testHarness.processWatermark2(new Watermark(1));

            testHarness.processElement1(createStreamRecord(2, "lhs"));
            testHarness.processWatermark1(new Watermark(2));

            testHarness.processElement2(createStreamRecord(2, "rhs"));
            testHarness.processWatermark2(new Watermark(2));

            testHarness.processElement1(createStreamRecord(3, "lhs"));
            testHarness.processWatermark1(new Watermark(3));

            testHarness.processElement2(createStreamRecord(3, "rhs"));
            testHarness.processWatermark2(new Watermark(3));

            // snapshot and validate output
            handles = testHarness.snapshot(0, 0);
            testHarness.close();

            expectedOutput =
                    Lists.newArrayList(
                            streamRecordOf(1, 1),
                            streamRecordOf(1, 2),
                            streamRecordOf(2, 1),
                            streamRecordOf(2, 2),
                            streamRecordOf(2, 3),
                            streamRecordOf(3, 2),
                            streamRecordOf(3, 3));

            TestHarnessUtil.assertNoLateRecords(testHarness.getOutput());
            assertOutput(expectedOutput, testHarness.getOutput());
        }

        try (TestHarness newTestHarness =
                createTestHarness(
                        lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {
            // create new test harness from snapshpt

            newTestHarness.setup();
            newTestHarness.initializeState(handles);
            newTestHarness.open();

            // process elements
            newTestHarness.processElement1(createStreamRecord(4, "lhs"));
            newTestHarness.processWatermark1(new Watermark(4));

            newTestHarness.processElement2(createStreamRecord(4, "rhs"));
            newTestHarness.processWatermark2(new Watermark(4));

            // assert expected output
            expectedOutput =
                    Lists.newArrayList(
                            streamRecordOf(3, 4), streamRecordOf(4, 3), streamRecordOf(4, 4));

            TestHarnessUtil.assertNoLateRecords(newTestHarness.getOutput());
            assertOutput(expectedOutput, newTestHarness.getOutput());
        }
    }

    @Test
    public void testContextCorrectLeftTimestamp() throws Exception {

        IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
                new IntervalJoinOperator<>(
                        -1,
                        1,
                        true,
                        true,
                        TestElem.serializer(),
                        TestElem.serializer(),
                        new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
                            @Override
                            public void processElement(
                                    TestElem left,
                                    TestElem right,
                                    Context ctx,
                                    Collector<Tuple2<TestElem, TestElem>> out)
                                    throws Exception {
                                Assert.assertEquals(left.ts, ctx.getLeftTimestamp());
                            }
                        });

        try (TestHarness testHarness =
                new TestHarness(
                        op,
                        (elem) -> elem.key,
                        (elem) -> elem.key,
                        TypeInformation.of(String.class))) {

            testHarness.setup();
            testHarness.open();

            processElementsAndWatermarks(testHarness);
        }
    }

    @Test
    public void testReturnsCorrectTimestamp() throws Exception {
        IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
                new IntervalJoinOperator<>(
                        -1,
                        1,
                        true,
                        true,
                        TestElem.serializer(),
                        TestElem.serializer(),
                        new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {

                            private static final long serialVersionUID = 1L;

                            @Override
                            public void processElement(
                                    TestElem left,
                                    TestElem right,
                                    Context ctx,
                                    Collector<Tuple2<TestElem, TestElem>> out)
                                    throws Exception {
                                Assert.assertEquals(
                                        Math.max(left.ts, right.ts), ctx.getTimestamp());
                            }
                        });

        try (TestHarness testHarness =
                new TestHarness(
                        op,
                        (elem) -> elem.key,
                        (elem) -> elem.key,
                        TypeInformation.of(String.class))) {

            testHarness.setup();
            testHarness.open();

            processElementsAndWatermarks(testHarness);
        }
    }

    @Test
    public void testContextCorrectRightTimestamp() throws Exception {

        IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
                new IntervalJoinOperator<>(
                        -1,
                        1,
                        true,
                        true,
                        TestElem.serializer(),
                        TestElem.serializer(),
                        new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
                            @Override
                            public void processElement(
                                    TestElem left,
                                    TestElem right,
                                    Context ctx,
                                    Collector<Tuple2<TestElem, TestElem>> out)
                                    throws Exception {
                                Assert.assertEquals(right.ts, ctx.getRightTimestamp());
                            }
                        });

        try (TestHarness testHarness =
                new TestHarness(
                        op,
                        (elem) -> elem.key,
                        (elem) -> elem.key,
                        TypeInformation.of(String.class))) {

            testHarness.setup();
            testHarness.open();

            processElementsAndWatermarks(testHarness);
        }
    }

    @Test(expected = FlinkException.class)
    public void testFailsWithNoTimestampsLeft() throws Exception {
        TestHarness newTestHarness = createTestHarness(0L, true, 0L, true);

        newTestHarness.setup();
        newTestHarness.open();

        // note that the StreamRecord has no timestamp in constructor
        newTestHarness.processElement1(new StreamRecord<>(new TestElem(0, "lhs")));
    }

    @Test(expected = FlinkException.class)
    public void testFailsWithNoTimestampsRight() throws Exception {
        try (TestHarness newTestHarness = createTestHarness(0L, true, 0L, true)) {

            newTestHarness.setup();
            newTestHarness.open();

            // note that the StreamRecord has no timestamp in constructor
            newTestHarness.processElement2(new StreamRecord<>(new TestElem(0, "rhs")));
        }
    }

    @Test
    public void testDiscardsLateData() throws Exception {
        setupHarness(-1, true, 1, true)
                .processElement1(1)
                .processElement2(1)
                .processElement1(2)
                .processElement2(2)
                .processElement1(3)
                .processElement2(3)
                .processWatermark1(3)
                .processWatermark2(3)
                .processElement1(1) // this element is late and should not be joined again
                .processElement1(4)
                .processElement2(4)
                .processElement1(5)
                .processElement2(5)
                .andExpect(
                        streamRecordOf(1, 1),
                        streamRecordOf(1, 2),
                        streamRecordOf(2, 1),
                        streamRecordOf(2, 2),
                        streamRecordOf(2, 3),
                        streamRecordOf(3, 2),
                        streamRecordOf(3, 3),
                        streamRecordOf(3, 4),
                        streamRecordOf(4, 3),
                        streamRecordOf(4, 4),
                        streamRecordOf(4, 5),
                        streamRecordOf(5, 4),
                        streamRecordOf(5, 5))
                .noLateRecords()
                .close();
    }

    private void assertEmpty(MapState<Long, ?> state) throws Exception {
        boolean stateIsEmpty = Iterables.size(state.keys()) == 0;
        Assert.assertTrue("state not empty", stateIsEmpty);
    }

    private void assertContainsOnly(MapState<Long, ?> state, long... ts) throws Exception {
        for (long t : ts) {
            String message =
                    "Keys not found in state. \n Expected: "
                            + Arrays.toString(ts)
                            + "\n Actual:   "
                            + state.keys();
            Assert.assertTrue(message, state.contains(t));
        }

        String message =
                "Too many objects in state. \n Expected: "
                        + Arrays.toString(ts)
                        + "\n Actual:   "
                        + state.keys();
        Assert.assertEquals(message, ts.length, Iterables.size(state.keys()));
    }

    private void assertOutput(
            Iterable<StreamRecord<Tuple2<TestElem, TestElem>>> expectedOutput,
            Queue<Object> actualOutput) {

        int actualSize =
                actualOutput.stream()
                        .filter(elem -> elem instanceof StreamRecord)
                        .collect(Collectors.toList())
                        .size();

        int expectedSize = Iterables.size(expectedOutput);

        Assert.assertEquals(
                "Expected and actual size of stream records different", expectedSize, actualSize);

        for (StreamRecord<Tuple2<TestElem, TestElem>> record : expectedOutput) {
            Assert.assertTrue(actualOutput.contains(record));
        }
    }

    private TestHarness createTestHarness(
            long lowerBound,
            boolean lowerBoundInclusive,
            long upperBound,
            boolean upperBoundInclusive)
            throws Exception {

        IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
                new IntervalJoinOperator<>(
                        lowerBound,
                        upperBound,
                        lowerBoundInclusive,
                        upperBoundInclusive,
                        TestElem.serializer(),
                        TestElem.serializer(),
                        new PassthroughFunction());

        return new TestHarness(
                operator,
                (elem) -> elem.key, // key
                (elem) -> elem.key, // key
                TypeInformation.of(String.class));
    }

    private JoinTestBuilder setupHarness(
            long lowerBound,
            boolean lowerBoundInclusive,
            long upperBound,
            boolean upperBoundInclusive)
            throws Exception {

        IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
                new IntervalJoinOperator<>(
                        lowerBound,
                        upperBound,
                        lowerBoundInclusive,
                        upperBoundInclusive,
                        TestElem.serializer(),
                        TestElem.serializer(),
                        new PassthroughFunction());

        TestHarness t =
                new TestHarness(
                        operator,
                        (elem) -> elem.key, // key
                        (elem) -> elem.key, // key
                        TypeInformation.of(String.class));

        return new JoinTestBuilder(t, operator);
    }

    private class JoinTestBuilder {

        private IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
                operator;
        private TestHarness testHarness;

        public JoinTestBuilder(
                TestHarness t,
                IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
                        operator)
                throws Exception {

            this.testHarness = t;
            this.operator = operator;
            t.open();
            t.setup();
        }

        public TestHarness get() {
            return testHarness;
        }

        public JoinTestBuilder processElement1(int ts) throws Exception {
            testHarness.processElement1(createStreamRecord(ts, "lhs"));
            return this;
        }

        public JoinTestBuilder processElement2(int ts) throws Exception {
            testHarness.processElement2(createStreamRecord(ts, "rhs"));
            return this;
        }

        public JoinTestBuilder processWatermark1(int ts) throws Exception {
            testHarness.processWatermark1(new Watermark(ts));
            return this;
        }

        public JoinTestBuilder processWatermark2(int ts) throws Exception {
            testHarness.processWatermark2(new Watermark(ts));
            return this;
        }

        public JoinTestBuilder processElementsAndWatermarks(int from, int to) throws Exception {
            if (lhsFasterThanRhs) {
                // add to lhs
                for (int i = from; i <= to; i++) {
                    testHarness.processElement1(createStreamRecord(i, "lhs"));
                    testHarness.processWatermark1(new Watermark(i));
                }

                // add to rhs
                for (int i = from; i <= to; i++) {
                    testHarness.processElement2(createStreamRecord(i, "rhs"));
                    testHarness.processWatermark2(new Watermark(i));
                }
            } else {
                // add to rhs
                for (int i = from; i <= to; i++) {
                    testHarness.processElement2(createStreamRecord(i, "rhs"));
                    testHarness.processWatermark2(new Watermark(i));
                }

                // add to lhs
                for (int i = from; i <= to; i++) {
                    testHarness.processElement1(createStreamRecord(i, "lhs"));
                    testHarness.processWatermark1(new Watermark(i));
                }
            }

            return this;
        }

        @SafeVarargs
        public final JoinTestBuilder andExpect(StreamRecord<Tuple2<TestElem, TestElem>>... elems) {
            assertOutput(Lists.newArrayList(elems), testHarness.getOutput());
            return this;
        }

        public JoinTestBuilder assertLeftBufferContainsOnly(long... timestamps) {

            try {
                assertContainsOnly(operator.getLeftBuffer(), timestamps);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return this;
        }

        public JoinTestBuilder assertRightBufferContainsOnly(long... timestamps) {

            try {
                assertContainsOnly(operator.getRightBuffer(), timestamps);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return this;
        }

        public JoinTestBuilder assertLeftBufferEmpty() {
            try {
                assertEmpty(operator.getLeftBuffer());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return this;
        }

        public JoinTestBuilder assertRightBufferEmpty() {
            try {
                assertEmpty(operator.getRightBuffer());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return this;
        }

        public JoinTestBuilder noLateRecords() {
            TestHarnessUtil.assertNoLateRecords(this.testHarness.getOutput());
            return this;
        }

        public void close() throws Exception {
            testHarness.close();
        }
    }

    private static class PassthroughFunction
            extends ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>> {

        @Override
        public void processElement(
                TestElem left,
                TestElem right,
                Context ctx,
                Collector<Tuple2<TestElem, TestElem>> out)
                throws Exception {
            out.collect(Tuple2.of(left, right));
        }
    }

    private StreamRecord<Tuple2<TestElem, TestElem>> streamRecordOf(long lhsTs, long rhsTs) {
        TestElem lhs = new TestElem(lhsTs, "lhs");
        TestElem rhs = new TestElem(rhsTs, "rhs");

        long ts = Math.max(lhsTs, rhsTs);
        return new StreamRecord<>(Tuple2.of(lhs, rhs), ts);
    }

    private static class TestElem {
        String key;
        long ts;
        String source;

        public TestElem(long ts, String source) {
            this.key = "key";
            this.ts = ts;
            this.source = source;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }

            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            TestElem testElem = (TestElem) o;

            if (ts != testElem.ts) {
                return false;
            }

            if (key != null ? !key.equals(testElem.key) : testElem.key != null) {
                return false;
            }

            return source != null ? source.equals(testElem.source) : testElem.source == null;
        }

        @Override
        public int hashCode() {
            int result = key != null ? key.hashCode() : 0;
            result = 31 * result + (int) (ts ^ (ts >>> 32));
            result = 31 * result + (source != null ? source.hashCode() : 0);
            return result;
        }

        @Override
        public String toString() {
            return this.source + ":" + this.ts;
        }

        public static TypeSerializer<TestElem> serializer() {
            return TypeInformation.of(new TypeHint<TestElem>() {})
                    .createSerializer(new ExecutionConfig());
        }
    }

    private static StreamRecord<TestElem> createStreamRecord(long ts, String source) {
        TestElem testElem = new TestElem(ts, source);
        return new StreamRecord<>(testElem, ts);
    }

    private void processElementsAndWatermarks(TestHarness testHarness) throws Exception {
        if (lhsFasterThanRhs) {
            // add to lhs
            for (int i = 1; i <= 4; i++) {
                testHarness.processElement1(createStreamRecord(i, "lhs"));
                testHarness.processWatermark1(new Watermark(i));
            }

            // add to rhs
            for (int i = 1; i <= 4; i++) {
                testHarness.processElement2(createStreamRecord(i, "rhs"));
                testHarness.processWatermark2(new Watermark(i));
            }
        } else {
            // add to rhs
            for (int i = 1; i <= 4; i++) {
                testHarness.processElement2(createStreamRecord(i, "rhs"));
                testHarness.processWatermark2(new Watermark(i));
            }

            // add to lhs
            for (int i = 1; i <= 4; i++) {
                testHarness.processElement1(createStreamRecord(i, "lhs"));
                testHarness.processWatermark1(new Watermark(i));
            }
        }
    }

    /** Custom test harness to avoid endless generics in all of the test code. */
    private static class TestHarness
            extends KeyedTwoInputStreamOperatorTestHarness<
                    String, TestElem, TestElem, Tuple2<TestElem, TestElem>> {

        TestHarness(
                TwoInputStreamOperator<TestElem, TestElem, Tuple2<TestElem, TestElem>> operator,
                KeySelector<TestElem, String> keySelector1,
                KeySelector<TestElem, String> keySelector2,
                TypeInformation<String> keyType)
                throws Exception {
            super(operator, keySelector1, keySelector2, keyType);
        }
    }
}


text:
const dgram = require('dgram');

function freeUdpPort(cb) {
  const socket = dgram.createSocket('udp4');
  socket.bind((err)=> {
    if (err) {
      return cb(err);
    }

    let address = socket.address();
    socket.close();
    setImmediate(cb, null, address.port);
  })
}

freeUdpPort((err, port) => {
  console.log(err, port);
});


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.9.5.12_A1_T2;
 * @section: 15.9.5.12;
 * @assertion: The Date.prototype property "getMonth" has { DontEnum } attributes;
 * @description: Checking absence of DontDelete attribute;
 */

if (delete Date.prototype.getMonth  === false) {
  $ERROR('#1: The Date.prototype.getMonth property has not the attributes DontDelete');
}

if (Date.prototype.hasOwnProperty('getMonth')) {
  $FAIL('#2: The Date.prototype.getMonth property has not the attributes DontDelete');
}


text:
class AddCustomFieldsMultiple < ActiveRecord::Migration
  def self.up
    add_column :custom_fields, :multiple, :boolean, :default => false
  end

  def self.down
    remove_column :custom_fields, :multiple
  end
end


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>9. Internationalization — RESThub JS 1.1.3 documentation</title>

    <link rel="stylesheet" href="static/resthub.css" type="text/css" />
    <link rel="stylesheet" href="static/pygments.css" type="text/css" />

    <link rel="top" title="RESThub JS 1.1.3 documentation" href="index.html" />
    <link rel="next" title="10. OAuth2 support" href="oauth2.html" />
    <link rel="prev" title="8. Repositories" href="repositories.html" />

Navigation

          index

          next |

          previous |

RESThub JS 1.1.3 documentation »

9. Internationalization¶

You should never use directly labels or texts in your source files. All labels should be externalized to prepare your app’s
Internationalization.
Doing such thing is pretty simple with RESThub-js because of requireJS.

9.1. i18n primer¶

All is explained in details here.  but the main concepts are :

1. Have a label file (for example labels.js):

define({
    // root is mandatory.
    'root': {
            'titles': {
                    'login': 'Connexion'
            }
        }
    });

2. Put it in a folder (nls is a standardized name for labels folders), or in a locale named subfolder (nls/en-US, nls/fr)...

You should always keep the same file name, and the file located at the root will be used by default.

3. Add a dependency in the js file where you’ll need labels.
You’ll absolutely need to give a scoped variable to the result (in this example <tt class="docutils literal">i18n</tt>, but you can choose the one you want).

Prepending ‘i18n!’ before the file path in the dependency indicates RequireJS to get the file related to the current locale.:

define(['i18n!nls/labels'], function(i18n) {

4. Use your labels:

$('#main').html(i18n.titles.login); // Displays 'Connexion' in the markup with id 'main'

5. Change the locale in the requireJS configuration options

9.2. Replacement in labels¶

You can use the $.sprintf() jquery function to have some replacement in your labels.
For example, with label:

i18n.texts.welcome = 'Welcome %s !';

You can have replacement this way:

$('#main').html($.sprintf(i18n.texts.welcome, 'Homer')); // Displays 'Welcome Homer !' in the markup with id 'main'

Just do not forget to include ‘lib/jquery/jquery.sprintf’ in your dependencies.

See sprintf Plugin documentation.

9.3. Labels in templates¶

Templates necessarily contain labels.
The prefered way of passing labels to a template is during its rendering:

this.render({i18n:i18n, user:this.user});

And used in the template:

<div class="home">
        <h1>${$.sprintf(i18n.texts.welcome, user.firstName, user.lastName)}</h1>

        <form id="passwordChange">
                <h2>${i18n.labels.editPassword}</h2>

You’ll notice that the $.sprintf() method is useable also in templates.

Table Of Contents

9. Internationalization

9.1. i18n primer

9.2. Replacement in labels

9.3. Labels in templates

Related Topics

Documentation overview

Previous: 8. Repositories

Next: 10. OAuth2 support

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      © Copyright 2011, pullrequest.org.
      Created using Sphinx.


text:
 /* Some parts.
 *
 * Author: Ian Piumarta <ian.piumarta@squeakland.org>
 *
 *   Copyright (C) 1996-2005 by Ian Piumarta and other authors/contributors
 *                              listed elsewhere in this file.
 *   All rights reserved.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *   SOFTWARE.
 *
 * Last edited: 2006-10-18 10:01:37 by piumarta on emilia.local
 */
#include <Carbon/Carbon.h>
#import <Cocoa/Cocoa.h>

#include "sq.h"
#include "sqMacNSPluginUILogic2.h"

sqInt ioSetCursorARGB(sqInt cursorBitsIndex, sqInt extentX, sqInt extentY, sqInt offsetX, sqInt offsetY);
void SetCursorBackToSomething(void);
int amIOSX102X(void);

NSCursor         *cursor= 0;
Boolean			biggerCursorActive=false;
extern Cursor macCursor;

void SetCursorBackToSomething() {
	if (biggerCursorActive) {
		[cursor set];
	}
	else
		SetCursor(&macCursor);
}

sqInt ioSetCursorARGB(sqInt cursorBitsIndex, sqInt extentX, sqInt extentY, sqInt offsetX, sqInt offsetY)
{
extern Boolean gSqueakHeadless;
extern Boolean gSqueakHasCursor;

	if (gSqueakHeadless) return 0;
	if (browserActiveAndDrawingContextOk() && !browserActiveAndDrawingContextOkAndInFullScreenMode())
		return 0;
	if (amIOSX102X())
		return 0;
// ? and what does the browser plugin do? We do not have code to manage big cursors.

      NSAutoreleasePool *pool= [[NSAutoreleasePool alloc] init];
      NSBitmapImageRep *bitmap= 0;
      NSImage          *image=  0;

	static BOOL		firstTime	= YES;

	if ( firstTime )
	{
		//	Must first call [[[NSWindow alloc] init] release] to get the NSWindow machinery set up so that NSCursor can use a window to cache the cursor image
		[[[NSWindow alloc] init] release];
		firstTime = NO;
	}
	biggerCursorActive = true;
	gSqueakHasCursor = true;

	bitmap= [[NSBitmapImageRep alloc]
		initWithBitmapDataPlanes: 0 pixelsWide: extentX pixelsHigh: extentY
		bitsPerSample: 8 samplesPerPixel: 4
		hasAlpha: YES isPlanar: NO
		colorSpaceName: NSCalibratedRGBColorSpace
		bytesPerRow: extentX * 4
		bitsPerPixel: 0];
      {
	unsigned *planes[5];
	[bitmap getBitmapDataPlanes: planes];
	unsigned* src= (unsigned*)cursorBitsIndex;
	unsigned* dst= planes[0];
	int i;
	for (i= 0; i < extentX * extentY; ++i, ++dst, ++src) {
#if VMENDIANNESS
		*dst=  ((*src & 0xFF000000) >> 24) | ((*src & 0x00FFFFFF) << 8) ; // ARGB to RGBA
#else
		*dst= (*src & 0xFF00FF00) | ((*src & 0x000000FF) << 16) | ((*src & 0x00FF0000) >> 16); // BGRA to RGBA
#endif
	}
      }
      image= [[NSImage alloc] init];
      [image addRepresentation: bitmap];
      {
	NSPoint hotSpot= { -offsetX, -offsetY };
	if (cursor)
		[cursor release];
	cursor= [[NSCursor alloc] initWithImage: image hotSpot: hotSpot];
      }
      [cursor set];
	   // [NSCursor unhide];
      [pool release];

  return 1;
}

// Code below is example stuff

/*
	File:		NSCursorWrappers.m

	Abstract:	Provide Carbon wrapper functions around the Cocoa NSCursor methods we
				use to handle our cursor support.

	Version:	1.0

	Disclaimer:	IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
 ("Apple") in consideration of your agreement to the following terms, and your
 use, installation, modification or redistribution of this Apple software
 constitutes acceptance of these terms.  If you do not agree with these terms,
 please do not use, install, modify or redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject
 to these terms, Apple grants you a personal, non-exclusive license, under Apple's
 copyrights in this original Apple software (the "Apple Software"), to use,
 reproduce, modify and redistribute the Apple Software, with or without
 modifications, in source and/or binary forms; provided that if you redistribute
 the Apple Software in its entirety and without modifications, you must retain
 this notice and the following text and disclaimers in all such redistributions of
 the Apple Software.  Neither the name, trademarks, service marks or logos of
 Apple Computer, Inc. may be used to endorse or promote products derived from the
 Apple Software without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or implied,
 are granted by Apple herein, including but not limited to any patent rights that
 may be infringed by your derivative works or by other works in which the Apple
 Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
						GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	Copyright © 2006 Apple Computer, Inc., All Rights Reserved
 */

/*
#import <Cocoa/Cocoa.h>
#import "NSCursorWrappers.h"

//	From "Cocoa Drawing Guide: Working with Images"
NSImage	*CreateNSImageFromCGImage( CGImageRef image )
{
	NSRect			imageRect		= NSMakeRect(0.0, 0.0, 0.0, 0.0);

	// Get the image dimensions.
	imageRect.size.height = CGImageGetHeight(image);
	imageRect.size.width = CGImageGetWidth(image);

	// Create a new image to receive the Quartz image data.
	NSImage	*newImage = [[NSImage alloc] initWithSize:imageRect.size];
	[newImage lockFocus];

	// Get the Quartz context and draw.
	CGContextRef	imageContext = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
	CGContextDrawImage( imageContext, *(CGRect*)&imageRect, image );
	[newImage unlockFocus];

	return( newImage );
}

//	C-based style wrapper routines around NSCursor
CursorRef	CreateCocoaCursor( CGImageRef cgImageRef, float hotSpotX, float hotSpotY )
{
	static BOOL		firstTime	= YES;

	if ( firstTime )
	{
		//	Must first call [[[NSWindow alloc] init] release] to get the NSWindow machinery set up so that NSCursor can use a window to cache the cursor image
		[[[NSWindow alloc] init] release];
		firstTime = NO;
	}

	NSImage		*nsImage	= CreateNSImageFromCGImage( cgImageRef );
	NSCursor	*cursor		= [[NSCursor alloc] initWithImage:nsImage hotSpot:NSMakePoint( hotSpotX, hotSpotY )];

	[nsImage release];

	return( (CursorRef)cursor );
}

void	ReleaseCocoaCursor( CursorRef cursor )
{
	[(NSCursor *)cursor release];
}

void	SetCocoaCursor( CursorRef cursor )
{
	[(NSCursor *)cursor set];
}

void	HideCocoaCursor()
{
	[NSCursor hide];
}

void	ShowCocoaCursor()
{
	[NSCursor unhide];
}
*/


text:
package org.datavec.image.mnist;

import org.apache.commons.io.FileUtils;
import org.datavec.api.util.ArchiveUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class MnistFetcher {

    private File fileDir;
    private static Logger log = LoggerFactory.getLogger(MnistFetcher.class);
    private static final String trainingFilesURL = "http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz";

    private static final String trainingFilesFilename = "images-idx1-ubyte.gz";
    public static final String trainingFilesFilename_unzipped = "images-idx1-ubyte";

    private static final String trainingFileLabelsURL = "http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz";
    private static final String trainingFileLabelsFilename = "labels-idx1-ubyte.gz";
    public static final String trainingFileLabelsFilename_unzipped = "labels-idx1-ubyte";
    private static final String LOCAL_DIR_NAME = "MNIST";

    public File downloadAndUntar() throws IOException {
        if (fileDir != null) {
            return fileDir;
        }
        // mac gives unique tmp each run and we want to store this persist
        // this data across restarts
        File tmpDir = new File(System.getProperty("user.home"));

        File baseDir = new File(tmpDir, LOCAL_DIR_NAME);
        if (!(baseDir.isDirectory() || baseDir.mkdir())) {
            throw new IOException("Could not mkdir " + baseDir);
        }

        log.info("Downloading mnist...");
        // getFromOrigin training records
        File tarFile = new File(baseDir, trainingFilesFilename);

        if (!tarFile.isFile()) {
            FileUtils.copyURLToFile(new URL(trainingFilesURL), tarFile);
        }

        ArchiveUtils.unzipFileTo(tarFile.getAbsolutePath(), baseDir.getAbsolutePath());

        // getFromOrigin training records
        File labels = new File(baseDir, trainingFileLabelsFilename);

        if (!labels.isFile()) {
            FileUtils.copyURLToFile(new URL(trainingFileLabelsURL), labels);
        }

        ArchiveUtils.unzipFileTo(labels.getAbsolutePath(), baseDir.getAbsolutePath());

        fileDir = baseDir;
        return fileDir;
    }

    public void untarFile(File baseDir, File tarFile) throws IOException {

        log.info("Untaring File: " + tarFile.toString());

        Process p = Runtime.getRuntime()
                        .exec(String.format("tar -C %s -xvf %s", baseDir.getAbsolutePath(), tarFile.getAbsolutePath()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        log.info("Here is the standard error of the command (if any):\n");
        String s;
        while ((s = stdError.readLine()) != null) {
            log.info(s);
        }
        stdError.close();

    }

    public static void gunzipFile(File baseDir, File gzFile) throws IOException {

        log.info("gunzip'ing File: " + gzFile.toString());

        Process p = Runtime.getRuntime().exec(String.format("gunzip %s", gzFile.getAbsolutePath()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        log.info("Here is the standard error of the command (if any):\n");
        String s;
        while ((s = stdError.readLine()) != null) {
            log.info(s);
        }
        stdError.close();

    }

}


text:
<idea-plugin version="2">
  <id>com.objectmastery.stylelint</id>
  <name>StyleLint</name>
  <version>1.0</version>
  <vendor email="omcode@objectmastery.com" url="https://github.com/objectmastery/stylelint-plugin">ObjectMastery</vendor>

  <description><![CDATA[
      StyleLint intellij integration.

    ]]></description>

  <change-notes><![CDATA[

1.0 First version, forked from ESLint-Plugin.

    ]]></change-notes>

  <idea-version since-build="141.0"/>

  <depends>com.intellij.modules.lang</depends>
  <depends>JavaScript</depends>
  <depends optional="true">com.intellij.css</depends>

  <extensions defaultExtensionNs="com.intellij">
    <projectService serviceImplementation="com.stylelint.settings.Settings"/>
    <projectConfigurable groupId="tools" displayName="StyleLint Settings" instance="com.stylelint.settings.StyleLintSettingsPage"/>

    <projectService serviceImplementation="com.stylelint.config.StyleLintConfigFileListener"/>
    <fileTypeFactory implementation="com.stylelint.config.StyleLintConfigFileTypeFactory"/>

    <localInspection language="CSS" groupPath="CSS" shortName="StyleLintInspection"
                     enabledByDefault="true" level="ERROR"
                     bundle="com.stylelint.StyleLintBundle"
                     implementationClass="com.stylelint.StyleLintInspection"
                     displayName="StyleLint" groupKey="stylelint.inspection.group.name"/>

    <externalAnnotator language="CSS" implementationClass="com.stylelint.StyleLintExternalAnnotator" />
  </extensions>

  <project-components>

    <component>
      <implementation-class>com.stylelint.StyleLintProjectComponent</implementation-class>
    </component>
  </project-components>

  <actions>

  </actions>

</idea-plugin>


text:
require "spec_helper"

describe SpreeShopifyImporter::Importers::ImageImporterJob, type: :job do
  subject { described_class.new }

  describe "#perfrom" do
    let(:resource) { double("ShopifyAPI::Image") }
    let(:parent_feed) { double("Shopify::DataFeed") }
    let(:spree_object) { double("Spree::Product") }

    it "calls a importer service" do
      expect(SpreeShopifyImporter::Importers::ImageImporter).to receive(:new).and_call_original
      expect_any_instance_of(SpreeShopifyImporter::Importers::ImageImporter).to receive(:import!)

      subject.perform(resource, parent_feed, spree_object)
    end
  end
end


text:
* Replace superagent-promise with restling (#8)

### Bug Fixes

* Avoid extra empty line (#7)

## 1.2.0 (June 21, 2015)

### Dependency Upgrades

* Update dependencies (#6)

## 1.1.0 (March 8, 2015)

### Bug Fixes

* Fix crash with mulitline commit message body (#4)

### Dependency Upgrades

* Update eslint (#5)
* Update dependencies (#3)

## 1.0.0 (January 22, 2015)

Initial release


text:
export default function updateActiveNavItem(activeSection, nav) {
  const previousActive = nav.querySelector('[data-sn-active]');

  if (!activeSection) {
    if (previousActive) {
      previousActive.classList.remove('scroll-nav__item--active');
      previousActive.removeAttribute('data-sn-active');
    }

    return;
  }

  const newActive = nav.querySelector(
    '[data-sn-section=' + activeSection.id + ']'
  );

  if (newActive && newActive !== previousActive) {
    if (previousActive) {
      previousActive.classList.remove('scroll-nav__item--active');
      previousActive.removeAttribute('data-sn-active');
    }
    newActive.classList.add('scroll-nav__item--active');
    newActive.setAttribute('data-sn-active', true);
  }
}


text:
from .tm_test import test_tbmatch
from .surf_test import test_surfmatch
from .sift_test import test_siftmatch
from .orb_test import test_orbmatch


text:
class WXDLLIMPEXP_CORE wxScreenDCImpl : public wxWindowDCImpl
{
public:
    wxScreenDCImpl( wxScreenDC *owner );

    ~wxScreenDCImpl();

    virtual void DoGetSize(int *width, int *height) const wxOVERRIDE;

private:

    wxDECLARE_ABSTRACT_CLASS(wxScreenDCImpl);
};

#endif // _WX_QT_DCSCREEN_H_


text:
/// <reference path="../../../Scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../../models/eventStreamModel.ts" />
/// <reference path="../../models/userRegistrationModel.ts" />
/// <reference path="../../factories/eventStreamFactory.ts" />
/// <reference path="../../factories/materialViewFactory.ts" />

"use strict";

module app.angular.Directives {
    import EventStreamDataModel = angular.Models.EventStreamDataModel;
    import UserRegistrationRequestModel = angular.Models.UserRegistrationRequestModel;

    export interface IUserRegistrationScope extends ng.IScope {
        model: angular.Models.EventStreamDataModel;
        click: Function;
    }

    export class UserRegistration implements ng.IDirective {
        replace = true;
        restrict = "EA";
        scope = {};
        templateUrl = "/App/components/userRegistration/userRegistration.html";

        link($scope: IUserRegistrationScope, element: JQuery, attributes: ng.IAttributes) {
            var $submit = element.find("input#submit");
            $submit.on("click", () => {
                var streamId = element.data("stream-id");
                $scope.click(streamId);
            });
        }

        controller($scope: IUserRegistrationScope, eventStreamFactory: angular.Factories.EventStreamFactory, materialViewFactory: angular.Factories.MaterialViewFactory) {
            $scope.model = new EventStreamDataModel();

            eventStreamFactory.getEventStream()
                .success((response: angular.Models.EventStreamResponseModel) => {
                    $scope.model.streamId = response.data.streamId;
                    console.log($scope.model);
                });

            $scope.click = (streamId) => {
                var request = new UserRegistrationRequestModel(streamId);

                eventStreamFactory.registerUser(request)
                    .success((response: angular.Models.UserRegistrationResponseModel) => {
                        materialViewFactory.setMaterialisedView(response.data.title, response.data.username, response.data.email);
                        console.log(response);
                    });
            }
        }
    }
}

angular.module("app")
    .directive("userRegistration", () => new app.angular.Directives.UserRegistration());


text:
class CategoriesController < ApplicationController

  include CategoriesHelper
  before_action :check_format!
  before_action :get_category!, :only => [:update, :destroy, :places]

  # GET /categories.json
  # ---------------------------------------------------------------------------------------
  def index
    render status: 200, json: Category.all.to_json
  end

  # POST /categories.json
  # ---------------------------------------------------------------------------------------
  def create
    @category = Category.new(category_params)

    if @category.save
      render status: 201, json: {
          :status => '0'
      }
    else
      render status: 500, json: {
          :status => '-1',
          :message => @category.errors.full_messages
      }
    end
  end

  # PATCH/PUT /categories/1.json
  # ---------------------------------------------------------------------------------------
  def update
    if @category.update(category_params)
      render status: 200, json: {
          :status => '0'
      }
    else
      render status: 400, json: {
          :status => '-1',
          :message => @category.errors.full_messages.join(', ')
      }
    end
  end

  # DELETE /categories/1.json
  # ---------------------------------------------------------------------------------------
  def destroy
    @category.destroy

    render status: 200, json: {
        :status => '0'
    }
  end

  # GET /category/:id/places.json
  # ---------------------------------------------------------------------------------------
  def places
    render status: 200, json: Place.where(
        :category_id => @category.id
    ).to_json
  end

end


text:
'use strict';

var isNative = require( './../lib' );

console.log( isNative( Math.sqrt ) );
// returns true

console.log( isNative( String ) );
// returns true

console.log( isNative( Object.prototype.toString ) );
// returns true

console.log( isNative( Int16Array ) );
// returns true

console.log( isNative( function(){} ) );
// returns false

console.log( isNative( null ) );
// returns false


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Natfie - Welcome to the Otherside</title>

	<link href="css/main/login2.css" rel="stylesheet" type="text/css"/>

			<form name="loginformname" method="post" id="loginformname" class="loginformid" enctype="application/x-www-form-urlencoded" action="testlog.php"  autocomplete="off">

<input type="checkbox" name="rememberme" value="1" style="margin-top: 5px; vertical-align: top;"/>Remember Me

						<input class='login_lock_fborderi' style='font-size: 16px;' value="" title="Email" type="text" placeholder="Email" id="username" name="username" maxlength="2048" style="border: none; outline-style: none;" spellcheck="false" autocomplete="on"/>

						<input class='login_lock_fborderi' style='font-size: 16px;' value="" title="Password" placeholder="Password" type="password" id="password" name="password" maxlength="2048" spellcheck="false"/>

Incorrect please try again

									<input class='login_lock_fborderi' style='font-size: 16px;' value="" title="Captcha" placeholder="Type the text in the box above..." type="text" id="recaptcha_response_field" name="recaptcha_response_field"  maxlength="2048" spellcheck="false"/>

								<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
								<input type="hidden" name="recaptcha_response_field" value="manual_challenge">

<input type="submit" id="cnai_send" style="visibility: hidden; float: left;"/>

				<input type="submit" id="submit" name="login" value="Log in" style='font-size: 16px;' class="login_button lock"/>

				<input name="action" id="action" value="login" type="hidden">

				Forgot password?
Sign up!

			</form>

New?

			About  | Help  |  Privacy Policy   | Contact

  English  | 中文  |  Français   | Pусский | Español | हिन्दी


text:
import Pokemon from './pokemon';

class Pokedex {
    constructor(json) {
        this.json = json;
        this.pokemons = [];
        this.team = [];
        this.loader = '';
        this.list = '';
        this.allDom = '';
        this.teamDom = '';
    }

    init() {
        this.list = document.querySelector('#pokemon-list');
        this.loader = document.querySelector('#loader');

        this.loader.classList.remove('hidden');

        fetch(this.json)
            .then((res) => {
                if (res.ok) {
                    return res.json();
                }

                throw Error(res.statusText);
            })
            .catch(err => console.error(err))
            .then((pokemons) => {
                if (pokemons instanceof Array) {
                    this.loader.classList.add('hidden');

                    this.pokemons = pokemons;

                    this.menu();
                    this.initTeam();
                    this.list.innerHTML = this.load(this.pokemons);
                    this.toggleCatchPokemon();
                }
            });
    }

    menu() {
        const body = document.querySelector('body');
        const choices = document.querySelectorAll('#menu li');

        for (let i = 0; i < choices.length; i += 1) {
            choices[i].addEventListener('click', (e) => {
                e.preventDefault();

                if (e.currentTarget.classList.contains('2')) {
                    body.classList.remove('list');
                    body.classList.add('team');

                    this.teamDom = this.load(
                        this.pokemons.filter(p => this.team.indexOf(p.id) !== -1)
                    );

                    // Reset data
                    this.list.innerHTML = this.teamDom;
                    this.toggleCatchPokemon();
                } else {
                    body.classList.remove('team');
                    body.classList.add('list');

                    this.allDom = this.load(this.pokemons);

                    // Reset data
                    this.list.innerHTML = this.allDom;
                    this.toggleCatchPokemon();
                }
            });
        }
    }

    initTeam() {
        if (Pokedex.pokemonsFromLocalStorage() === null) {
            localStorage.setItem('pokémons', JSON.stringify([]));
        }

        this.team = Pokedex.pokemonsFromLocalStorage();
    }

    static pokemonsFromLocalStorage() {
        return JSON.parse(localStorage.getItem('pokémons'));
    }

    isInTeam(id) {
        // In case the pokemon is in the local storage
        return !!(this.team.length > 0 && this.team.indexOf(id) !== -1);
    }

    load(pokemons) {
        let pokemon = {};
        let dom = '';

        for (let i = 0; i < pokemons.length; i += 1) {
            pokemon = new Pokemon(
                pokemons[i].id,
                pokemons[i].number,
                pokemons[i].name,
                pokemons[i].image,
                pokemons[i].types,
                this.isInTeam(pokemons[i].id),
                i
            );

            dom += pokemon.template();
        }

        return dom;
    }

    toggleCatchPokemon() {
        const pokeballs = document.querySelectorAll('.is-gotten');

        for (let i = 0; i < pokeballs.length; i += 1) {
            pokeballs[i].addEventListener('click', (e) => {
                e.preventDefault();

                const id = parseInt(e.currentTarget.dataset.id, 10);

                // If already caught (id in localstorage)
                if (this.team.indexOf(id) !== -1) {
                    this.team.splice(this.team.indexOf(id), 1);
                    e.currentTarget.classList.remove('gotten');
                } else if (this.team.length < 6) {
                    this.team.push(id);
                    e.currentTarget.classList.add('gotten');
                } else {
                    alert('Vous avez déjà 6 pokémons dans votre équipe.'); // eslint-disable-line no-alert
                }

                localStorage.setItem('pokémons', JSON.stringify(this.team));
            });
        }
    }
}

export default Pokedex;


text:
"""CLI for interacting with CBenchF."""

import cmd
import os
import sys

# Makes imports relative to root of repo
new_path = [os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")]
sys.path = new_path + sys.path

import cbenchf.controllers.opendaylight as odl_mod

class CLI(cmd.Cmd):

    """CLI for intracting with CBenchF."""

    prompt = "cbenchf$ "

    def __init__(self):
        """"""
        # Call superclass __init__ (required by cmd.Cmd)
        cmd.Cmd.__init__(self)

        # Build instance of ODL abstraction
        self.odl = odl_mod.OpenDaylight()

    def do_start_odl(self, raw_args):
        """Start an OpenDaylight controller.

        :param raw_args: Mandatory param for Cmd handler, not used.
        :type raw_args: string

        """
        self.odl.start()

    def help_start_odl(self):
        """Provide help message for start_odl command."""
        print("start_odl")
        print("\tStart an OpenDaylight controller.")

    def do_stop_odl(self, raw_args):
        """Stop the OpenDaylight controller.

        :param raw_args: Mandatory param for Cmd handler, not used.
        :type raw_args: string

        """
        self.odl.stop()

    def help_stop_odl(self):
        """Provide help message for stop_odl command."""
        print("stop_odl")
        print("\tStop the OpenDaylight controller.")

    def do_shell(self, cmd):
        """Allows normal shell commands to be run.

        :param cmd: Everything after "shell" or "!", to be passed to shell.
        :type cmd: string

        """
        os.system(cmd)

    def help_shell(self):
        """Provide help message for shell command."""
        print("!|shell <command>")
        print("\tSend command to underlying system shell (like Bash/ZSH).")

    def do_EOF(self, raw_args):
        """Cleans up when ctrl+d is used to exit CLI.

        TODO: Add any future clean-up (closing controller) here.

        :param raw_args: Mandatory param for Cmd handler, not used.
        :type raw_args: string

        """
        return True

    def help_EOF(self):
        """Provide help message for EOF (ctrl+d) command."""
        print("ctrl+d")
        print("\tClean up and close CLI cleanly.")

    def help_help(self):
        """Provide help message for help command."""
        print("help [command]")
        print("\tProvide help on given command. If no arg, list commands.")

if __name__ == "__main__":
    CLI().cmdloop()


text:
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/cloudfront/model/ItemSelection.h>
#include <aws/cloudfront/model/CookieNames.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFront
{
namespace Model
{

  /**
   * A complex type that specifies the cookie preferences associated with this cache
   * behavior.

See Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDFRONT_API CookiePreference
  {
  public:
    CookiePreference();
    CookiePreference(const Aws::Utils::Xml::XmlNode& xmlNode);
    CookiePreference& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;

    /**
     * Use this element to specify whether you want CloudFront to forward cookies to
     * the origin that is associated with this cache behavior. You can specify all,
     * none or whitelist. If you choose All, CloudFront forwards all cookies regardless
     * of how many your application uses.
     */
    inline const ItemSelection& GetForward() const{ return m_forward; }

    /**
     * Use this element to specify whether you want CloudFront to forward cookies to
     * the origin that is associated with this cache behavior. You can specify all,
     * none or whitelist. If you choose All, CloudFront forwards all cookies regardless
     * of how many your application uses.
     */
    inline void SetForward(const ItemSelection& value) { m_forwardHasBeenSet = true; m_forward = value; }

    /**
     * Use this element to specify whether you want CloudFront to forward cookies to
     * the origin that is associated with this cache behavior. You can specify all,
     * none or whitelist. If you choose All, CloudFront forwards all cookies regardless
     * of how many your application uses.
     */
    inline void SetForward(ItemSelection&& value) { m_forwardHasBeenSet = true; m_forward = std::move(value); }

    /**
     * Use this element to specify whether you want CloudFront to forward cookies to
     * the origin that is associated with this cache behavior. You can specify all,
     * none or whitelist. If you choose All, CloudFront forwards all cookies regardless
     * of how many your application uses.
     */
    inline CookiePreference& WithForward(const ItemSelection& value) { SetForward(value); return *this;}

    /**
     * Use this element to specify whether you want CloudFront to forward cookies to
     * the origin that is associated with this cache behavior. You can specify all,
     * none or whitelist. If you choose All, CloudFront forwards all cookies regardless
     * of how many your application uses.
     */
    inline CookiePreference& WithForward(ItemSelection&& value) { SetForward(std::move(value)); return *this;}

    /**
     * A complex type that specifies the whitelisted cookies, if any, that you want
     * CloudFront to forward to your origin that is associated with this cache
     * behavior.
     */
    inline const CookieNames& GetWhitelistedNames() const{ return m_whitelistedNames; }

    /**
     * A complex type that specifies the whitelisted cookies, if any, that you want
     * CloudFront to forward to your origin that is associated with this cache
     * behavior.
     */
    inline void SetWhitelistedNames(const CookieNames& value) { m_whitelistedNamesHasBeenSet = true; m_whitelistedNames = value; }

    /**
     * A complex type that specifies the whitelisted cookies, if any, that you want
     * CloudFront to forward to your origin that is associated with this cache
     * behavior.
     */
    inline void SetWhitelistedNames(CookieNames&& value) { m_whitelistedNamesHasBeenSet = true; m_whitelistedNames = std::move(value); }

    /**
     * A complex type that specifies the whitelisted cookies, if any, that you want
     * CloudFront to forward to your origin that is associated with this cache
     * behavior.
     */
    inline CookiePreference& WithWhitelistedNames(const CookieNames& value) { SetWhitelistedNames(value); return *this;}

    /**
     * A complex type that specifies the whitelisted cookies, if any, that you want
     * CloudFront to forward to your origin that is associated with this cache
     * behavior.
     */
    inline CookiePreference& WithWhitelistedNames(CookieNames&& value) { SetWhitelistedNames(std::move(value)); return *this;}

  private:
    ItemSelection m_forward;
    bool m_forwardHasBeenSet;
    CookieNames m_whitelistedNames;
    bool m_whitelistedNamesHasBeenSet;
  };

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
package com.googlecode.bpmn_simulator.bpmn.swing.model.core.common;

import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;

import com.googlecode.bpmn_simulator.animation.element.visual.Bounds;
import com.googlecode.bpmn_simulator.animation.element.visual.GeometryUtils;
import com.googlecode.bpmn_simulator.animation.element.visual.Point;
import com.googlecode.bpmn_simulator.animation.element.visual.Waypoint;
import com.googlecode.bpmn_simulator.animation.element.visual.Waypoints;
import com.googlecode.bpmn_simulator.animation.ref.ReferenceUtils;
import com.googlecode.bpmn_simulator.bpmn.model.core.common.Expression;
import com.googlecode.bpmn_simulator.bpmn.model.core.common.SequenceFlow;
import com.googlecode.bpmn_simulator.bpmn.model.core.common.gateways.Gateway;
import com.googlecode.bpmn_simulator.bpmn.swing.di.AbstractBPMNTokenEdge;

@SuppressWarnings("serial")
public final class SequenceFlowEdge
		extends AbstractBPMNTokenEdge<SequenceFlow> {

	private static final double SYMBOL_DEFAULT_RAD = Math.toRadians(45.);

	private static final int START_SYMBOL_SIZE = 8;

	private JCheckBox checkBox;

	public SequenceFlowEdge(final SequenceFlow element) {
		super(element);
	}

	@Override
	public void addNotify() {
		super.addNotify();
		if (checkBox == null) {
			createCheckbox();
		}
		updateCheckboxPosition();
	}

	private void createCheckbox() {
		final SequenceFlow sequenceflow = getLogicalElement();
		if (sequenceflow.isConditional()) {
			final Expression expression = sequenceflow.getConditionExpression();
			checkBox = new JCheckBox();
			checkBox.setOpaque(false);
			checkBox.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(final ActionEvent event) {
					expression.setValue(checkBox.isSelected());
				}
			});
			checkBox.setSelected(expression.getResult());
			getParent().add(checkBox, 0);
		}
	}

	private void updateCheckboxPosition() {
		if (checkBox != null) {
			final Waypoints waypoints = getWaypoints();
			final Point point = waypoints.getWaypoint(waypoints.getLength() / 2.);
			if (point != null) {
				final Dimension size = checkBox.getPreferredSize();
				checkBox.setBounds(point.getX() - (size.width / 2), point.getY() - (size.height / 2),
						size.width, size.height);
			}
		}
	}

	@Override
	public void addElementWaypoint(final Waypoint waypoint) {
		super.addElementWaypoint(waypoint);
		updateCheckboxPosition();
	}

	private boolean isSourceGateway() {
		return (ReferenceUtils.element(getLogicalElement().getSource()) instanceof Gateway);
	}

	@Override
	protected void paintElementStart(final Graphics2D g) {
		super.paintElementStart(g);
		final SequenceFlow sequenceFlow = getLogicalElement();
		if (sequenceFlow.isDefault()) {
			if (!sequenceFlow.isConditional()) {
				drawDefaultSymbol(g);
			}
		} else {
			if (sequenceFlow.isConditional() && !isSourceGateway()) {
				drawConditionalSymbol(g);
			}
		}
	}

	private void drawDefaultSymbol(final Graphics2D g) {
		final Waypoints waypoints = getWaypointsRelative();
		final Point position = waypoints.getWaypoint(START_SYMBOL_SIZE);
		final double angle = waypoints.getAngleAt(START_SYMBOL_SIZE) - SYMBOL_DEFAULT_RAD;
		final double length = START_SYMBOL_SIZE * 0.8;
		final Point from = GeometryUtils.polarToCartesian(position, length, angle);
		final Point to = GeometryUtils.polarToCartesian(position, length, GeometryUtils.invert(angle));
		getPresentation().drawLine(g, from, to);
	}

	private void drawConditionalSymbol(final Graphics2D g) {
		final Waypoints waypoints = getWaypointsRelative();
		final Point position = waypoints.getWaypoint(START_SYMBOL_SIZE);
		final double angle = waypoints.getAngleAt(START_SYMBOL_SIZE);
		final Bounds diamondBounds = Bounds.fromCenter(position, START_SYMBOL_SIZE, (int) (START_SYMBOL_SIZE * 0.6));
		getPresentation().rotate(g, position, angle);
		final Paint paint = g.getPaint();
		g.setPaint(getBackgroundColor());
		getPresentation().fillDiamond(g, diamondBounds);
		g.setPaint(paint);
		getPresentation().drawDiamond(g, diamondBounds);
		getPresentation().restore(g);
	}

	@Override
	protected void paintElementEnd(final Graphics2D g) {
		super.paintElementEnd(g);
		final Waypoints waypoints = getWaypointsRelative();
		if (waypoints.isValid()) {
			getPresentation().fillArrowhead(g, waypoints.nextToLast(), waypoints.last());
		}
	}

}


text:
#include "ucp_test.h"

#include <common/test_helpers.h>

#if _OPENMP
#include "omp.h"
#endif

using namespace ucs; /* For vector<char> serialization */

class test_ucp_rma_mt : public ucp_test {
public:
    static ucp_params_t get_ctx_params() {
        ucp_params_t params = ucp_test::get_ctx_params();
        params.features     = UCP_FEATURE_RMA;
        return params;
    }

    void init()
    {
        ucp_test::init();
        sender().connect(&receiver());
    }

    static std::vector<ucp_test_param> enum_test_params(const ucp_params_t& ctx_params,
                                                        const ucp_worker_params_t& worker_params,
                                                        const std::string& name,
                                                        const std::string& test_case_name,
                                                        const std::string& tls)
    {
        std::vector<ucp_test_param> result;

        generate_test_params_variant(ctx_params, worker_params, name, test_case_name, tls,
                                     0, result, MULTI_THREAD_CONTEXT);
        generate_test_params_variant(ctx_params, worker_params, name, test_case_name, tls,
                                     0, result, MULTI_THREAD_WORKER);
        return result;
    }
};

UCS_TEST_P(test_ucp_rma_mt, put_get) {
    int i;
    ucs_status_t st;
    uint64_t orig_data[MT_TEST_NUM_THREADS] GTEST_ATTRIBUTE_UNUSED_;
    uint64_t target_data[MT_TEST_NUM_THREADS] GTEST_ATTRIBUTE_UNUSED_;

    ucp_mem_map_params_t params;
    ucp_mem_h memh;
    void *memheap = target_data;

    params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS |
                        UCP_MEM_MAP_PARAM_FIELD_LENGTH |
                        UCP_MEM_MAP_PARAM_FIELD_FLAGS;
    params.address    = memheap;
    params.length     = sizeof(uint64_t) * MT_TEST_NUM_THREADS;
    params.flags      = GetParam().variant;

    st = ucp_mem_map(receiver().ucph(), &params, &memh);
    ASSERT_UCS_OK(st);

    void *rkey_buffer;
    size_t rkey_buffer_size;

    st = ucp_rkey_pack(receiver().ucph(), memh, &rkey_buffer, &rkey_buffer_size);
    ASSERT_UCS_OK(st);

    ucp_rkey_h *rkey;

    rkey = (ucp_rkey_h *)malloc(sizeof(ucp_rkey_h) * sender().get_num_workers());
    for (i = 0; i < sender().get_num_workers(); i++) {
        st = ucp_ep_rkey_unpack(sender().ep(i), rkey_buffer, &rkey[i]);
        ASSERT_UCS_OK(st);
    }

    ucp_rkey_buffer_release(rkey_buffer);

    /* test blocking PUT */

    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        orig_data[i] = 0xdeadbeefdeadbeef + 10 * i;
        target_data[i] = 0;
    }

#if _OPENMP && ENABLE_MT
#pragma omp parallel for
    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        ucs_status_t status;
        int worker_index = 0;

        if (GetParam().thread_type == MULTI_THREAD_CONTEXT)
            worker_index = i;

        status = ucp_put(sender().ep(worker_index), &orig_data[i], sizeof(uint64_t),
                         (uintptr_t)((uint64_t *)memheap + i), rkey[worker_index]);
        ASSERT_UCS_OK(status);

        sender().flush_worker(worker_index);

        EXPECT_EQ(orig_data[i], target_data[i]);
    }
#endif

    /* test nonblocking PUT */

    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        orig_data[i] = 0xdeadbeefdeadbeef + 10 * i;
        target_data[i] = 0;
    }

#if _OPENMP && ENABLE_MT
#pragma omp parallel for
    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        ucs_status_t status;
        int worker_index = 0;

        if (GetParam().thread_type == MULTI_THREAD_CONTEXT)
            worker_index = i;

        status = ucp_put_nbi(sender().ep(worker_index), &orig_data[i], sizeof(uint64_t),
                             (uintptr_t)((uint64_t *)memheap + i), rkey[worker_index]);
        ASSERT_UCS_OK_OR_INPROGRESS(status);

        sender().flush_worker(worker_index);

        EXPECT_EQ(orig_data[i], target_data[i]);
    }
#endif

    /* test blocking GET */

    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        orig_data[i] = 0;
        target_data[i] = 0xdeadbeefdeadbeef + 10 * i;
    }

#if _OPENMP && ENABLE_MT
#pragma omp parallel for
    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        ucs_status_t status;
        int worker_index = 0;

        if (GetParam().thread_type == MULTI_THREAD_CONTEXT)
            worker_index = i;

        status = ucp_get(sender().ep(worker_index), &orig_data[i], sizeof(uint64_t),
                         (uintptr_t)((uint64_t *)memheap + i), rkey[worker_index]);
        ASSERT_UCS_OK(status);

        sender().flush_worker(worker_index);

        EXPECT_EQ(orig_data[i], target_data[i]);
    }
#endif

    /* test nonblocking GET */

    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        orig_data[i] = 0;
        target_data[i] = 0xdeadbeefdeadbeef + 10 * i;
    }

#if _OPENMP && ENABLE_MT
#pragma omp parallel for
    for (i = 0; i < MT_TEST_NUM_THREADS; i++) {
        ucs_status_t status;
        int worker_index = 0;

        if (GetParam().thread_type == MULTI_THREAD_CONTEXT)
            worker_index = i;

        status = ucp_get_nbi(sender().ep(worker_index), &orig_data[i], sizeof(uint64_t),
                             (uintptr_t)((uint64_t *)memheap + i), rkey[worker_index]);
        ASSERT_UCS_OK_OR_INPROGRESS(status);

        sender().flush_worker(worker_index);

        EXPECT_EQ(orig_data[i], target_data[i]);
    }
#endif

    for (i = 0; i < sender().get_num_workers(); i++) {
        ucp_rkey_destroy(rkey[i]);
    }
    free(rkey);

    st = ucp_mem_unmap(receiver().ucph(), memh);
    ASSERT_UCS_OK(st);
}

UCP_INSTANTIATE_TEST_CASE(test_ucp_rma_mt)


text:
Users = Meteor.users;

// Search subscribe mongodb fields ['username', 'profile.name']
Users.initEasySearch(['username', 'profile.name'], {
    use: 'mongo-db'
});

// HELPERS
Users.helpers({
    boards: function() {
        return Boards.find({ userId: this._id });
    },
    hasStarred: function(boardId) {
        return this.profile.starredBoards && _.contains(this.profile.starredBoards, boardId);
    },
    isBoardMember: function() {
        var board = Boards.findOne(Router.current().params.boardId);
        return _.contains(_.pluck(board.members, 'userId'), this._id);
    },
    isBoardAdmin: function() {
        var board = Boards.findOne(Router.current().params.boardId);
        return this.isBoardMember(board) && _.where(board.members, {userId: this._id})[0].isAdmin;
    }
});

// BEFORE HOOK
Users.before.insert(function (userId, doc) {

    // connect profile.status default
    doc.profile.status = 'offline';

    // slugify to username
    doc.username = getSlug(doc.profile.name, '');
});

// AFTER HOOK
isServer(function() {
    Users.after.insert(function(userId, doc) {
        var ExampleBoard = {
            title: 'Welcome Board',
            userId: doc._id,
            permission: 'private' // Private || Public
        };

        // Welcome Board insert and list, card :)
        Boards.insert(ExampleBoard, function(err, boardId) {

            // lists
            _.forEach(['Basics', 'Advanced'], function(title) {
                var list = {
                    title: title,
                    boardId: boardId,
                    userId: ExampleBoard.userId
                };

                // insert List
                Lists.insert(list);
            });
        });
    });
});