text:
UBodySetup2D::UBodySetup2D(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

#if WITH_EDITOR

void UBodySetup2D::InvalidatePhysicsData()
{
	//ClearPhysicsMeshes();
	//BodySetupGuid = FGuid::NewGuid(); // change the guid
	//CookedFormatData.FlushData();
}

#endif

void UBodySetup2D::CreatePhysicsMeshes()
{
}

float UBodySetup2D::GetVolume(const FVector& Scale) const
{
	const float FictionalThickness = 10.0f; //@TODO: PAPER2D: Make tweakable or read from the sprite
	return AggGeom2D.GetArea(Scale) * FictionalThickness;
}


text:
import React, { Component } from "react";
import ReactDisqusComments from "react-disqus-comments";

import * as constants from "../util/constants";

class Comments extends Component {

  constructor(props) {
    super(props);

    this.state = {
      toasts: []
    };

    this.notifyAboutComment = this.notifyAboutComment.bind(this);
    this.onSnackbarDismiss = this.onSnackbarDismiss.bind(this);
  }

  onSnackbarDismiss() {
    const [, ...toasts] = this.state.toasts;
    this.setState({ toasts });
  }

  notifyAboutComment() {
    const toasts = this.state.toasts.slice();
    toasts.push({ text: "New comment available!" });
    this.setState({ toasts });
  }

  render() {
    const url = constants.SITE_URL + this.props.path;

    return (
      <ReactDisqusComments
        shortname={constants.DISQUS_SHORTNAME}
        identifier={this.props.title}
        title={this.props.title}
        url={url}
        category_id="12345"
        onNewComment={this.notifyAboutComment}
      />
    );
  }
}

export default Comments;

redpajama_set_name: RedPajamaGithub


text:
#ifndef VISQOL_INCLUDE_SVRSIMILARITYTOQUALITYMAPPER_H
#define VISQOL_INCLUDE_SVRSIMILARITYTOQUALITYMAPPER_H

#include <vector>

#include "absl/status/status.h"
#include "file_path.h"
#include "similarity_to_quality_mapper.h"
#include "support_vector_regression_model.h"

namespace Visqol {
/**
 * This class utilises a Support Vector Regression machine learning model to
 * produce a quality score from a similarity score, that was produced through
 * spectrogram comparison.
 */
class SvrSimilarityToQualityMapper : public SimilarityToQualityMapper {
 public:
  /**
   * Construct the mapper utilising the given SVR model file.
   *
   * @param support_vector_model The filepath to the SVR model file.
   */
  explicit SvrSimilarityToQualityMapper(const FilePath& support_vector_model);

  // Docs inherited from parent.
  double PredictQuality(
      const std::vector<double>& fvnsim_vector,
      const std::vector<double>& fvnsim10_vector,
      const std::vector<double>& fstdnsim_vector,
      const std::vector<double>& fvdegenergy_vector) const override;

  // Docs inherited from parent.
  absl::Status Init() override;

 private:
  /**
   * The SVR model used for predictions.
   */
  SupportVectorRegressionModel model_;

  /**
   * The filepath to the SVR model file, used for instantiating the SVR model.
   */
  FilePath model_path_;
};
}  // namespace Visqol

#endif  // VISQOL_INCLUDE_SVRSIMILARITYTOQUALITYMAPPER_H


text:
package org.kairos.tripSplitterClone.controller;

import com.google.gson.Gson;
import org.kairos.tripSplitterClone.json.JsonResponse;
import org.kairos.tripSplitterClone.tests.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;

/**
 * Created on 8/22/15 by
 *
 * @author AxelCollardBovy.
 */
@RequestMapping(value = "/test", produces = "text/json;charset=utf-8", method = RequestMethod.POST)
public class TestCtrl {

	/**
	 * Logger
	 */
	private Logger logger = LoggerFactory.getLogger(TestCtrl.class);

	@Autowired
	private Gson gson;

	/**
	 * Runs the tests.
	 *
	 * @param data
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/run.json")
	public String runTests(@RequestBody String data){
		TestListenerAdapter tla = new TestListenerAdapter();
		TestNG tripSplitterCloneTests = new TestNG();

//		tripSplitterCloneTests.setTestClasses(new Class[]{UserTest.class, DestinationTest.class, TripTest.class});
		tripSplitterCloneTests.setTestClasses(new Class[]{UserModelTest.class, DestinationModelTest.class, TripModelTest.class});
		tripSplitterCloneTests.addListener(tla);
//		tripSplitterCloneTests.setVerbose(2);
		tripSplitterCloneTests.run();

		TestSuiteResultVo testSuiteResultVo = new TestSuiteResultVo();

		for(ITestResult ngTestResult : tla.getFailedTests()){
			TestResultVo testResultVo = new TestResultVo();
			testResultVo.setClazz(ngTestResult.getTestClass().getRealClass().getSimpleName());
			testResultVo.setMethod(ngTestResult.getMethod().getMethodName());

			testSuiteResultVo.getFailedTests().add(testResultVo);
		}
		for(ITestResult ngTestResult : tla.getSkippedTests()){
			TestResultVo testResultVo = new TestResultVo();
			testResultVo.setClazz(ngTestResult.getTestClass().getRealClass().getSimpleName());
			testResultVo.setMethod(ngTestResult.getMethod().getMethodName());

			testSuiteResultVo.getSkippedTests().add(testResultVo);
		}
		for(ITestResult ngTestResult : tla.getConfigurationFailures()){
			TestResultVo testResultVo = new TestResultVo();
			testResultVo.setClazz(ngTestResult.getTestClass().getRealClass().getSimpleName());
			testResultVo.setMethod(ngTestResult.getMethod().getMethodName());

			testSuiteResultVo.getConfigurationFailures().add(testResultVo);
		}
		for(ITestResult ngTestResult : tla.getPassedTests()){
			TestResultVo testResultVo = new TestResultVo();
			testResultVo.setClazz(ngTestResult.getTestClass().getRealClass().getSimpleName());
			testResultVo.setMethod(ngTestResult.getMethod().getMethodName());

			testSuiteResultVo.getPassedTests().add(testResultVo);
		}
		if(tla.getFailedTests().size()>0 || tla.getConfigurationFailures().size()>0 || tla.getSkippedTests().size()>0){
			return this.getGson().toJson(JsonResponse.error(this.getGson().toJson(testSuiteResultVo),"At least one of the tests either failed or was skipped"));
		}else{
			return this.getGson().toJson(JsonResponse.ok(this.getGson().toJson(testSuiteResultVo),"All tests passed successfully"));
		}

	}

	private void exRun(){
		/*XmlSuite suite = new XmlSuite();
		suite.setName("CompleteTestSuite");

		XmlTest test = new XmlTest(suite);
		test.setName("CompleteTest");
		List<XmlClass> classList = new ArrayList<>();
		classList.add(new XmlClass("org.kairos.tripSplitterClone.tests.UserTest"));
//		classList.add(new XmlClass("org.kairos.tripSplitterClone.tests.UserTest"));
//		classList.add(new XmlClass("org.kairos.tripSplitterClone.tests.UserTest"));
		test.setXmlClasses(classList);

		List<XmlSuite> suites = new ArrayList<XmlSuite>();
		suites.add(suite);

		tripSplitterCloneTests.setXmlSuites(suites);*/
	}

	public Gson getGson() {
		return gson;
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}
}


text:
package org.apache.camel.converter.dozer;

import java.util.Arrays;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.converter.dozer.service.Customer;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.dozer.Mapper;
import org.junit.Test;

import static org.apache.camel.converter.dozer.DozerTestArtifactsFactory.createServiceCustomer;

public class DozerTypeConverterTest extends CamelTestSupport {

    @Override
    public void setUp() throws Exception {
        super.setUp();

        DozerBeanMapperConfiguration config = new DozerBeanMapperConfiguration();
        config.setMappingFiles(Arrays.asList("mapping.xml"));

        new DozerTypeConverterLoader(context, config);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:service-in").bean(new CustomerProcessor()).to("mock:verify-model");
            }
        };
    }

    @Test
    public void verifyCamelConversionViaDozer() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:verify-model");
        mock.expectedMessageCount(1);

        template.sendBody("direct:service-in", createServiceCustomer());

        assertMockEndpointsSatisfied();
    }

    @Test
    public void verifyCustomerMapping() throws Exception {
        Mapper mapper = DozerTestArtifactsFactory.createMapper(context);
        Customer service = createServiceCustomer();
        org.apache.camel.converter.dozer.model.Customer model = mapper.map(service, org.apache.camel.converter.dozer.model.Customer.class);
        Customer roundTrip = mapper.map(model, Customer.class);
        assertEquals(service, roundTrip);
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="test.IDao.OrderMapper" >
  <resultMap id="BaseResultMap" type="test.domain.Order" >
    <result column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="order_id" property="orderId" jdbcType="INTEGER" />
    <result column="product_id" property="productId" jdbcType="INTEGER" />
    <result column="to_user_id" property="toUserId" jdbcType="INTEGER" />
    <result column="order_code" property="orderCode" jdbcType="VARCHAR" />
    <result column="crtime" property="crtime" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="VARCHAR" />
    <result column="orderdetail_id" property="orderdetailId" jdbcType="INTEGER" />
    <result column="product_name" property="productName" jdbcType="VARCHAR" />
    <result column="price" property="price" jdbcType="REAL" />
    <result column="amount" property="amount" jdbcType="REAL" />
  </resultMap>
  <insert id="insert" parameterType="test.domain.Order" >
    insert into user_order_list_v (user_id, user_name, order_id,
      product_id, to_user_id, order_code,
      crtime, status, orderdetail_id,
      product_name, price, amount
      )
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{orderId,jdbcType=INTEGER},
      #{productId,jdbcType=INTEGER}, #{toUserId,jdbcType=INTEGER}, #{orderCode,jdbcType=VARCHAR},
      #{crtime,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR}, #{orderdetailId,jdbcType=INTEGER},
      #{productName,jdbcType=VARCHAR}, #{price,jdbcType=REAL}, #{amount,jdbcType=REAL}
      )
  </insert>
  <insert id="insertSelective" parameterType="test.domain.Order" >
    insert into user_order_list_v
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        user_id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="orderId != null" >
        order_id,
      </if>
      <if test="productId != null" >
        product_id,
      </if>
      <if test="toUserId != null" >
        to_user_id,
      </if>
      <if test="orderCode != null" >
        order_code,
      </if>
      <if test="crtime != null" >
        crtime,
      </if>
      <if test="status != null" >
        status,
      </if>
      <if test="orderdetailId != null" >
        orderdetail_id,
      </if>
      <if test="productName != null" >
        product_name,
      </if>
      <if test="price != null" >
        price,
      </if>
      <if test="amount != null" >
        amount,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="orderId != null" >
        #{orderId,jdbcType=INTEGER},
      </if>
      <if test="productId != null" >
        #{productId,jdbcType=INTEGER},
      </if>
      <if test="toUserId != null" >
        #{toUserId,jdbcType=INTEGER},
      </if>
      <if test="orderCode != null" >
        #{orderCode,jdbcType=VARCHAR},
      </if>
      <if test="crtime != null" >
        #{crtime,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=VARCHAR},
      </if>
      <if test="orderdetailId != null" >
        #{orderdetailId,jdbcType=INTEGER},
      </if>
      <if test="productName != null" >
        #{productName,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=REAL},
      </if>
      <if test="amount != null" >
        #{amount,jdbcType=REAL},
      </if>
    </trim>
  </insert>
</mapper>


text:
using System;

namespace Azure.ResourceManager.Cdn.Models
{
    /// <summary> The JSON object that contains the properties to validate a domain. </summary>
    public partial class DomainValidationProperties
    {
        /// <summary> Initializes a new instance of DomainValidationProperties. </summary>
        internal DomainValidationProperties()
        {
        }

        /// <summary> Initializes a new instance of DomainValidationProperties. </summary>
        /// <param name="validationToken"> Challenge used for DNS TXT record or file based validation. </param>
        /// <param name="expiresOn"> The date time that the token expires. </param>
        internal DomainValidationProperties(string validationToken, DateTimeOffset? expiresOn)
        {
            ValidationToken = validationToken;
            ExpiresOn = expiresOn;
        }

        /// <summary> Challenge used for DNS TXT record or file based validation. </summary>
        public string ValidationToken { get; }
        /// <summary> The date time that the token expires. </summary>
        public DateTimeOffset? ExpiresOn { get; }
    }
}


text:
(function () {
'use strict';
var module = angular.module('fim.base');
module.factory('IndexedEntityProvider', function (nxt, $timeout, $q, $interval) {

  function IndexedEntityProvider() {
  }
  IndexedEntityProvider.prototype = {

    /**
     * # getData
     *
     * This function is provided by the extending class.
     *
     * It expects a firstIndex argument. The result must be a Promise that
     * retrieves said data.
     */
    getData: function (firstIndex) {
      console.log('IndexedEntityProvider.getData not implemented');
      var deferred = $q.defer();
      deferred.resolve({msg: 'Implement me please'});
      return deferred.promise;
    },

    /**
     * # dataIterator
     *
     * It expects the raw data returned from the getData function and returns
     * an Iterator.
     *
     * If the data returned from getData needs additional filtering it must be
     * done in this function.
     */
    dataIterator: function (data) {
      console.log('IndexedEntityProvider.dataIterator not implemented');
      return new Iterator([]);
    },

    /**
     * # transactionIterator
     *
     * It expects an array of transactions and returns an Iterator. This method
     * is called from 'addedConfirmedTransactions', 'addedUnConfirmedTransactions'
     * and 'removedUnConfirmedTransactions'.
     *
     * If an account was set or if this provider must filter certain types of
     * transactions it must be done in this function.
     */
    transactionIterator: function (transactions) {
      console.log('EntityProvider.transactionIterator not implemented for '+Object.prototype.toString.call(this));
      return new Iterator([]);
    },

    /**
     * # uniqueKey
     *
     * This function is provided by the extending class.
     * In order to prevent duplicate entries to appear each entity must have a
     * unique key.
     *
     * This function expects an entity and returns a unique key to identify that
     * entity.
     */
    uniqueKey: function (entity) {
      console.log('IndexedEntityProvider.uniqueKey not implemented');
      console.trace();
      return entity;
    },

    /**
     * # sortFunction
     *
     * This function is provided by the extending class.
     * In order to sort results the extending class must provide a comparator function
     * which is used in the Array.sort(func) call.
     */
    sortFunction: function (a, b) {
      console.log('IndexedEntityProvider.sortFunction not implemented');
      return 0;
    },

    init: function (api, $scope, pageSize, account) {
      var self        = this;
      this.api        = api;
      this.$scope     = $scope;
      this.entities   = [];
      this.keys       = {};
      this.isLoading  = true;
      this.hasMore    = true;
      this.pageSize   = pageSize;
      this.account    = account;
    },

    /**
     * Applies a function on each entity every N milliseconds.
     * Implementers would use this function to define a function that updates
     * calculated date fields of the 'timeago' type.
     *
     * @param each_fn Function
     * @param delay (optional)
     */
    interval: function (each_fn, delay) {
      var interval = $interval(angular.bind(this, function () { this.forEach(each_fn) }), delay||15*1000);
      this.$scope.$on('$destroy', function () { $interval.cancel(interval) });
    },

    reload: function () {
      var self = this;
      var deferred = $q.defer();
      this.$scope.$evalAsync(function () {
        self.entities.length  = 0;
        self.keys             = {};
        self.isLoading        = true;
        self.hasMore          = true;
        $timeout(function () {  self.getNetworkData(0, deferred); }, 1, false);
      });
      return deferred.promise;
    },

    clear: function () {
      var self = this;
      this.$scope.$evalAsync(function () {
        self.entities.length  = 0;
        self.keys             = {};
      });
    },

    loadMore: function () {
      if (this.loadMoreBusy) {
        this.scheduledLoadMore = true;
      }
      else {
        var self = this;
        this.loadMoreBusy = $q.defer();
        this.loadMoreBusy.promise.then(function () {
          self.loadMoreBusy = null;
          if (self.scheduledLoadMore) {
            self.scheduledLoadMore  = false;
            self.loadMore();
          }
        });

        this.$scope.$evalAsync(function () {
          self.isLoading = true;
          self.getNetworkData(self.entities.length).then(self.loadMoreBusy.resolve);
        });
      }
    },

    getNetworkData: function (firstIndex, reload_deferred) {
      var deferred = $q.defer();
      var self = this;
      this.getData(firstIndex).then(
        function (data) {
          self.$scope.$evalAsync(function () {
            self.isLoading = false;
            var iterator = self.dataIterator(data);
            self.processGetData(iterator, false);
            deferred.resolve();
            if (reload_deferred) {
              reload_deferred.resolve();
            }
          });
        },
        function (data) {
          self.$scope.$evalAsync(function () {
            self.isLoading = false;
            deferred.resolve();
            if (reload_deferred) {
              reload_deferred.resolve();
            }
          });
        }
      );
      return deferred.promise;
    },

    processGetData: function (iterator, unshift) {
      this.hasMore = iterator.hasMore();
      var entity, key;
      while (iterator.hasMore()) {
        entity = iterator.next();
        key = this.uniqueKey(entity);
        if (!this.keys[key]) {
          this.keys[key] = entity;
          entity.uniqueKey = key;
          if (unshift) {
            this.entities.unshift(entity);
          }
          else {
            this.entities.push(entity);
          }
        }
        else {
          angular.extend(this.keys[key], entity);
        }
      }
      this.sort();
    },

    remove: function (uniqueKey) {
      if (this.keys[uniqueKey]) {
        delete this.keys[uniqueKey];
        this.filter(function (other) {
          return other.uniqueKey !== uniqueKey;
        });
      }
    },

    /* Adds or updates an entity.
       If there is no such entity it is added.
       If there is an entity with the same uniqueKey it is updated. */
    add: function (entity) {
      var key = this.uniqueKey(entity);
      if (this.keys[key]) {
        angular.extend(this.keys[key], entity);
      }
      else {
        this.keys[key] = entity;
        entity.uniqueKey = key;
        this.entities.unshift(entity);
      }
      this.sort();
    },

    filter: function (filter_fn) {
      this.entities = this.entities.filter(filter_fn);
    },

    sort: function () {
      this.entities.sort(angular.bind(this, this.sortFunction));
    },

    forEach: function (each_fn) {
      this.entities.forEach(each_fn);
    },

    subscribe: function (topic, handler) {
      this.api.engine.socket().subscribe(topic, angular.bind(this, handler), this.$scope);
    },

    /* Extending classes can re-use this generic sorted function */
    transactionSort: function (a, b) {
      if (b.confirmations < a.confirmations) {
        return 1;
      }
      else if (b.confirmations > a.confirmations) {
        return -1;
      }
      else {
        if (a.timestamp < b.timestamp) {
          return 1;
        }
        else if (a.timestamp > b.timestamp) {
          return -1;
        }
      }
      return 0;
    },

    /* @websocket */
    removedUnConfirmedTransactions: function (transactions) {
      var self = this;
      var length = this.entities.length;
      this.entities = this.entities.filter(
        function (entity) {
          for (var i=0; i<transactions.length; i++) {
            if (self.uniqueKey(transactions[i]) == self.uniqueKey(entity)) {
              delete self.keys[self.uniqueKey(entity)];
              return false;
            }
          }
          return true;
        }
      );
      if (this.entities.length != length) {
        this.$scope.$evalAsync(function () {
          self.sort();
        });
      }
    },

    /* @websocket */
    addedUnConfirmedTransactions: function (transactions) {
      var self = this;
      var iterator = this.transactionIterator(transactions);
      this.$scope.$evalAsync(function () {
        self.processGetData(iterator, true);
      });
    },

    /* @websocket */
    addedConfirmedTransactions: function (transactions) {
      var self = this;
      var iterator = this.transactionIterator(transactions);
      this.$scope.$evalAsync(function () {
        self.processGetData(iterator, true);
      });
    },

    /* @websocket */
    blockPopped: function (block) {
      var self = this;
      this.$scope.$evalAsync(function () {
        var result = [], entity, changed = false;
        for (var i=0; i<self.entities.length; i++) {
          entity = self.entities[i];
          if (entity.height <= block.height) {
            entity.confirmations = block.height - entity.height;
            result.push(entity);
            changed = true;
          }
          else {
            delete self.keys[self.uniqueKey(entity)];
          }
        }
        self.entities = result;
        if (changed) {
          self.sort();
        }
      });
    },

    /* @websocket */
    blockPushed: function (block) {
      var self = this;
      this.$scope.$evalAsync(function () {
        for (var i=0; i<self.entities.length; i++) {
          self.entities[i].confirmations = block.height - self.entities[i].height;
        }
      });
    }
  };

  return IndexedEntityProvider;
});
})();


text:
require.ensure([], function(require) {
require("./50.async.js");
require("./100.async.js");
require("./200.async.js");
require("./400.async.js");
});
module.exports = 401;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var fs = require('fs');
var fsE = require('fs.extra');
var jsSha = require('jssha');
var OBJPATH = 'objects';
var BRANCHPATH = 'branches';
var MASTERPATH = BRANCHPATH + '/master';
var  MASTERINDEX = MASTERPATH + '/index.afs';
function Repo(path){
    this.path = path;
    this.isRepo = false;
    this.init = function(callback)
    {
        var count = 0;
        var cb = function(err){
            if(err)
                console.log(err);
            count++;
            if(count === 5)//5 is the number of times this fuction is used
            {
                callback();
            }
        };
        this.isRepo = true;
        fsE.mkdirp(path, cb);
        //fs.mkdir(path, cb);
        fsE.mkdirp(path + '/' + BRANCHPATH, cb);
        //fs.mkdir(path + '/' + BRANCHPATH, cb);
        fsE.mkdirp(path + '/' + MASTERPATH, function(err)
        {
            cb(err);
            if(!err)
                fs.writeFile(path + '/' + MASTERINDEX, '', cb);
        });
        //fs.mkdir(path + '/' + MASTERPATH, cb);
        fsE.mkdirp(path + '/' + OBJPATH, cb);
        //fs.mkdir(path + '/' + OBJPATH, cb);

        //now create master index

    };
    //constructor
    fs.exists(path + '/' + MASTERINDEX, function(exists){
        if(exists)
        {
            this.isRepo = true;
        }
    });
    //load the specified branch of the repo if the branch is / master is assumed
    //callback has 2 parameters the first returns the indices of the data,
    //the second returns the data as a javascript object callback may be called
    //multiple times and not nessesarily in order
    this.loadBranch = function (branch ,callback)
    {
        if(branch === '/')
        {
            branch = 'master';
        }
        fs.readFile(path + '/' + BRANCHPATH + '/' + branch +
                '/index.afs', 'utf8', 'String',function(err, data){
            if(err)
            {
                console.log('loading branch failed');
                return;
            }

            var indices = JSON.parse(data);

            indices.forEach(function(entry){
                var folder = entry.substr(0,3);
                var filename = entry.substr(3);
                fs.readFile(path + '/' + OBJPATH + '/' + folder + '/' + filename,
                function(err2, d2){
                   d2 = JSON.parse(d2);
                   d2.index = entry;
                   callback(indices, d2);
                });
            });
        });
    }
    this.saveBranch = function (branch, data, callback)
    {
        var indices = new Array();
        var count = 0;
        console.log('branch: ' + branch + ' data: ' + data);
        data.forEach(function(entry){
            var hash =(new jsSha(JSON.stringify(entry),"TEXT")).getHash("SHA-1", "HEX");
            //console.log('hash is: ' + hash);
            indices.push(hash);
            var folder = hash.substr(0,3);
            var filename = hash.substr(3);
            fs.exists(path + '/' + OBJPATH + '/' + folder + '/' + filename, function(exists){
                if(exists)
                {
                    //console.log('sucessfully doing nothing');
                    count++;
                        if(count == (data.length -1))
                        {
                            //we are done put all hashes in the index file
                            fs.writeFile(path + '/' + BRANCHPATH + '/' + branch + '/index.afs', JSON.stringify(indices), function(e2){
                                if(e2)
                                    console.log('saving indexfile failed with ' + e2);
                                callback();
                            });

                        }
                }
                else
                {
                    fsE.mkdirp(path + '/' + OBJPATH + '/' + folder, function(err, made){
                    //think about not overwriting the data files each time
                    if(err)
                        console.log(err);
                    fs.writeFile(path + '/' + OBJPATH + '/' + folder + '/' + filename, JSON.stringify(entry), function(err){
                        if(err)
                            console.log(err);
                        count++;
                        if(count == (data.length -1))
                        {
                            //we are done put all hashes in the index file
                            fs.writeFile(path + '/' + BRANCHPATH + '/' + branch + '/index.afs', JSON.stringify(indices), function(e2){
                                if(e2)
                                    console.log('saving indexfile failed with ' + e2);
                                callback();
                            });

                        }
                    });
                });
                }
            });

        });
    }
    this.cloneBranch = function(oldBranch, newBranch, callback){
        fsE.copyRecursive(path + '/' + BRANCHPATH + '/' + oldBranch,
        path + '/' + BRANCHPATH + '/' + newBranch, function(err){
            if(err)
                console.log(err);
            callback();
        });
    }
}

// Functions which will be available to external callers
//exports.saveBranch = saveBranch;
//exports.getBranch = getBranch;
exports.Repo = Repo;


text:
module Validator
  require "ipaddress"

  class IpAddress
    def initialize(value)
      @value = value
    end

    # check if ip has prefix
    def has_prefix?
      @value =~ /\//
    end

    # IPv4 addresses which are only 32 bits long
    def valid_ipv4_prefix?
      prefix = get_prefix
      (prefix >= 1 and prefix <= 32)
    end

    # IPv6 addresses are 128 bits long
    def valid_ipv6_prefix?
      prefix = get_prefix
      (prefix >= 1 and prefix <= 128)
    end

    # IPv4 determination by . (dot)
    def is_ipv4?
      @value =~ /\./
    end

    def valid_prefix?
      if is_ipv4?
        valid_ipv4_prefix?
      else
        valid_ipv6_prefix?
      end
    end

    def valid_ipv4?
      IPAddress(@value).ipv4? rescue false
    end

    def valid_ipv6?
      IPAddress(@value).ipv6? rescue false
    end

    def valid?
      valid_ipv4? || valid_ipv6?
    end

  private
     def get_prefix
       @value.split("/").last.to_i
     end
  end
end


text:
package sbt.internal.util

import scala.collection.JavaConverters._
private[util] class WrappedMap[K, V](val jmap: java.util.Map[K, V]) extends Map[K, V] {
  def removed(key: K): scala.collection.immutable.Map[K, V] = jmap.asScala.toMap.removed(key)
  def updated[V1 >: V](key: K, value: V1): scala.collection.immutable.Map[K, V1] =
    jmap.asScala.toMap.updated(key, value)

  def get(key: K): Option[V] = Option(jmap.get(key))
  def iterator: Iterator[(K, V)] = jmap.asScala.iterator
}


text:
<!doctype html>

    <title>Find the Target!</title>

    	<link type="text/css" rel="stylesheet" href="js/jspsych/css/jspsych.css"></link>


text:
pjsip_samples
=============

Playground for pjsip


text:
package io.shardingsphere.shardingjdbc.jdbc.adapter.invocation;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.lang.reflect.Method;

/**
 * Invocation that reflected call for JDBC method.
 *
 * @author gaohongtao
 */
@RequiredArgsConstructor
public class JdbcMethodInvocation {

    @Getter
    private final Method method;

    @Getter
    private final Object[] arguments;

    /**
     * Invoke JDBC method.
     *
     * @param target target object
     */
    @SneakyThrows
    public void invoke(final Object target) {
        method.invoke(target, arguments);
    }
}


text:
require 'test_helper'

class Group::UpdateTest < ActiveSupport::TestCase
  def setup
    @update_group = Group::Update.new()
  end
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<title>Ruben Carrasco Esparza | Perfil</title>
	<meta name="description" content="Perfil y experiencia laboral de Rubén David Carrasco Esparza." />
	<meta name="keywords" content="perfil, ruben carrasco, ruben esparza, historial, experiencia" />
	<link rel="canonical" href="https://www.rubencarrascoesparza.com" />

Informáticos

Geográficos

Servicios Informáticos

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sagittis justo eget ante sagittis tristique. Curabitur vestibulum mauris tincidunt, pretium nulla a, facilisis erat. Phasellus ac nisi vitae nisl lacinia tristique. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis varius nunc diam. Sed eleifend nulla vitae nisi mollis vestibulum. Aliquam tellus mauris, pellentesque euismod felis sed, porta tempor dui. Vivamus at lacinia neque, ut convallis mi. Phasellus vel odio sed ex lobortis elementum. Morbi faucibus nisi justo, vel elementum leo posuere vitae. Nulla facilisi. Sed sit amet nulla vitae est auctor eleifend non at arcu. Maecenas condimentum massa sit amet ex sodales ultrices.

Integer eu gravida ante. Mauris sed neque metus. Suspendisse aliquet ultricies volutpat. Vivamus luctus nec nulla dignissim ullamcorper. Sed sit amet massa aliquam, condimentum eros vitae, efficitur odio. Ut condimentum pellentesque enim non auctor. Aliquam erat volutpat. Phasellus sollicitudin est at turpis malesuada laoreet. Sed faucibus augue a pretium commodo. Phasellus condimentum tellus orci, nec cursus nisi blandit ac. Etiam at turpis pulvinar, dignissim turpis et, condimentum massa. Sed lacinia sem pharetra, facilisis dolor quis, ultricies erat. Sed malesuada sollicitudin libero, ut bibendum leo semper sed. Sed ullamcorper mi nec tellus dictum, eget aliquam purus hendrerit.

Servicios Geográficos

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sagittis justo eget ante sagittis tristique. Curabitur vestibulum mauris tincidunt, pretium nulla a, facilisis erat. Phasellus ac nisi vitae nisl lacinia tristique. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis varius nunc diam. Sed eleifend nulla vitae nisi mollis vestibulum. Aliquam tellus mauris, pellentesque euismod felis sed, porta tempor dui. Vivamus at lacinia neque, ut convallis mi. Phasellus vel odio sed ex lobortis elementum. Morbi faucibus nisi justo, vel elementum leo posuere vitae. Nulla facilisi. Sed sit amet nulla vitae est auctor eleifend non at arcu. Maecenas condimentum massa sit amet ex sodales ultrices.

Integer eu gravida ante. Mauris sed neque metus. Suspendisse aliquet ultricies volutpat. Vivamus luctus nec nulla dignissim ullamcorper. Sed sit amet massa aliquam, condimentum eros vitae, efficitur odio. Ut condimentum pellentesque enim non auctor. Aliquam erat volutpat. Phasellus sollicitudin est at turpis malesuada laoreet. Sed faucibus augue a pretium commodo. Phasellus condimentum tellus orci, nec cursus nisi blandit ac. Etiam at turpis pulvinar, dignissim turpis et, condimentum massa. Sed lacinia sem pharetra, facilisis dolor quis, ultricies erat. Sed malesuada sollicitudin libero, ut bibendum leo semper sed. Sed ullamcorper mi nec tellus dictum, eget aliquam purus hendrerit.


text:
namespace RMIT.Counter.Libraries.Sushi.Core
{
    public class SushiCustomException : System.Exception
    {
        public SushiCustomException(string message, int number) : base(message)
        {
            HResult = number;
        }
    }
}


text:
package data

// ItemAttributes response group
type ItemAttributes struct {
	Authors         []string `xml:"Author"`
	Binding         string
	Brand           string
	EAN             string
	Edition         string
	Features        []string `xml:"Features"`
	ISBN            string
	Label           string
	Languages       Languages
	ListPrice       Price
	Manufacturer    string
	ProductGroup    string
	PublicationDate string
	Publisher       string
	ReleaseDate     string
	Studio          string
	Title           string
	UPC             string
}

// Languages for the item
type Languages struct {
	LanguageList []Language `xml:"Language"`
}

// Languages returns item languages as an easy to work with map
func (l Languages) Languages() []string {
	var langs []string
	unique := map[string]bool{}

	for _, lang := range l.LanguageList {
		if exists, _ := unique[lang.Name]; !exists {
			langs = append(langs, lang.Name)
			unique[lang.Name] = true
		}

	}

	return langs
}

// Language of an item
type Language struct {
	Name string
	Type string
}


text:
package defaultbinder

import (
	"context"
	"errors"
	"testing"

	"github.com/google/go-cmp/cmp"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/kubernetes/fake"
	clienttesting "k8s.io/client-go/testing"
	frameworkruntime "k8s.io/kubernetes/pkg/scheduler/framework/runtime"
)

func TestDefaultBinder(t *testing.T) {
	testPod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "ns"},
	}
	testNode := "foohost.kubernetes.mydomain.com"
	tests := []struct {
		name        string
		injectErr   error
		wantBinding *v1.Binding
	}{
		{
			name: "successful",
			wantBinding: &v1.Binding{
				ObjectMeta: metav1.ObjectMeta{Namespace: "ns", Name: "foo"},
				Target:     v1.ObjectReference{Kind: "Node", Name: testNode},
			},
		}, {
			name:      "binding error",
			injectErr: errors.New("binding error"),
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var gotBinding *v1.Binding
			client := fake.NewSimpleClientset(testPod)
			client.PrependReactor("create", "pods", func(action clienttesting.Action) (bool, runtime.Object, error) {
				if action.GetSubresource() != "binding" {
					return false, nil, nil
				}
				if tt.injectErr != nil {
					return true, nil, tt.injectErr
				}
				gotBinding = action.(clienttesting.CreateAction).GetObject().(*v1.Binding)
				return true, gotBinding, nil
			})

			fh, err := frameworkruntime.NewFramework(nil, nil, nil, frameworkruntime.WithClientSet(client))
			if err != nil {
				t.Fatal(err)
			}
			binder := &DefaultBinder{handle: fh}
			status := binder.Bind(context.Background(), nil, testPod, "foohost.kubernetes.mydomain.com")
			if got := status.AsError(); (tt.injectErr != nil) != (got != nil) {
				t.Errorf("got error %q, want %q", got, tt.injectErr)
			}
			if diff := cmp.Diff(tt.wantBinding, gotBinding); diff != "" {
				t.Errorf("got different binding (-want, +got): %s", diff)
			}
		})
	}
}


text:
/**
 * Command pattern implementation for AngularJS
 * @version v0.9.0 - 2015-03-15
 * @link https://github.com/yukatan/commangular
 * @author Jesús Barquín Cheda <yukatan@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
"use strict";

(function(window, angular, undefined) {

	var commangular = window.commangular || (window.commangular = {});
	var commands = {};
	var commandNameString = "";
	var eventNameString = "";
	var aspects = [];
	var eventAspects = [];
	var descriptors = {};
	var eventInterceptors= {};
	var interceptorExtractor = /\/(.*)\//;
	var aspectExtractor = /@([^(]*)\((.*)\)/;
	var debugEnabled = false;

	function escapeRegExp(str) {
  		return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
	}

	commangular.create = function(commandName, commandFunction, commandConfig) {

		commands[commandName] = {
			commandFunction: commandFunction,
			config: commandConfig,
			interceptors:{},
			commandName:commandName
		};
		commandNameString = commandNameString.concat("%" + commandName + "%{" + commandName + "}\n");
	}
	commangular.command = commangular.create;

	commangular.aspect = function(aspectDescriptor,aspectFunction,order) {

		var result = aspectExtractor.exec(aspectDescriptor);
		var poincut = result[1];
		var matcherString = interceptorExtractor.exec(result[2])[1];
		var matcher = new RegExp("^%" + matcherString + "%\{(.*)\}$","mg");
		var aspectOrder = order || (order = 0);
		if(!/(\bBefore\b|\bAfterExecution\b|\bAfter\b|\bAfterThrowing\b|\bAround\b)/.test(poincut))
			throw new Error('aspect descriptor ' + aspectDescriptor + ' contains errors');
		aspects.push({poincut:poincut,
			matcher:matcher,
			aspectFunction:aspectFunction,
			order:aspectOrder,
			descriptor:aspectDescriptor});
	}

	commangular.eventAspect = function(aspectDescriptor,aspectFunction,order) {

		var result = aspectExtractor.exec(aspectDescriptor);
		var poincut = result[1];
		var matcherString = interceptorExtractor.exec(result[2])[1];
		var matcher = new RegExp("^%" + matcherString + "%\{(.*)\}$","mg");
		var aspectOrder = order || (order = 0);
		if(!/(\bBefore\b|\bAfter\b|\bAfterThrowing\b)/.test(poincut))
			throw new Error('aspect descriptor ' + aspectDescriptor + ' contains errors');
		eventAspects.push({poincut:poincut,
			matcher:matcher,
			aspectFunction:aspectFunction,
			order:aspectOrder,
			descriptor:aspectDescriptor});
	}

	commangular.resolver = function (commandName,resolverFunction) {

		var aspectResolverFunction = ['lastResult','processor','$injector',function(lastResult,processor,$injector) {
			return {
				execute : function() {
					var result = $injector.invoke(resolverFunction,this,{result:lastResult});
					processor.setData('lastResult',result);
					if(commands[commandName] &&
						commands[commandName].config &&
						commands[commandName].config.resultKey)
							processor.setData(commands[commandName].config.resultKey,result);
					return result;
				}
			}
		}];
		var aspectDescriptor = "@AfterExecution(/" + escapeRegExp(commandName) + "/)";
		commangular.aspect(aspectDescriptor,aspectResolverFunction,-100);
	}

	commangular.reset = function() {

		aspects = eventAspects = [];
		commands = eventInterceptors = {};
		commandNameString = eventNameString = "";
	}

	commangular.debug = function(enableDebug){

		debugEnabled = enableDebug;
	}

	commangular.build = function(){

		(function processInterceptors(collection,stringList,targets) {

				angular.forEach(collection,function(aspect){
					var result;
					while((result = aspect.matcher.exec(stringList)) != null) {

						if(!targets[result[1]].interceptors[aspect.poincut])
							targets[result[1]].interceptors[aspect.poincut] = [];
						targets[result[1]].interceptors[aspect.poincut]
								.push({func:aspect.aspectFunction,order:aspect.order});
					}
				});
				return processInterceptors;
			}(aspects,commandNameString,commands)(eventAspects,eventNameString,eventInterceptors));

	}

	//----------------------------------------------------------------------------------------------------------------------

	function CommandDescriptor(ctype,command) {

		this.ctype = ctype;
		this.command = command;
		this.descriptors = [];
	}

	CommandDescriptor.prototype.asSequence = function() {

		this.ctype = 'S';
		return this;
	};

	CommandDescriptor.prototype.asParallel = function() {

		this.ctype = 'P';
		return this;
	};

	CommandDescriptor.prototype.asFlow = function() {

		this.ctype = 'F';
		return this;
	};

	CommandDescriptor.prototype.add =  function(command) {

		this.descriptors.push((angular.isString(command)) ? new CommandDescriptor('E',commands[command]):command);
		return this;
	};
	CommandDescriptor.prototype.link = function(expresion, services) {

		this.descriptors.push({expresion:expresion,services:services});
		return this;
	};
	CommandDescriptor.prototype.to = function(command) {

		this.descriptors[this.descriptors.length -1].commandDescriptor = (angular.isString(command) ?
			new CommandDescriptor('E',commands[command]):command);
		return this;
	};

	//----------------------------------------------------------------------------------------------------------------------
	function CommandContext(data,$q,$injector,$parse) {

		this.contextData = data || {};
		this.contextData.commandModel = {};
		this.currentDeferred;
		this.currentCommandInstance;
		this.canceled = false;

		this.processDescriptor = function(descriptor) {

			switch (descriptor.ctype) {
				case 'S':
					return this.processSequence(descriptor);
				case 'P':
					return this.processParallel(descriptor);
				case 'E':
					return this.processCommand(descriptor);
				case 'F':
					return this.processFlow(descriptor);
			}
		}

		this.processSequence = function(descriptor) {

			var defer = $q.defer();
			var index = 0;
			var self = this;
			(function sequenceChain(){
				self.processDescriptor(descriptor.descriptors[index]).then(function(){
					if(++index === descriptor.descriptors.length){
						defer.resolve();
						return;
					}
					sequenceChain();
				},function(error){defer.reject(error)});
			}());
			return defer.promise;
		}

		this.processParallel = function(descriptor) {

			var self = this;
			var defer = $q.defer();
			var index = 0;
			angular.forEach(descriptor.descriptors,function(desc){
				self.processDescriptor(desc).then(function(){
					if(++index === descriptor.descriptors.length){
						defer.resolve();
						return;
					}
				},function(error){defer.reject(error)});
			});
			return defer.promise;

		}

		this.processFlow = function(descriptor) {

			var self = this;
			var defer = $q.defer();
			var index = 0;
			(function flowChain() {
				var locals = {};
				var desc = descriptor.descriptors[index];
				if(desc.services) {

					angular.forEach(desc.services.split(','), function(service, key){
						locals[service] = $injector.get(service);
					});
				}
				var result = $parse(desc.expresion)(self.contextData,locals);
				if(typeof result !== 'boolean')
					throw new Error('Result from expresion :' + descriptor.expresion + ' is not boolean');
				if(result){
					self.processDescriptor(desc.commandDescriptor).then(function(){
						if(++index === descriptor.descriptors.length){
							defer.resolve();
							return;
						}
						flowChain();
					},function(error){defer.reject(error)});
				}
				else{
					if(++index === descriptor.descriptors.length){
							defer.resolve();
							return;
					}
					flowChain();
				}
			}());
			return defer.promise;
		}

		this.processCommand = function(descriptor) {

			var self = this;
			var result;
			var deferExecution = $q.defer();
			deferExecution.resolve();
			return deferExecution.promise
				.then(function () {
					return self.intercept('Before',descriptor.command.interceptors);
				})
				.then(function() {
					var deferred = $q.defer();
					try{
						if(descriptor.command.interceptors['Around'])
							result = self.intercept('Around',descriptor.command.interceptors,descriptor.command.commandFunction);
						else {
							var command = self.instantiate(descriptor.command.commandFunction,true);
							result = self.invoke(command.execute, command);
						}
						self.processResults(result,descriptor.command.config).then(function(){
							deferred.resolve();
						},function(error){
							deferred.reject(error);
						});
					}catch(error){
						deferred.reject(error);
					}
					return deferred.promise;
				})
				.then(function(){
					return self.intercept('AfterExecution',descriptor.command.interceptors);
				})
				.then(function(){
					result = self.exeOnResult(self.contextData.lastResult);
					return self.processResults(result,descriptor.command.config);
				})
				.then(function(){
					return self.intercept('After',descriptor.command.interceptors);
				},function(error) {
					var deferred = $q.defer();
					if(self.canceled){
						deferred.reject(error);
						return deferred.promise;
					}
					self.exeOnError(error);
					self.getContextData().lastError = error;
					self.intercept('AfterThrowing',descriptor.command.interceptors).then(function(){
						deferred.reject(error)
					},function(){deferred.reject(error)});
					return deferred.promise;
				});
		}

		this.intercept = function(poincut,interceptors,command) {

			var self = this;
			var deferred = $q.defer();
			if(!interceptors[poincut]){
				deferred.resolve();
				return deferred.promise;
			}
			interceptors[poincut].sort(function(a,b){
				return b.order - a.order;
			})
			switch(poincut) {
				case 'Around' : {
					var processor = new AroundProcessor(command,null,self,deferred,$q);
					angular.forEach(interceptors[poincut],function(value){
						processor = new AroundProcessor(value.func,processor,self,deferred,$q);
					});
					$q.when(processor.invoke()).then(function(result){
						deferred.resolve(result);
					},function(error){
						deferred.reject(error);});
					break;
				}
				default : {
					var processor = this.contextData.processor = new InterceptorProcessor(self,deferred);
					interceptors[poincut].reverse();
					var x = 0;
					(function invocationChain(){
						try{
							if(x === interceptors[poincut].length || self.canceled){
								deferred.resolve();
								return;
							}
							var interceptor = self.instantiate(interceptors[poincut][x++].func,false);
							$q.when(self.invoke(interceptor.execute,interceptor)).then(function(){
								invocationChain();
							},function(error){});
						}catch(error){deferred.reject(error)};
					}());
					break;
				}
			}
			return deferred.promise;
		}

		this.instantiate = function(funct,isCommand) {

			var instance = $injector.instantiate(funct,this.contextData);
			if(isCommand) this.currentCommandInstance = instance;
			return instance;
		}

		this.exeOnResult = function(result) {

			if(this.currentCommandInstance && this.currentCommandInstance.hasOwnProperty('onResult'))
				return this.currentCommandInstance.onResult(result);
		}

		this.exeOnError = function(error) {

			if(this.currentCommandInstance && this.currentCommandInstance.hasOwnProperty('onError'))
				this.currentCommandInstance.onError(error);
		}

		this.processResults = function(result,config) {

			var self = this;
			var defer = $q.defer();
			if (!result) {
				defer.resolve();
				return defer.promise;
			}
			var promise = $q.when(result).then(function(data) {

				self.contextData.lastResult = data;
				if (config && config.resultKey) {
					self.contextData[config.resultKey] = data;
				}
				defer.resolve();
			},function(error){defer.reject(error)});
			return defer.promise;
		}

		this.invoke = function(func, self) {

			return $injector.invoke(func,self,this.contextData);
		}

		this.getContextData = function(resultKey) {

			return this.contextData;
		}
	}

	//----------------------------------------------------------------------------------------------------------------------
	function InterceptorProcessor(context,deferred) {

		this.deferred = deferred;
		this.context = context;

	}
	InterceptorProcessor.prototype.cancel = function(reason) {

		this.context.canceled = true;
		this.deferred.reject(reason);
	}
	InterceptorProcessor.prototype.setData = function(key,value) {

		this.context.contextData[key] = value;
	}
	InterceptorProcessor.prototype.getData = function(key) {

		return this.context.contextData[key];
	}
	//----------------------------------------------------------------------------------------------------------------------
	function AroundProcessor(executed,next,context,deferred,$q) {

		InterceptorProcessor.apply(this,[context,deferred]);
		this.executed = executed;
		this.next = next;
		this.$q = $q;
	}
	AroundProcessor.prototype = new InterceptorProcessor();
	AroundProcessor.prototype.constructor = AroundProcessor;

	AroundProcessor.prototype.invoke = function() {

		this.context.contextData.processor = this.next;
		var instance = this.context.instantiate(this.executed,this.next == null);
		return this.$q.when(this.context.invoke(instance.execute,instance))
	}

	//----------------------------------------------------------------------------------------------------------------------
	angular.module('commangular', [])
		.provider('$commangular', function() {

			return {
				$get: ['commandExecutor',function(commandExecutor) {

					return {
						dispatch: function(eventName, data) {

							return commandExecutor.execute(eventName, data);
						}
					}
				}],

				mapTo: function(eventName) {

					var interceptorChain = eventInterceptors[eventName] || (eventInterceptors[eventName] = {});
					if(!interceptorChain.interceptors)
						interceptorChain.interceptors = {};
					eventNameString = eventNameString.concat("%" + eventName + "%{" + eventName + "}\n");
					descriptors[eventName] = new CommandDescriptor();
					return descriptors[eventName];
				},

				asSequence : function() {

					return new CommandDescriptor('S');
				},
				asParallel : function() {

					return new CommandDescriptor('P');
				},
				asFlow : function() {

					return new CommandDescriptor('F');
				},

				findCommand: function(eventName) {

					return descriptors[eventName];
				}
			};
		});
	//-----------------------------------------------------------------------------------------------------------------
	angular.module('commangular')
		.service('commandExecutor',['$q','$injector','$parse','$exceptionHandler',
			function($q,$injector,$parse,$exceptionHandler) {

				return {

					execute: function(eventName, data) {
						var self = this;
						var defer = $q.defer();
						var context = self.createContext(data);
						var descriptor = descriptors[eventName];
						var interceptors = eventInterceptors[eventName].interceptors;
						defer.resolve();
						return defer.promise.then(function() {

							return context.intercept('Before',interceptors);
						}).then(function() {

							return context.processDescriptor(descriptor);
						}).then(function(){

							return context.intercept('After',interceptors);
						}).then(function() {

							return self.returnData(context);
						},function(error){
							if(debugEnabled) $exceptionHandler(error);
							var def = $q.defer();
							context.intercept('AfterThrowing',interceptors).then(function(){
								def.reject(error);
							},function(){defer.reject(error)});
							return def.promise;
						});

					},
					createContext: function(data) {

						return new CommandContext(data,$q,$injector,$parse);
					},
					returnData : function(context) {

						return context.contextData;
					}
				};
			}
		]);
	//------------------------------------------------------------------------------------------------------------------
	angular.module('commangular')
		.run(commangular.build);
	//------------------------------------------------------------------------------------------------------------------
	angular.module('commangular')
		.config(['$provide',function($provide) {

			$provide.decorator('$rootScope',['$injector','$delegate',function($injector,$delegate){

				$delegate.dispatch = function(eventName,data) {
					return $injector.get('commandExecutor').execute(eventName,data);
				}
				return $delegate;
			}]);
		}]);
})(window, window.angular);


text:
// cubic polynomial computation

#include "StVKReducedInternalForces.h"
#include "StVKReducedInternalForcesWX.h"
#include "StVKCubeABCD.h"
#include "matrixIO.h"
#include "StVKElementABCDLoader.h"
#include "largeModalDeformationFactory.h"

void MyFrame::OnLoadCubicPolynomials(wxCommandEvent& event)
{
  wxFileDialog *dlg = new wxFileDialog(this, _T("Load cubic polynomials"),
    uiState.currentWorkingDirectory, _T(""), _T("Cubic polynomials files(*.cub)|*.cub|All files(*.*)|*.*"),
    wxFD_OPEN /*| wxHIDE_READONLY*/, wxDefaultPosition);

  if ( dlg->ShowModal() == wxID_OK )
  {
    wxString cubicPolynomialsFilename = dlg->GetPath();
    SaveCurrentWorkingDirectory(cubicPolynomialsFilename);
    if( !cubicPolynomialsFilename.empty() )
    {
      StVKReducedInternalForces * newCubicPolynomials = NULL;

      SetCursor(*wxHOURGLASS_CURSOR);
      const char * filename = cubicPolynomialsFilename.mb_str();
      newCubicPolynomials = new StVKReducedInternalForces((char*) filename);
      int code = 0; // should also catch any errors
      SetCursor(*wxSTANDARD_CURSOR);

      if (code != 0)
      {
        this->errMsg( _T("Loading error"),
        _T("Unable to load cubic polynomials from ") + cubicPolynomialsFilename );
        dlg->Destroy();
        return;
      }

      // success
      delete(precomputationState.cubicPolynomials);
      precomputationState.cubicPolynomials = newCubicPolynomials;

      precomputationState.cubicPolynomialsAvailable = true;

      UpdateMenus();

      Refresh();
    }
  }

  dlg->Destroy();
}

void MyFrame::OnSaveCubicPolynomials(wxCommandEvent& event)
{
   wxFileDialog *dlg = new wxFileDialog(this, _T("Save cubic polynomials"),
     uiState.currentWorkingDirectory, _T(""), _T("Cubic Polynomials Files(*.cub)|*.cub|All files(*.*)|*.*"),
	wxFD_SAVE /*| wxHIDE_READONLY*/, wxDefaultPosition);
   if ( dlg->ShowModal() == wxID_OK )
   {
     wxString cubicPolynomialsFilename( dlg->GetPath() );
     SaveCurrentWorkingDirectory(cubicPolynomialsFilename);
     if( !cubicPolynomialsFilename.empty() )
     {
       const char * filename = cubicPolynomialsFilename.mb_str();
       int code = precomputationState.cubicPolynomials->Save((char*)filename);

       if (code != 0)
       {
         this->errMsg( _T("Saving error"),
           _T("Unable to save cubic polynomials to ") + cubicPolynomialsFilename );
         dlg->Destroy();
         return;
       }
     }
   }

   dlg->Destroy();
}

void MyFrame::OnComputeCubicPolynomials(wxCommandEvent& event)
{
  if (!precomputationState.nonLinearModesAvailable)
  {
    this->errMsg( _T("Cannot compute cubic polynomials"),
      _T("Nonlinear modes are not available.\n"
      ) );
    return;
  }

  wxDialog * dlg = new wxDialog(this, -1, _T("Select the number of threads"),
    wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("dialogBox") );

  wxBoxSizer * dlgSizer = new wxBoxSizer(wxVERTICAL);
  wxStaticText * numComputationThreadsText = new wxStaticText(dlg, -1,
       _T("Number of computation threads: "), wxDefaultPosition, wxDefaultSize,
       wxALIGN_CENTER, _T( "staticText"));

  char numComputationThreadsC[96];
  sprintf(numComputationThreadsC, "%d", uiState.numComputationThreads);
  wxTextCtrl * numComputationThreadsControl = new wxTextCtrl(dlg, -1,
      wxString(numComputationThreadsC, wxConvUTF8), wxDefaultPosition, wxSize(100,-1));

  wxBoxSizer * numComputationThreadsSizer = new wxBoxSizer(wxHORIZONTAL);
  numComputationThreadsSizer->Add(numComputationThreadsText, 0, wxCENTER);
  numComputationThreadsSizer->Add(numComputationThreadsControl, 0, wxCENTER);
  dlgSizer->Add(numComputationThreadsSizer, 0, wxALL | wxCENTER, 8);

  dlgSizer->Add(dlg->CreateButtonSizer(wxOK | wxCANCEL), 0, wxLEFT | wxRIGHT | wxBOTTOM | wxCENTER, 8);

  dlg->SetSizer(dlgSizer);
  dlgSizer->SetSizeHints(dlg);

  if (dlg->ShowModal() != wxID_OK)
  {
    delete(dlg);
    return;
  }

  wxString valueString = numComputationThreadsControl->GetValue();

  delete(dlg);

  long value;
  bool goodInput = valueString.ToLong(&value);

  if (goodInput)
  {
    if ((value <= 0) || (value > 65536))
      goodInput = false;
  }

  if (goodInput)
  {
    uiState.numComputationThreads = value;

    StVKReducedInternalForces * newCubicPolynomials = NULL;

    SetCursor(*wxHOURGLASS_CURSOR);
    int code;
    CubicPolynomialsWorker(&code, &newCubicPolynomials);
    SetCursor(*wxSTANDARD_CURSOR);

    if (code != 0)
    {
      this->errMsg( _T("Cubic polynomials computation failed"),
             _T("Cubic polynomials computation failed.") );
      free(newCubicPolynomials);
      return;
    }
    else
    {
      delete(precomputationState.cubicPolynomials);
      precomputationState.cubicPolynomials = newCubicPolynomials;
      precomputationState.cubicPolynomialsAvailable = true;

      UpdateMenus();

      Refresh();
    }
  }
}

void * MyFrame::CubicPolynomialsWorker(int * code, StVKReducedInternalForces ** newCubicPolynomial)
{
  // compute cubic polynomials
  StVKElementABCD * precomputedABCDIntegrals = StVKElementABCDLoader::load(precomputationState.simulationMesh);

  if (uiState.numComputationThreads == 1)
  {
    *newCubicPolynomial = new StVKReducedInternalForces(
      precomputationState.rNonLin,
      precomputationState.nonLinearModalMatrix->GetMatrix(),
      precomputationState.simulationMesh, precomputedABCDIntegrals);
  }
  else
  {
    *newCubicPolynomial = new StVKReducedInternalForcesWX(
      precomputationState.rNonLin,
      precomputationState.nonLinearModalMatrix->GetMatrix(),
      precomputationState.simulationMesh, precomputedABCDIntegrals, false, uiState.numComputationThreads);
  }

  delete(precomputedABCDIntegrals);

  computationRunning = -1;

  *code = 0;
  return NULL;
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <stdbool.h>
#include <stdio.h>

#include <sys/param.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <atf-c.h>
/* Helper functions*/

/*
 * Create two devd events.  The easiest way I know of, that requires no special
 * hardware, is to create md(4) devices.
 */
static void
create_two_events(void)
{
	FILE *create_stdout;
	FILE *destroy_stdout;
	char mdname[80];
	char destroy_cmd[80];
	char *error;

	create_stdout = popen("mdconfig -a -s 64 -t swap", "r");
	ATF_REQUIRE(create_stdout != NULL);
	error = fgets(mdname, sizeof(mdname), create_stdout);
	ATF_REQUIRE(error != NULL);
	/* We only expect one line of output */
	ATF_REQUIRE_EQ(0, pclose(create_stdout));

	snprintf(destroy_cmd, nitems(destroy_cmd), "mdconfig -d -u %s", mdname);
	destroy_stdout = popen(destroy_cmd, "r");
	/* We expect no output */
	ATF_REQUIRE_EQ(0, pclose(destroy_stdout));
}

/*
 * Test Cases
 */

/*
 * Open a client connection to devd, create some events, and test that they can
 * be read _whole_ and _one_at_a_time_ from the socket
 */
ATF_TC_WITHOUT_HEAD(seqpacket);
ATF_TC_BODY(seqpacket, tc)
{
	int s;
	int error;
	struct sockaddr_un devd_addr;
	bool got_create_event = false;
	bool got_destroy_event = false;
	const char create_pat[] =
		"!system=DEVFS subsystem=CDEV type=CREATE cdev=md";
	const char destroy_pat[] =
		"!system=DEVFS subsystem=CDEV type=DESTROY cdev=md";

	memset(&devd_addr, 0, sizeof(devd_addr));
	devd_addr.sun_family = PF_LOCAL;
	strlcpy(devd_addr.sun_path, "/var/run/devd.seqpacket.pipe",
			sizeof(devd_addr.sun_path));

	s = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
	ATF_REQUIRE(s >= 0);
	error = connect(s, (struct sockaddr*)&devd_addr, SUN_LEN(&devd_addr));
	ATF_REQUIRE_EQ(0, error);

	create_two_events();

	/*
	 * Loop until both events are detected on _different_ reads
	 * There may be extra events due to unrelated system activity
	 * If we never get both events, then the test will timeout.
	 */
	while (!(got_create_event && got_destroy_event)) {
		int cmp;
		ssize_t len;
		char event[1024];

		len = recv(s, event, sizeof(event), MSG_WAITALL);
		ATF_REQUIRE(len != -1);
		/* NULL terminate the result */
		event[len] = '\0';
		printf("%s", event);
		cmp = strncmp(event, create_pat, sizeof(create_pat) - 1);
		if (cmp == 0)
			got_create_event = true;

		cmp = strncmp(event, destroy_pat, sizeof(destroy_pat) - 1);
		if (cmp == 0)
			got_destroy_event = true;
	}
}

/*
 * Open a client connection to devd using the stream socket, create some
 * events, and test that they can be read in any number of reads.
 */
ATF_TC_WITHOUT_HEAD(stream);
ATF_TC_BODY(stream, tc)
{
	int s;
	int error;
	struct sockaddr_un devd_addr;
	bool got_create_event = false;
	bool got_destroy_event = false;
	const char create_pat[] =
		"!system=DEVFS subsystem=CDEV type=CREATE cdev=md";
	const char destroy_pat[] =
		"!system=DEVFS subsystem=CDEV type=DESTROY cdev=md";
	ssize_t len = 0;

	memset(&devd_addr, 0, sizeof(devd_addr));
	devd_addr.sun_family = PF_LOCAL;
	strlcpy(devd_addr.sun_path, "/var/run/devd.pipe",
			sizeof(devd_addr.sun_path));

	s = socket(PF_LOCAL, SOCK_STREAM, 0);
	ATF_REQUIRE(s >= 0);
	error = connect(s, (struct sockaddr*)&devd_addr, SUN_LEN(&devd_addr));
	ATF_REQUIRE_EQ(0, error);

	create_two_events();

	/*
	 * Loop until both events are detected on _different_ reads
	 * There may be extra events due to unrelated system activity
	 * If we never get both events, then the test will timeout.
	 */
	while (!(got_create_event && got_destroy_event)) {
		char event[1024];
		ssize_t newlen;
		char *create_pos, *destroy_pos;

		newlen = read(s, &event[len], sizeof(event) - len);
		ATF_REQUIRE(newlen != -1);
		len += newlen;
		/* NULL terminate the result */
		event[newlen] = '\0';
		printf("%s", event);

		create_pos = strstr(event, create_pat);
		if (create_pos != NULL)
			got_create_event = true;

		destroy_pos = strstr(event, destroy_pat);
		if (destroy_pos != NULL)
			got_destroy_event = true;

	}
}

/*
 * Main.
 */

ATF_TP_ADD_TCS(tp)
{
	ATF_TP_ADD_TC(tp, seqpacket);
	ATF_TP_ADD_TC(tp, stream);

	return (atf_no_error());
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2011 JBoss Inc
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~         http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  -->
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
             xmlns:b="urn:import:org.gwtbootstrap3.client.ui">

    <ui:with field="i18n" type="org.uberfire.ext.widgets.core.client.resources.i18n.CoreConstants"/>
    <ui:with field="res" type="org.uberfire.ext.widgets.core.client.resources.WizardResources"/>

    <b:Container fluid="true">
        <b:Row>
            <b:Column size="MD_3">
                <b:NavPills ui:field="sideBar" stacked="true"/>
            </b:Column>
            <b:Column size="MD_9" ui:field="body" />
        </b:Row>
    </b:Container>

</ui:UiBinder>


text:
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
import Text.XML.HXT.Core

-- This example demonstrates a more complex XML parse,
-- involving multiple levels, attributes, inner lists,
-- and dealing with optional data.

-- Example data drawn from:
-- http://www.ibiblio.org/xml/books/bible/examples/05/5-1.xml
-- save as: simple2.xml

data Team = Team
  { teamName, division, league, city :: String,
    players :: [Player] }
  deriving (Show, Eq)

data Player = Player
  { firstName, lastName, position :: String,

    atBats, hits :: Maybe Int,
    era          :: Maybe Float }
  deriving (Show, Eq)

parseXML file = readDocument [ withValidate no
                             , withRemoveWS yes  -- throw away formating WS
                             ] file

atTag tag = deep (isElem >>> hasName tag)

-- Incremental development of the getTeams function:

-- First, list the teams.
-- Try it out in GHCi:
-- Main> runX (parseXML "simple2.xml" >>> getTeams1)

getTeams1 = atTag "LEAGUE" >>>
  proc l -> do
    leagName <- getAttrValue "NAME" -< l
    divi     <- atTag "DIVISION"    -< l
    diviName <- getAttrValue "NAME" -< divi
    team     <- atTag "TEAM"        -< divi
    teamName <- getAttrValue "NAME" -< team
    returnA -< (leagName, diviName, teamName)

-- getTeams2 also lists the players.
-- But there is a catch; now teams without players
-- are being left out.  (This behavior is familiar to
-- users of the List monad)

getTeams2 = atTag "LEAGUE" >>>
  proc l -> do
    leagName <- getAttrValue "NAME"       -< l
    divi     <- atTag "DIVISION"          -< l
    diviName <- getAttrValue "NAME"       -< divi
    team     <- atTag "TEAM"              -< divi
    teamName <- getAttrValue "NAME"       -< team
    player   <- atTag "PLAYER"            -< team
    fName    <- getAttrValue "GIVEN_NAME" -< player
    lName    <- getAttrValue "SURNAME"    -< player
    returnA -< (leagName, diviName, teamName, fName, lName)

-- What we really want is to capture the players in a list
-- at this level; and if there are no players then the
-- empty list will suffice.  listA is used for this purpose.

getPlayer1 = atTag "PLAYER" >>>
  proc p -> do
    fName    <- getAttrValue "GIVEN_NAME" -< p
    lName    <- getAttrValue "SURNAME"    -< p
    returnA -< (fName, lName)

getTeams3 = atTag "LEAGUE" >>>
  proc l -> do
    leagName <- getAttrValue "NAME" -< l
    divi     <- atTag "DIVISION"    -< l
    diviName <- getAttrValue "NAME" -< divi
    team     <- atTag "TEAM"        -< divi
    teamName <- getAttrValue "NAME" -< team
    players  <- listA getPlayer1    -< team
    returnA -< (leagName, diviName, teamName, players)

-- Try capturing some statistics about the players

significant = not . all (`elem` " \n\r\t")

-- Use our definition of "significant" strings to
-- capture the value; or else nothing.

getStat attr =
  (getAttrValue attr >>> isA significant >>> arr Just)
    `orElse` (constA Nothing)

getPlayer2 = atTag "PLAYER" >>>
  proc p -> do
    fName    <- getAttrValue "GIVEN_NAME" -< p
    lName    <- getAttrValue "SURNAME"    -< p
    position <- getAttrValue "POSITION"   -< p
    hits     <- getStat "HITS"            -< p
    atBats   <- getStat "AT_BATS"         -< p
    era      <- getStat "ERA"             -< p
    returnA -< Player
      { firstName = fName,
        lastName  = lName,
        position  = position,
        hits      = read `fmap` hits,
        atBats    = read `fmap` atBats,
        era       = read `fmap` era }

getTeams4 = atTag "LEAGUE" >>>
  proc l -> do
    leagName <- getAttrValue "NAME" -< l
    divi     <- atTag "DIVISION"    -< l
    diviName <- getAttrValue "NAME" -< divi
    team     <- atTag "TEAM"        -< divi
    teamName <- getAttrValue "NAME" -< team
    city     <- getAttrValue "CITY" -< team
    players  <- listA getPlayer2    -< team
    returnA -< Team
      { league   = leagName,
        division = diviName,
        teamName = teamName,
        city     = city,
        players  = players }

-- Our final choices

getPlayer = getPlayer2
getTeams  = getTeams4

main = do
  teams <- runX (parseXML "simple2.xml" >>> getTeams)
  print teams


text:
package com.googlecode.pngtastic.core.processing;

import com.googlecode.pngtastic.core.PngException;
import com.googlecode.pngtastic.core.PngFilterType;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Apply PNG filtering and defiltering
 *
 * @author rayvanderborght
 */
public interface PngFilterHandler {

	/**
	 * Apply the given filter type to the scanlines provided.
	 */
	public void applyFiltering(PngFilterType filterType, List<byte[]> scanlines, int sampleBitCount);

	/**
	 * Apply adaptive filtering as described in the png spec.
	 */
	public void applyAdaptiveFiltering(PngByteArrayOutputStream inflatedImageData, List<byte[]> scanlines, Map<PngFilterType, List<byte[]>> filteredScanLines, int sampleSize) throws IOException;

	/**
	 * Do filtering as described in the png spec:
	 * The scanline starts with a filter type byte, then continues with the image data.
	 */
	public void filter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException;

	/**
	 * Do the opposite of PNG filtering:
	 * @see #filter(byte[], byte[], int)
	 */
	public void deFilter(byte[] line, byte[] previousLine, int sampleBitCount) throws PngException;
}


text:
package com.googlesource.gerrit.plugins.deleteproject.fs;

import static com.google.common.truth.Truth.assertThat;
import static com.googlesource.gerrit.plugins.deleteproject.fs.DeleteTrashFolders.TrashFolderPredicate.match;

import org.junit.Test;

public class TrashFolderNameMatcherTest {

  @Test
  public void matchingNames() {
    matches("a.1234567890123.deleted");
    matches("aa.1234567890123.deleted");
    matches("a.b.c.1234567890123.deleted");

    matches("a.1234567890123.%deleted%.git");
    matches("aa.1234567890123.%deleted%.git");
    matches("a.b.c.1234567890123.%deleted%.git");

    matches("a.20181010120101.%deleted%.git");
    matches("aa.20181010120101.%deleted%.git");
    matches("a.b.c.20181010120101.%deleted%.git");
  }

  @Test
  public void nonMatchingNames() {
    doesNotMatch("a.git");
    doesNotMatch("a.1234567890123.git");
    doesNotMatch("a.1234567890123.deleted.git");

    // timestamp one digit shorter
    doesNotMatch("a.123456789012.deleted");

    // additional characters after the "deleted" suffix
    doesNotMatch("a.1234567890123.deleted.");
    doesNotMatch("a.1234567890123.deleted.git");

    // missing .git suffix
    doesNotMatch("a.1234567890123.%deleted%");
    doesNotMatch("a.20181010120101.%deleted%");

    // additional characters after the "git" suffix
    doesNotMatch("a.1234567890123.%deleted%.git.");
    doesNotMatch("a.1234567890123.%deleted%.git.git");
    doesNotMatch("a.20181010120101.%deleted%.git.");
    doesNotMatch("a.20181010120101.%deleted%.git.git");
  }

  private void matches(String name) {
    assertThat(match(name)).isTrue();
  }

  private void doesNotMatch(String name) {
    assertThat(match(name)).isFalse();
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=640,initial-scale=0.5,user-scalable=no">


text:
package com.r3bl.todo_app.container.firebase;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import com.google.firebase.database.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.r3bl.todo_app.container.App;
import com.r3bl.todo_app.container.redux.Actions;
import com.r3bl.todo_app.container.redux.state.Data;
import com.r3bl.todo_app.container.redux.state.State;
import com.r3bl.todo_app.container.redux.state.User;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.r3bl.todo_app.container.firebase.MyDB.Locations.USER_ACCOUNT_ROOT;
import static com.r3bl.todo_app.container.firebase.MyDB.Locations.USER_DATA_ROOT;

/**
 * Created by nazmul on 11/8/16.
 */

public class MyDB {
private final App                _ctx;
private final FirebaseDatabase   _db;
private final ExecutorService    _exec;
private       ValueEventListener user_data_listener;
private       ValueEventListener user_info_listener;
private       DatabaseReference  user_data_ref;
private       DatabaseReference  user_info_ref;

public enum Locations {
  USER_ACCOUNT_ROOT,
  USER_DATA_ROOT,
  DATA_KEY,
}

public MyDB(App app) {
  _ctx = app;
  _db = com.google.firebase.database.FirebaseDatabase.getInstance();
  _exec = Executors.newSingleThreadExecutor();
}

public com.google.firebase.database.FirebaseDatabase getDatabase() {
  return _db;
}

public void saveUserAndLoadData(User user) {
  // save the user object to firebase
  saveUserInfoToFirebase(user);

  // start listening for updates from firebase (which will fire actions)
  attachListenerToUserInfo(user.uid);
  attachListenerToUserData(user.uid);
}

public void attachListenerToUserData(String uid) {
  removeUserDataValueListener();

  user_data_ref = _db.getReference().child(USER_DATA_ROOT.name())
                     .child(uid)
                     .child(Locations.DATA_KEY.name());

  user_data_listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      _fromFirebaseUserData(dataSnapshot);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
  };

  user_data_ref.addValueEventListener(user_data_listener);
}

public void removeUserDataValueListener() {
  try {
    user_data_ref.removeEventListener(user_data_listener);
  } catch (Exception e) {
  }
}

public void attachListenerToUserInfo(String uid) {
  removeUserInfoValueListener();

  user_info_ref = _db.getReference().child(USER_ACCOUNT_ROOT.name())
                     .child(uid);

  user_info_listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      _fromFirebaseUserInfo(dataSnapshot);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
  };

  user_info_ref.addValueEventListener(user_info_listener);

}

public void removeUserInfoValueListener() {
  try {
    user_info_ref.removeEventListener(user_info_listener);
  } catch (Exception e) {
  }
}

//
// UserInfo and Data load / save to / from Firebase
//

private void _fromFirebaseUserInfo(DataSnapshot dataSnapshot) {

  _exec.submit(() -> {
    try {
      App.log("Database", "_fromFirebaseUserInfo");
      User userinfo = dataSnapshot.getValue(User.class);

      if (userinfo == null) {
        App.log("Database._fromFirebaseUserInfo]",
                "no data object found in Firebase");
        return;
      }

      // Create a handler attached to the UI Looper
      Handler handler = new Handler(Looper.getMainLooper());
      // Post code to run on the main UI Thread (usually invoked from worker thread)
      handler.post(() -> {
        _ctx.getReduxStore().dispatch(new Actions.SetUser(userinfo));
        App.log("Database._fromFirebaseUserInfo",
                "dispatching SetData action");
      });

    } catch (Exception e) {
      App.logErr("Database", "_fromFirebaseUserInfo issue", e);
    }
  });

}// end _fromFirebaseUserInfo

public void saveUserInfoToFirebase(User userinfo) {
  if (userinfo != null) {
    DatabaseReference ref = _db.getReference()
                               .child(USER_ACCOUNT_ROOT.name())
                               .child(userinfo.uid);
    ref.setValue(userinfo);
  }
  saveStateToSharedPrefs(_ctx, _ctx.getReduxState());
}

/**
 * run this code in a background thread, since this is an expensive method call!
 *

 * more info - https://guides.codepath.com/android/Managing-Threads-and-Custom-Services#using-an-asynctask
 */
private void _fromFirebaseUserData(DataSnapshot dataSnapshot) {

  _exec.submit(() -> {
    try {
      App.log("Database", "_fromFirebaseUserData");
      Data data = dataSnapshot.getValue(Data.class);
      data.trimEmptyArrayItems();

      if (data == null) {
        App.log("Database._fromFirebaseUserData]",
                "no data object found in Firebase");
        return;
      }

      // Create a handler attached to the UI Looper
      Handler handler = new Handler(Looper.getMainLooper());
      // Post code to run on the main UI Thread (usually invoked from worker thread)
      handler.post(() -> {
        _ctx.getReduxStore().dispatch(new Actions.SetData(data));
        App.log("Database._fromFirebaseUserData",
                "dispatching SetData action");
      });

    } catch (Exception e) {
      App.logErr("Database", "_fromFirebaseUserData issue", e);
    }
  });

}// end _fromFirebaseUserData

public void saveUserDataToFirebase(Data data) {
  if (data != null) {
    data.prepForSaveToFirebase(_ctx.getSessionId(), ServerValue.TIMESTAMP);

    DatabaseReference ref = _db.getReference()
                               .child(USER_DATA_ROOT.name())
                               .child(_ctx.getReduxState().user.uid)
                               .child(Locations.DATA_KEY.name());
    ref.setValue(data);
  }
  saveStateToSharedPrefs(_ctx, _ctx.getReduxState());
}

//
// Shared Preferences
//

public static State loadStateFromSharedPrefs(App context) {
  SharedPreferences pref = context.getSharedPreferences(MyDB.class.getSimpleName(),
                                                        Context.MODE_PRIVATE);
  String serform = pref.getString(Locations.DATA_KEY.name(), null);
  if (serform == null) return null;
  Gson gson = new GsonBuilder().create();
  State retval = gson.fromJson(serform, State.class);

  App.log("Database.loadStateFromSharedPrefs",
          "loading state from SharedPreferences");

  return retval;
}

public static void saveStateToSharedPrefs(App context, State state) {
  SharedPreferences.Editor pref = context.getSharedPreferences(MyDB.class.getSimpleName(),
                                                               Context.MODE_PRIVATE)
                                         .edit();
  pref.putString(Locations.DATA_KEY.name(),
                 state.toString());
  pref.apply();

  App.log("Database.saveStateToSharedPrefs",
          "saving state to SharedPreferences");
}

//
// Data migration from one user to another
//

/**
 * Y * 1) copy data from old -> new user (only if new user is NOT pre existing)
 * 2) delete old user from {@link Locations#USER_ACCOUNT_ROOT} & Locations#USER_DATA_ROOT
 *

 * Note - this means that a user that converts from anon -> a signed in user that already
 * has data in the system will lose the anon data. Data is only migrated for signedin
 * users that don't already existing in the database.
 */
public void performDataMigration(@NonNull User old_user,
                                 @NonNull User new_user) {
  // delete the old_user
  _copyAndDelete(old_user, new_user);
}

/**
 * copy data from old_user -> new_user ONLY if new_user doesn't have any existing data
 */
private void _copyAndDelete(User old_user, User new_user) {
  DatabaseReference old_user_data_ref =
    getDatabase().getReference()
                 .child(USER_DATA_ROOT.name())
                 .child(old_user.uid)
                 .child(Locations.DATA_KEY.name());

  DatabaseReference new_user_data_ref =
    getDatabase().getReference()
                 .child(USER_DATA_ROOT.name())
                 .child(new_user.uid)
                 .child(Locations.DATA_KEY.name());

  new_user_data_ref.addListenerForSingleValueEvent(new MyValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot newUserDataSnapshot) {
      if (newUserDataSnapshot.getValue() == null) {
        // new_user doesnt have any day in the db
        old_user_data_ref.addListenerForSingleValueEvent(new MyValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot oldUserDataSnapshot) {
            _copy(oldUserDataSnapshot, new_user_data_ref);
            _delete(old_user);
          }
        });

      } else {
        _delete(old_user);
      }
    }
  });
}

private void _copy(DataSnapshot dataSnapshot, DatabaseReference new_user_data_ref) {
  Data oldUserData = dataSnapshot.getValue(Data.class);
  if (oldUserData != null) {
    // copy the data from old_user -> new_user
    new_user_data_ref.setValue(oldUserData);
  }
}

/**
 * delete user and data for the old_user
 */
private void _delete(User old_user) {
  DatabaseReference old_user_data_root =
    getDatabase().getReference()
                 .child(USER_DATA_ROOT.name());

  DatabaseReference old_user_account_root =
    getDatabase().getReference()
                 .child(Locations.USER_ACCOUNT_ROOT.name());

  old_user_data_root.child(old_user.uid).removeValue();
  old_user_account_root.child(old_user.uid).removeValue();

  App.log("Database", "_deleteDataAndUser: deleting USER_DATA_ROOT/old_user & USER_ACCOUNT_ROOT/old_user");
}

public abstract class MyValueEventListener implements ValueEventListener {
  @Override
  public void onCancelled(DatabaseError databaseError) {

  }
}

}// end class Database


text:
define([], function () {

	var staff = function ($httpRequest, $q, $binder, $resContacts){
		var baseUrl = 'market/';
		var binder = $binder.get();
		var self = this;

		this.getPublishStaffs = function (){
			return $httpRequest.get('market/getList', {marketType:'supply'})
				.then(function (resp){
					var result = resp.data.result;
					if(!angular.isArray(result) || result.length === 0){
						return [];
					}
					//过滤只留有备注名的
					result.filter(function(item){
						return !!item.supply_remark_name;
					});
					return result;
				})
				.catch (function (resp) {
					return $q.reject(resp.data.error || resp.data);
				});
		};

		this.bindStaffGoods = function (scope, property) {
			binder.bind('goodsChanged', scope, property);
			return this.getStaffGoods().then(function (goods) {
				if (scope && property) scope[property] = goods;
				return goods;
			})
		};

		this.getStaffGoods = function (){
			return $httpRequest.get(baseUrl + 'getStaffGoods')
				.then(function (resp){
					var result = resp.data.result;
					return result;
				})
				.catch (function (resp) {
					return $q.reject(resp.data.error || resp.data);
				});
		};

		this.publish = function (itemDatas, contactData){
			return $resContacts.getContactsByGroups(contactData)
				.then(function (friendIds) {
					return $httpRequest.post(baseUrl + 'price', {
						items: itemDatas,
						friendIds: friendIds
					}).then(function () {
						self.getStaffGoods();
					}).catch(function (resp) {
						return $q.reject(resp.data.error || resp.data);
					});
				});
		};

		this.getGoodsApprovals = function (goodsId){
			return $httpRequest.get(baseUrl + 'getGoodsApprovals', {id:goodsId})
				.then(function (resp){
					var result = resp.data.result;
					return result;
				})
				.catch (function (resp) {
					return $q.reject(resp.data.error || resp.data);
				});
		};

		this.getStaffGoodsTradeInfo = function (goodsId){
			return $httpRequest.get(baseUrl + 'getStaffGoodsTradeInfo', {id:goodsId})
				.then(function (resp){
					var result = resp.data.result;
					return result;
				})
				.catch (function (resp) {
					return $q.reject(resp.data.error || resp.data);
				});
		};
	};

	angular.module('marketAgent')
		.service('$marketAgentStaff', ['$httpRequest', '$q', '$binder', '$resContacts', staff]);
});


text:
<?php

/* sprint2RealEstateAdminBundle:Pages:offres.html.twig */
class __TwigTemplate_ee812a32e3eb73addf6e06ddcba682e5e1dd3c2bc09c6ba20262909ec4e29855 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("sprint2RealEstateAdminBundle::admin_layout.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'Image' => array($this, 'block_Image'),
            'offreActive' => array($this, 'block_offreActive'),
            'offreCore' => array($this, 'block_offreCore'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "sprint2RealEstateAdminBundle::admin_layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_Image($context, array $blocks = array())
    {
        // line 3
        echo "        env, (isset($context["image"]) ? $context["image"] : $this->getContext($context, "image")), "html", null, true);
        echo "\" class=\"img-circle\" alt=\"User Image\" />
    ";
    }

    // line 5
    public function block_offreActive($context, array $blocks = array())
    {
        // line 6
        echo "        class=\"active treeview\"
    ";
    }

    // line 9
    public function block_offreCore($context, array $blocks = array())
    {
        // line 10
        echo "

                    ";
        // line 17
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($context["offre"]);
        foreach ($context['_seq'] as $context["_key"] => $context["offre"]) {
            echo "

                                    env, $this->getAttribute($context["offre"], "urlimage", array()), "html", null, true);
            echo "\"  height=\"150\"/>

";
            // line 22
            echo twig_escape_filter($this->env, $this->getAttribute($context["offre"], "typeimmob", array()), "html", null, true);
            echo "

                                  ";
            // line 23
            ob_start();
            // line 24
            echo "                                    ";
            echo twig_escape_filter($this->env, $this->getAttribute($context["offre"], "position", array()), "html", null, true);
            echo "
                                  ";
            $context["foo"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
            // line 26
            echo "

 ";
            // line 27
            echo twig_escape_filter($this->env, $this->getAttribute($context["offre"], "nbrpiece", array()), "html", null, true);
            echo " Piece, ";
            echo twig_escape_filter($this->env, $this->getAttribute($context["offre"], "surface", array()), "html", null, true);
            echo " Metre, Tunisie ";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($context["offre"], "idAdresse", array()), "gouvernorat", array()), "html", null, true);
            echo " ";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($context["offre"], "idAdresse", array()), "ville", array()), "html", null, true);
            echo "

                                  More info

                    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['offre'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 36
        echo "

    ";
    }

    public function getTemplateName()
    {
        return "sprint2RealEstateAdminBundle:Pages:offres.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  117 => 36,  96 => 27,  93 => 26,  87 => 24,  85 => 23,  81 => 22,  77 => 21,  68 => 17,  59 => 10,  56 => 9,  51 => 6,  48 => 5,  41 => 3,  38 => 2,  11 => 1,);
    }
}


text:
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeOperators              #-}

module Api.Environment where

import           Control.Monad.Except
import           Control.Monad.Reader        (ReaderT, runReaderT)
import           Control.Monad.Reader.Class
import           Data.Int                    (Int64)
import           Database.Persist.Postgresql (Entity (..), fromSqlKey, insert, get, delete, update,
                                              selectFirst, selectList, (==.), (=.))
import           Network.Wai                 (Application)
import           Servant

import           Config                      (App (..), Config (..))
import           Models

type EnvironmentAPI =
         "environments" :> Get '[JSON] [Entity Environment]
    :<|> "environments" :> ReqBody '[JSON] Environment :> Post '[JSON] Int64
    :<|> "environments" :> Capture "environmentId" (Key Environment) :> Get '[JSON] (Environment)
    :<|> "environments" :> Capture "environmentId" (Key Environment) :> Delete '[JSON] (String)
    :<|> "environments" :> Capture "environmentId" (Key Environment) :> ReqBody '[JSON] Environment :> Put '[JSON] (Environment)
    :<|> "environments" :> Capture "environtmentId" (Key Environment) :> "appliances" :> Get '[JSON] [Entity Appliance]
    :<|> "environments" :> Capture "environtmentId" (Key Environment) :> "devices" :> Get '[JSON] [Entity Device]
    :<|> "environments" :> Capture "environtmentId" (Key Environment) :> "devices" :> ReqBody '[JSON] (Entity Device) :> Post '[JSON] [Entity Device]
    :<|> "environments" :> Capture "environtmentId" (Key Environment) :> "devices" :> Capture "deviceId" (Key Device) :> Delete '[JSON] [Entity Device]

-- | The server that runs the EnvironmentAPI
environmentServer :: ServerT EnvironmentAPI App
environmentServer = allEnvironments :<|> createEnvironment :<|> singleEnvironment :<|> deleteEnvironment :<|> updateEnvironment :<|> singleEnvironmentAppliances :<|> getEnvironmentDevice :<|> postEnvironmentDevice :<|> deleteEnvironmentDevice

-- | Returns all environments in the database.
allEnvironments :: App [Entity Environment]
allEnvironments = do
    maybeUser <- runDb (selectFirst [UserName ==. "Ricky Hariady"] [])
    case maybeUser of
      Nothing ->
        throwError err401
      Just user -> do
        runDb (selectList [EnvironmentUserId ==. (entityKey user)] [])

-- | Returns an environment by name or throws a 404 error.
singleEnvironment :: Key Environment -> App (Environment)
singleEnvironment environmentId = do
    maybeEnvironment <- runDb (get environmentId)
    case maybeEnvironment of
         Nothing ->
            throwError err404
         Just environment ->
            return environment

-- | Returns an environment by name or throws a 404 error.
updateEnvironment :: Key Environment -> Environment -> App (Environment)
updateEnvironment environmentId newEnvironment = do
    maybeEnvironment <- runDb (get environmentId)
    case maybeEnvironment of
         Nothing ->
            throwError err404
         Just environment -> do
            runDb (update environmentId [EnvironmentParentId =. (environmentParentId newEnvironment), EnvironmentName =. (environmentName newEnvironment)])
            return newEnvironment

-- | Returns an appliance by name or throws a 404 error.
deleteEnvironment :: Key Environment -> App (String)
deleteEnvironment environmentId = do
    runDb (delete environmentId)
    return "OK"

-- | Creates an environment in the database.
createEnvironment :: Environment -> App Int64
createEnvironment p = do
    maybeUser <- runDb (selectFirst [UserName ==. "Ricky Hariady"] [])
    case maybeUser of
      Nothing ->
        throwError err401
      Just user -> do
        newEnvironment <- runDb (insert (Environment (entityKey user) (environmentParentId p) (environmentName p)))
        return $ fromSqlKey newEnvironment

-- | Returns an environment by name or throws a 404 error.
singleEnvironmentAppliances :: Key Environment -> App [Entity Appliance]
singleEnvironmentAppliances environmentId = do
    maybeEnvironment <- runDb (get environmentId)
    case maybeEnvironment of
         Nothing ->
            throwError err404
         Just environment ->
            runDb (selectList [ApplianceEnvironmentId ==. (environmentId) ] [])

getEnvironmentDevice :: Key Environment -> App [Entity Device]
getEnvironmentDevice environmentId = do
    maybeEnvironment <- runDb (get environmentId)
    case maybeEnvironment of
         Nothing ->
            throwError err404
         Just appliance -> do
           runDb (selectList [DeviceEnvironmentId ==. (Just environmentId)] [])

postEnvironmentDevice :: Key Environment -> Entity Device -> App [Entity Device]
postEnvironmentDevice environmentId device = do
  maybeEnvironment <- runDb (get environmentId)
  case maybeEnvironment of
    Nothing ->
      throwError err404
    Just environment -> do
      maybeDevice <- runDb (get (entityKey device))
      case maybeDevice of
        Nothing ->
          throwError err404
        Just _ -> do
          runDb (update (entityKey device) [DeviceEnvironmentId =. (Just environmentId), DeviceApplianceId =. Nothing])
          runDb (selectList [DeviceEnvironmentId ==. (Just environmentId)] [])

deleteEnvironmentDevice :: Key Environment -> Key Device -> App [Entity Device]
deleteEnvironmentDevice environmentId deviceId = do
  maybeEnvironment <- runDb (get environmentId)
  case maybeEnvironment of
    Nothing ->
      throwError err404
    Just environment -> do
      maybeDevice <- runDb (selectFirst [DeviceId ==. deviceId, DeviceEnvironmentId ==. (Just environmentId)] [])
      case maybeDevice of
        Nothing ->
          throwError err404
        Just device -> do
          runDb (update (deviceId) [DeviceEnvironmentId =. Nothing])
          runDb (selectList [DeviceEnvironmentId ==. (Just environmentId)] [])


text:
<?php
/**
 * Created by PhpStorm.
 * User: T.Behrens
 * Date: 04.05.14
 * Time: 12:05
 */

class resource_type {
	private $sql;

	public function getSql($type, $data = null)
	{
		switch ($type) {
			case 'load':
				$this->sql = "SELECT r.id, r.durability, r.amount, r.resource_type_id, rt.type, rt.purchase_price FROM `resources` r
				INNER JOIN `resource_type` rt ON r.resource_type_id = rt.id";
				break;
			case 'loadById':
				$this->sql = "SELECT * FROM `resource_type` rt
				WHERE id = $data";
				break;
			case 'truncate':
				$this->sql = "TRUNCATE `resource_type`";
				break;
		}

		return $this->sql;
	}
}


text: Show MOTD and Rules


text:
package au.com.pactera.pacterapulse.app;

import android.app.Application;
import android.os.StrictMode;

/**
 * Created by kai on 20/05/15.
 */
public class Config
{

	public static final String SERVERURL = "http://pacterapulse-dev.elasticbeanstalk.com/";

	Config(Application application)
	{
		setupStrictMode();
	}

	private void setupStrictMode()
	{
		StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
				new StrictMode.ThreadPolicy.Builder()
						.detectAll()
						.penaltyLog();
		StrictMode.VmPolicy.Builder vmPolicyBuilder =
				new StrictMode.VmPolicy.Builder()
						.detectLeakedSqlLiteObjects()
						.detectLeakedClosableObjects()
						.penaltyLog();
		StrictMode.setThreadPolicy(threadPolicyBuilder.build());
		StrictMode.setVmPolicy(vmPolicyBuilder.build());
	}
}


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>Gulella factsheet on ARKive - Gulella puzeyi</title>
        <link rel="canonical" href="http://www.arkive.org/gulella/gulella-puzeyi/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Gulella (Gulella puzeyi)

Kingdom	Animalia

Phylum	Mollusca

Class	Gastropoda

Order	Stylommatophora

Family	Streptaxidae

Genus	Gulella (1)

Classified as Critically Endangered (CR) on the IUCN Red List (1).

Information on Gulella puzeyi is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: arkive@wildscreen.org.uk

IUCN Red List  (August, 2009)
http://www.iucnredlist.org/