text:
GLSL fragment shading on rectangle library
useful for experient of fractal, filter, raymarch, etc...

### Usage

```HTML
<!DOCTYPE html>

<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
		</style>
	</head>
	<body>
    <script id="frag" type="x-shader/x-fragment">
      // Your fragment shader here

      #ifdef GL_ES
      precision mediump float;
      #endif

      uniform float time;
      uniform vec2 resolution;

      void main()
      {
        vec2 uv = gl_FragCoord.xy / resolution;
        gl_FragColor = vec4( uv, 0.5 + 0.5*sin( time ), 1.0 );
      }
    </script>
    <script src="ItaPoly.js"></script>
		<script>
      var width = 240;
      var height = 240;
      var itapoly = new ItaPoly( width, height ); // create ItaPoly object
      document.body.appendChild( itapoly.canvas ); // put canvas into document
      itapoly.createProgram( document.getElementById( 'frag' ).innerHTML, function(){ // compile fragment shader then callback
          function update(){
            itapoly.update(); // draw once
            requestAnimationFrame( update ); // request next frame
          }
          update();
      } );

		</script>
	</body>
</html>
```

### Methods

- `ItaPoly( width (number), height (number) )`
	create ItaPoly Object wow

- `ItaPoly.createProgram( frag (string), callback (function) )`
	create the program wow

- `ItaPoly.update()`
	draw once wow

- `ItaPoly.setFloat( name (string), param (number) )`
- `ItaPoly.setVec2( name (string), param ([ number, number ]) )`
- `ItaPoly.setVec3( name (string), param ([ number, number, number ]) )`
- `ItaPoly.setVec4( name (string), param ([ number, number, number, number ]) )`
- `ItaPoly.setInt( name (string), param (number) )`
- `ItaPoly.setSampler2D( name (string), texture (image or canvas or video) )`
- `ItaPoly.setSampler2DFromArray( name (string), array ([ number, number, number, number, ... ]), width (number), height (number) )`
	set uniform variables wow

### Events

- `ItaPoly.onMouseDown( mouseEvent )`
- `ItaPoly.onMouseMove( mouseEvent )`
- `ItaPoly.onMouseUp( mouseEvent )`
	events wow


text:
export { ImageUploadModule } from './src/image-upload.module';
export { ImageUploadComponent } from './src/components/image-upload/image-upload.component';

redpajama_set_name: RedPajamaGithub


text:
/**
 * Reevaluation that just returns the base object.
 */
dbm.registerClass("dbm.utils.reevaluation.staticreevaluation.SelectBaseObjectObject", "dbm.utils.reevaluation.ReevaluationBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.utils.reevaluation.staticreevaluation.SelectBaseObjectObject");

	//Self reference
	var SelectBaseObjectObject = dbm.importClass("dbm.utils.reevaluation.staticreevaluation.SelectBaseObjectObject");

	//Error report

	//Dependencies

	//Utils

	//Constants

	/**
	 * Contructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.utils.reevaluation.staticreevaluation.SelectBaseObjectObject::_init");

		this.superCall();

		this.reevaluationData = null;

		return this;
	};

	/**
	 * The function that reevalutes this reference.
	 *
	 * @param	aBaseObject		*	The object to base the reevaluation from.
	 *
	 * @return	*	The base object
	 */
	objectFunctions.reevaluate = function(aBaseObject) {

		return aBaseObject;
	};

	/**
	 * Set all properties of the object to null. Part of the destroy function.
	 */
	objectFunctions.setAllReferencesToNull = function() {

		this.reevaluationData = null;

		this.superCall();
	};

	/**
	 * Creates a new command of this class.
	 *
	 * @return	SelectBaseObjectObject	The newly created command.
	 */
	staticFunctions.createCommand = function() {
		return ClassReference._createAndInitClass(ClassReference);
	};
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Fagara boninshimae Koidz. ex Hara

### Remarks
null


text:
/**
 * A sub module of APP.GUI that allows to create a pager for splitting lots of screen elements on several pages.
 *
 * @class APP.GUI.pager
 */
APP.GUI.pager = function(config){

	var self = this;

	this.current_page = (config.start_page || 0);
	this.items_per_page = (config.items_per_page || 20);
	this.view = config.view;
	this.items_list = config.items_list;
	this.on_page_change = config.on_page_change;

	//if show_always is activated, the pager renders, even if all items fit on one page
	this.show_always = (config.show_always || false);

	this.before_page_change = config.before_page_change;

	var refreshVars = function(){

		self.items_count = self.items_list.length;

		//how many pages will there be
		self.page_count = Math.ceil(self.items_count / self.items_per_page);

		/*
		console.log(
			"items_count / items_per_page = " + self.items_count + " / "+
			self.items_per_page
		);
		*/

		//if there are 0 items, page_count should not be 0, but 1
		if (self.page_count == 0){
			//console.log("page count was 0 but should be 1");
			self.page_count = 1;
		}

		self.start_item = self.current_page * self.items_per_page;

		//if the page if full of items
		self.end_item = self.start_item + self.items_per_page - 1;

		//if page is last page and not full of items
		if (self.items_list.length < (self.end_item + 1)){
			self.end_item = self.items_list.length - 1;
		}

		//if there are no items at all
		if (self.items_list.length == 0){
			self.end_item = 0;
		}

		/*******************************************/
		//if the page is full of items
		self.visible_items = self.items_list.slice(
			self.start_item,
			self.start_item + self.items_per_page
		);

		//if page is last page
		if (self.current_page == self.page_count - 1){

			self.visible_items = self.items_list.slice(
				self.start_item
			);

			/*
			console.log("page is last page. showing all items from "+
				self.start_item + ". page is " + self.current_page +
				". page_count = " + self.page_count
			);
			*/

		}

		//console.log("PAGER ITEMS LIST:");
		//console.log(self.items_list);

		//if page is last page but no items there because no items at all
		if (self.items_list.length == 0){
			self.visible_items = [];
		}

		// if current page is higher than page_count, reset current_page to
		// the highest possible
		if (self.current_page >= self.page_count){

			/*
			console.log(
				"current page " + self.current_page +
				"higher than page_count " + self.page_count + "! Set it to " + (self.page_count - 1)
			);
			*/

			self.changePage(self.page_count - 1);
			return;
		}

	};

	this.refresh = function(items){

		//console.log("got items: ");
		//console.log(items);

		self.items_list = items;

		refreshVars();

		/*
		console.log(
			"rendering page " + self.current_page + "\n" +
			"page_count " + self.page_count + "\n" +
			"start " + self.start_item + "\n" +
			"end " + self.end_item + "\n" +
			"items count " + self.items_count + "\n" +
			"visible items length " + self.visible_items.length + "\n"
		);
		*/

		self.hide();

		if ((self.items_count > self.items_per_page || self.show_always == true) && (g(APP.active_view) == self.view)){

			var div = dom.div(g("environment_view"), "pager", "pager", "Page: ");
			g("content_wrapper").style.bottom = "84px";

		}

		else {

			return;

		}

		for (var i = 0; i < self.page_count; i++){

			var span = dom.span(div, "page_link_"+i, "page_link", i+1);

			if (i == self.current_page){

				span.className += " page_link_active";

			}

			span.addEventListener("click", function(num){

				return function(){
					self.changePage(num);
					self.refresh(self.items_list);
				};

			}(i), false);

		}

		if (self.items_count != 0){

			var pager_info = "Showing items " + (self.start_item+1) + "-" +
			(self.end_item+1) + " of " + self.items_list.length;

		}

		else {

			pager_info = "";

		}

		dom.span(div, "pager_info_span", "", pager_info);

	};

	this.changePage = function(p){

		if (typeof self.before_page_change == "function"){

			self.before_page_change();

		}

		self.current_page = p;

		self.on_page_change(self.items_list);

		APP.GUI.scrollTop();

	};

	this.hide = function(){

		if (g("pager")){
			dom.remove("pager");
			g("content_wrapper").style.bottom = "";

		}

		//console.log("pager HIDDEN");

	};

	refreshVars();
	//this.render();

};


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var argCommand = require('../cmd-helpers').argCommand;

module.exports = function (send) {
  return {
    get: argCommand(send, 'config'),
    set: function set(key, value, opts, cb) {
      if (typeof opts === 'function') {
        cb = opts;
        opts = {};
      }

      if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
        value = JSON.stringify(value);
        opts = { json: true };
      } else if (typeof value === 'boolean') {
        value = value.toString();
        opts = { bool: true };
      }

      return send('config', [key, value], opts, null, cb);
    },
    show: function show(cb) {
      return send('config/show', null, null, null, true, cb);
    },
    replace: function replace(file, cb) {
      return send('config/replace', null, null, file, cb);
    }
  };
};


text:
module Databasedotcom
  module Rails
    VERSION = "1.1.0"
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Famliy.Finance.Models
{
    public class CustomAttribute
    {
    }

    ///
    /// 自定义唯一约束
    ///
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class UniqueAttribute : ValidationAttribute
    {
        public override Boolean IsValid(Object value)
        {
            //校验数据库是否存在当前Key
            return true;
        }
    }

    //public class SomeMsgAttribute : FilterAttribute, IResultFilter
    //{
    //    public void OnResultExecuted(ResultExecutedContext filterContext)
    //    {
    //    }

    //    public void OnResultExecuting(ResultExecutingContext filterContext)
    //    {
    //        filterContext.Controller.ViewBag.Msg = "Hello";
    //    }
    //}
    public class MyFilterAttribute : ActionFilterAttribute
    {
        public string Message { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            filterContext.HttpContext.Response.Write("Action执行之前" + Message + "
");
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            filterContext.HttpContext.Response.Write("Action执行之后" + Message + "
");
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            filterContext.HttpContext.Response.Write("返回Result之前" + Message + "
");
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            filterContext.HttpContext.Response.Write("返回Result之后" + Message + "
");
        }
    }

    public class CheckLogin : ActionFilterAttribute
    {
        //在Action执行之前 乱了点,其实只是判断Cookie用户名密码正不正确而已而已。
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //HttpCookieCollection CookieCollect = System.Web.HttpContext.Current.Request.Cookies; if (CookieCollect["username"] == null || CookieCollect["password"] == null)
            //{
            //    filterContext.Result = new RedirectResult("/Home/Login");
            //}
            //else
            //{
            //    if (CookieCollect["username"].Value != "admin" && CookieCollect["password"].Value != "123456")
            //    {
            //        filterContext.Result = new RedirectResult("/Home/Login");
            //    }
            //}
        }
    }//本示例贪图方便,将要跳转到的Action放在同一个Controller下了,如果将过滤器放到Controller类顶部,则永远也跳不到这个LoginAction。
}


text:
package net.thisptr.java.influxdb.metrics.agent.template.resolvers;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;

import net.thisptr.java.influxdb.metrics.agent.template.PlaceholderResolver;

import com.google.common.base.Joiner;

public class JmxResolver implements PlaceholderResolver {
	private static final MBeanServer MBEANS = ManagementFactory.getPlatformMBeanServer();

	@Override
	public String resolve(String expr) {
		try {
			return resolveInternal(expr);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private String resolveInternal(final String expr) throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
		final String[] names = expr.split(":");
		if (names.length < 3)
			throw new IllegalArgumentException(expr);
		final String attribute = names[names.length - 1];
		final String domainWithKeyProperties = String.join(":", Arrays.copyOfRange(names, 0, names.length - 1));

		final List<String> values = new ArrayList<>();
		for (final ObjectInstance mbean : MBEANS.queryMBeans(ObjectName.getInstance(domainWithKeyProperties), null)) {
			values.add(MBEANS.getAttribute(mbean.getObjectName(), attribute).toString());
		}
		return Joiner.on(",").join(values);
	}
}


text:
using NUnit.Framework;
using Xamarin.UITest;

namespace TaskyUITest
{
	[TestFixture(Platform.Android)]
	[TestFixture(Platform.iOS)]

	public abstract class BaseTest
	{
		protected IApp app;
		protected Platform platform;

		protected HomeScreen HomeScreen;
		protected TaskDetailsPage TaskDetailsPage;

		protected BaseTest(Platform platform)
		{
			this.platform = platform;

		}

		[SetUp]
		virtual public void BeforeEachTest()
		{
			app = AppInitializer.StartApp(platform);
			app.Screenshot("App Initialized");

			this.HomeScreen = new HomeScreen(app, this.platform);
			this.TaskDetailsPage = new TaskDetailsPage(app, this.platform);
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Dashboard">
    <meta name="keyword" content="Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">

    <title>Sistema Estadistico</title>

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

        <link href="../../css/font-awesome.min.css" rel="stylesheet" type="text/css" />

        <link href="../../css/ionicons.min.css" rel="stylesheet" type="text/css" />

        <link href="../../css/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />

        <link href="../../css/iCheck/all.css" rel="stylesheet" type="text/css" />

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

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

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

    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="../assets/css/style-responsive.css" rel="stylesheet">

<?php
$id=$_GET['id'];
echo "$id";
?>

ESTA A PUNTO DE

  BORRAR

LOS DATOS DE UN PERIODO ESCOLAR

¡BORRAR LOS DATOS IMPLICA PERDER TODA LA INFORMACIÓN PERMANENTEMENTE!

<form class="contact_form" action="../control/borrar_periodo.php" method="post">
  <input type="hidden" name="id_periodo_escolar" value= <?php echo "$id"; ?> />
      <button type="submit" class="btn btn-danger  btn-lg">
         BORRAR
      </button>

      <button type="button" class="btn btn-primary  btn-lg">
         NO BORRAR
      </button>

</form>


text:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import trace
# from PackageNormalData import *
from flask import Blueprint, request, jsonify, redirect, render_template
import requests
import urllib
from Libraries.Utils import *
from Platform.ZuiwanCenter.ZuiwanCenter import ZuiwanCenter
zuiwanCenter = ZuiwanCenter.instance()
# 实例化一个blueprint
ZuiwanWechat = Blueprint("ZuiwanWechat", __name__)

@ZuiwanWechat.route('api/v1/zuiwan/ask-leave', methods = ['POST'], endpoint='ask_leave')
@check_api_cost_time
@allow_cross_domain
@package_json_request_data
def ask_leave():
    result = {'code':ED.no_err,'data':{}}
    data = request.data
    # data = [{user:'',ask_time:'',token:''}]
    result['data'] = zuiwanCenter.ask_leave(data)
    return json.dumps(result)

@ZuiwanWechat.route('api/v1/zuiwan/vote', methods = ['POST'], endpoint='zuiwan_vote')
@check_api_cost_time
@allow_cross_domain
@package_json_request_data
def zuiwan_vote():
    result = {'code':ED.no_err,'data':{}}
    data = request.data
    if data != None:
        result['data'] = zuiwanCenter.vote(data)
    else:
        result['code'] = ED.err_sys

    return json.dumps(result)

@ZuiwanWechat.route('api/v1/zuiwan/get-vote', methods = ['GET'], endpoint='zuiwan_get_vote')
@check_api_cost_time
@allow_cross_domain
@package_json_request_data
def zuiwan_vote():
    result = {'code':ED.no_err,'data':{}}
    data = request.data
    if data != None:
        result['data'] = zuiwanCenter.get_vote(data)
    else:
        result['code'] = ED.err_sys

    return json.dumps(result)


text:
package de.sambalmueslie.wot_api_definition.tankopedia_api;

import de.sambalmueslie.wot_api_definition.common.WotApiFieldDefinition;
import de.sambalmueslie.wot_api_definition.common.WotApiRequestDefinition;
import de.sambalmueslie.wot_api_definition.common.WotRequestDefinition;

/**
 * Method returns list of available vehicles.
 *
 * @autor Sambalmueslie
 */
@WotApiRequestDefinition(method = "wot/encyclopedia/tanks/")
public class EncyclopediaVehiclesRequestDefinition extends WotRequestDefinition {

	/** Nation. */
	@WotApiFieldDefinition(list = true)
	private String nation;
	/** Vehicle ID. */
	@WotApiFieldDefinition(list = true)
	private long tank_id;
	/** Tier. */
	@WotApiFieldDefinition(list = true)
	private long tier;

}


text:
// Copyright 2017 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.web.apirequest;

import java.util.LinkedHashSet;
import java.util.Map;

/**
 * Slices API Request. Such an API Request binds, validates, and models the parts of a request to the slices endpoint.
 */
public interface SlicesApiRequest extends ApiRequest {
    String REQUEST_MAPPER_NAMESPACE = "slicesApiRequestMapper";
    String EXCEPTION_HANDLER_NAMESPACE = "exceptionHandler";

    /**
     * Returns a set of all available slices.
     *
     * @return the set of all available slices
     */
    LinkedHashSet<Map<String, String>> getSlices();

    /**
     * Returns a slice object.
     *
     * @return the slice object
     */
    Map<String, Object> getSlice();
}


text:
An Angular directive for nested forms that prevents `$invalid` from propagating, allowing a nested form to be invalid without affecting its parent's validity.

Code originally written by [91K00](https://github.com/91K00), as seen [here](http://stackoverflow.com/questions/19333544/skip-nested-forms-validation-with-angularjs/24936234#24936234) and [here](https://github.com/angular/angular.js/issues/5858#issuecomment-50026221).

 **Usage:**

~~~html
 <form name="parent">
    <input type="text" ng-model="outside"/>
    <ng-form name="subform" isolate-form>
        <input type="text" ng-model="inside"/>
    </ng-form>
</form>

~~~

**Example:** [http://jsfiddle.net/gikoo/qNrFX/](http://jsfiddle.net/gikoo/qNrFX/)


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>675</FormatID>
      <FormatName>Exchangeable Image File Format (Compressed)</FormatName>
      <FormatVersion>2.1</FormatVersion>
      <FormatAliases>Exif Compressed Image (2.1)</FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Image (Raster)</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Exchangeable image file format (Exif) is a standard that specifies the formats for images, sound, and ancillary tags used by digital cameras (including smartphones), scanners and other systems handling image and sound files recorded by digital cameras.</FormatDescription>
      <BinaryFileFormat>Binary</BinaryFileFormat>
      <ByteOrders>Little-endian (Intel) and Big-endian (Motorola)</ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>1</ProvenanceSourceID>
      <ProvenanceName>Digital Preservation Department / The National Archives</ProvenanceName>
      <ProvenanceSourceDate>11 Mar 2005</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>02 Aug 2005</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>image/jpeg</Identifier>
        <IdentifierType>MIME</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>x-fmt/390</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Document>
        <DocumentID>19</DocumentID>
        <DisplayText>Japan Electronic Industry Development Association, 1998, JEIDA-49-1998 - Digital Still Camera Image File Format Standard (Exchangeable image file format for Digital Still Cameras: Exif), Version 2.1</DisplayText>
        <DocumentType>Authoritative</DocumentType>
        <AvailabilityDescription>Public</AvailabilityDescription>
        <AvailabilityNote>
        </AvailabilityNote>
        <PublicationDate>01 Dec 1998</PublicationDate>
        <TitleText>JEIDA-49-1998 - Digital Still Camera Image File Format Standard (Exchangeable image file format for Digital Still Cameras: Exif), Version 2.1</TitleText>
        <DocumentIPR>
        </DocumentIPR>
        <DocumentNote>
        </DocumentNote>
        <DocumentIdentifier>
          <Identifier>www.exif.org/dcf-exif.PDF</Identifier>
          <IdentifierType>URL</IdentifierType>
        </DocumentIdentifier>
        <Author>
          <AuthorID>105</AuthorID>
          <AuthorName>
          </AuthorName>
          <OrganisationName>Japan Electronic Industry Development Association</OrganisationName>
          <AuthorCompoundName>Japan Electronic Industry Development Association</AuthorCompoundName>
        </Author>
        <Publisher>
          <PublisherID>105</PublisherID>
          <PublisherName>
          </PublisherName>
          <OrganisationName>Japan Electronic Industry Development Association</OrganisationName>
          <PublisherCompoundName>Japan Electronic Industry Development Association</PublisherCompoundName>
        </Publisher>
      </Document>
      <ExternalSignature>
        <ExternalSignatureID>688</ExternalSignatureID>
        <Signature>jpg</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <ExternalSignature>
        <ExternalSignatureID>2262</ExternalSignatureID>
        <Signature>jpeg</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>147</SignatureID>
        <SignatureName>EXIF Compressed Image 2.1 (big-endian)</SignatureName>
        <SignatureNote>SOI and APP1, EXIF IFD (EXIF ver=2.1), EOI marker</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>93</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>
          </MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>FFD8FFE1{2}4578696600004D4D002A*900000070000000430323130</ByteSequenceValue>
        </ByteSequence>
        <ByteSequence>
          <ByteSequenceID>105</ByteSequenceID>
          <PositionType>Absolute from EOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>16000</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>FFD9</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <InternalSignature>
        <SignatureID>150</SignatureID>
        <SignatureName>EXIF Compressed Image 2.1 (little-endian)</SignatureName>
        <SignatureNote>SOI and APP1, EXIF IFD (EXIF ver=2.1), EOI marker</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>94</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>
          </MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>FFD8FFE1{2}45786966000049492A00*009007000400000030323130</ByteSequenceValue>
        </ByteSequence>
        <ByteSequence>
          <ByteSequenceID>106</ByteSequenceID>
          <PositionType>Absolute from EOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>16000</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>FFD9</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>670</RelatedFormatID>
        <RelatedFormatName>Raw JPEG Stream</RelatedFormatName>
        <RelatedFormatVersion>
        </RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Is previous version of</RelationshipType>
        <RelatedFormatID>676</RelatedFormatID>
        <RelatedFormatName>Exchangeable Image File Format (Compressed)</RelatedFormatName>
        <RelatedFormatVersion>2.2</RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Is subsequent version of</RelationshipType>
        <RelatedFormatID>751</RelatedFormatID>
        <RelatedFormatName>Exchangeable Image File Format (Compressed)</RelatedFormatName>
        <RelatedFormatVersion>2.0</RelatedFormatVersion>
      </RelatedFormat>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
This project is to watering plants outside.

## How to use
Copy Credentials.h and update your credentials to match your settings.


text:
package com.hazelcast.map.impl.record;

/**
 * Factory for creating records. Created for every partition.
 *
 * @param <T> the type of object which is going to be created.
 */
public interface RecordFactory<T> {

    Record<T> newRecord(Object value);

    void setValue(Record<T> record, Object value);
}


text:
package org.telegram.api.document.attribute;

/**
 * Indates that a document is animated
 * @author Ruben Bermudez
 * @version 2.0
 * @date 9 /01/15
 */
public class TLDocumentAttributeAnimated extends TLAbsDocumentAttribute {
    /**
     * The constant CLASS_ID.
     */
    public static final int CLASS_ID = 0x11b58939;

    /**
     * Instantiates a new TL document attribute animated.
     */
    public TLDocumentAttributeAnimated() {
        super();
    }

    @Override
    public int getClassId() {
        return CLASS_ID;
    }

    @Override
    public String toString() {
        return "documentAttributeAnimated#11b58939";
    }
}


text:
module SocialSnippet::Repository::DriverFactory

  @@drivers = []

  class << self

    def drivers
      @@drivers
    end

    def reset_drivers
      @@drivers = []
    end

    def add_driver(driver_class)
      drivers.push driver_class
    end

    # @param url [String] The URL of repository
    # @reutrn [::SocialSnippet::Repository::Drivers::DriverBase]
    def clone(url)
      driver = resolve_driver(url)
      driver.fetch
      driver
    end

    def resolve_driver(url)
      driver_class = drivers.select do |driver_class|
        driver_class.target? url
      end.first
      if driver_class.nil?
        raise "ERROR: driver not found"
      else
        driver_class.new url
      end
    end

  end # class << self

end # DriverFactory


text:
The learning curve for cfengine seams rather steep. I started with reading this crash course: https://cfengine.com/manuals/cf3-Reference#A-simple-crash-course

You should now be familiar with these concepts:

 1. promiser-type
 1. associations - are used by the promiser-type
 1. promiser - the abstract object making the promise
 1. promisee - the abstract object to whom the promise is made

Generalized syntax:

```
type:

        classes::

         "promiser" -> { "promisee1", "promisee2", ... }

            attribute_1 => value_1,
            attribute_2 => value_2,
            ...
            attribute_n => value_n;
```

You should also have learned the best practices when writing promises:
```
    comment => "Update the configuration from a master server",
    handle     => "update_policy",

    depends_on => {"serve_updates"},

```

Show availande classes:
```
sudo cf-promises -v
```

Types of hosts:

 * cf-agent - Keeps promisis in common and agent
 * execd - Runs agent and also keeps promisis in common
 * monitord - keeps promisis in common and monitor
 * serverd - Keeps promisis in common and server
 * cf-report - print reports from the cfengine database, keeps promisis in common

Now take a look at this: https://cfengine.com/manuals/cf3-solutions/


text:
<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_button.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#E93A1B"/>
    <corners
        android:bottomRightRadius="30dp"
        android:bottomLeftRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp"/>
</shape>


text:
module CommandT
  module VIM
    module Screen
      def self.lines
        ::VIM::evaluate('&lines').to_i
      end
    end # module Screen
  end # module VIM
end # module CommandT


text:
<?php
$tables['domains']         = 'cw_domains';
$tables['domains_config']  = 'cw_domains_config';

cw_include('addons/multi_domains/include/func.md.php');

cw_addons_set_controllers(
    array('replace', 'admin/domains.php', 'addons/multi_domains/admin/domains.php'),
    array('post', 'init/abstract.php', 'addons/multi_domains/init/domains.php'),
# kornev, access levels
    array('post', 'include/auth.php', 'addons/multi_domains/include/auth.php')
);
if ($target != 'image') {
    cw_set_controller('init/post_init.php', 'addons/multi_domains/init/get_host_data.php', EVENT_POST);
    cw_set_controller('init/post_init.php', 'addons/multi_domains/post_init.php', EVENT_POST);
}
cw_set_hook('cw_core_get_config',       'cw_md_core_get_config',            EVENT_POST);
cw_set_hook('cw_attributes_save',       'cw_md_attributes_save',            EVENT_POST); // additional function for the category attributes

cw_addons_set_hooks(
// search filters, can be unset if only one domain defined, see post_init.php
    array('pre', 'cw_product_search', 'cw_md_product_search'),
    array('pre', 'cw_category_search', 'cw_md_category_search'),
    array('pre', 'cw_manufacturer_search', 'cw_md_manufacturer_search'),
    array('pre', 'cw_speed_bar_search', 'cw_md_speed_bar_search'),
    array('pre', 'cw_shipping_search', 'cw_md_shipping_search'),
    array('pre', 'cw_payment_search', 'cw_md_payment_search'),
// individual object filters
    array('pre', 'cw_product_get', 'cw_md_product_search'),
    array('pre', 'cw_category_get', 'cw_md_category_search'),
    array('pre', 'cw_manufacturer_get', 'cw_md_manufacturer_search'),
// place order - save attributes
    array('pre', 'cw_doc_place_order', 'cw_md_doc_place_order'),
// settings
    array('post', 'cw_code_get_template_dir', 'cw_md_code_get_template_dir')
);

if (APP_AREA == 'cron') {
    cw_set_hook('cw_send_mail','cw_md_send_mail', EVENT_PRE);
}

if (APP_AREA == 'admin') {
    cw_event_listen('on_prepare_search_orders', 'cw_md_prepare_search_orders');

    cw_set_hook('cw_send_mail','cw_md_send_mail', EVENT_PRE); // This hook adds altskin as source of email templates
    cw_set_hook('cw_spam','cw_md_send_mail', EVENT_PRE);

    cw_addons_set_template(
	array('pre', 'main/docs/additional_search_field.tpl', 'addons/multi_domains/admin/additional_domain_selector.tpl'),
       array('post', 'common/navigation_counter.tpl', 'addons/multi_domains/common/current_domain_warning.tpl'),
       array('post', 'admin/attributes/default_types.tpl', 'addons/multi_domains/types/domain-selector.tpl')

    );
}
if (APP_AREA == 'customer') {
# kornev, languages per domain
    cw_addons_set_controllers(
        array('pre', 'init/lng.php', 'addons/multi_domains/init/lng.php'),
        array('pre', 'customer/referer.php', 'addons/multi_domains/customer/referer.php')
    );
    cw_addons_set_hooks(
        array('replace', 'cw_core_get_available_languages', 'cw_md_get_available_languages')
    );
    cw_addons_set_template(
        array('post', 'main/attributes/default_types.tpl', 'addons/multi_domains/types/domain-selector.tpl')
    );
}

cw_addons_set_template(
    array('post', 'common/top-filters.tpl', 'addons/multi_domains/common/top-filters.tpl')
);

cw_addons_add_css('addons/multi_domains/general.css', 'A');


text:
import sys
import fileinput
import random

# generate a list of symbols via ascii code
SYMBOLS = [str(unichr(i)) for i in range(33, 65)]

def rng_delimitor(password):
    words = password.split()
    n_words = len(words)

    # zip the split password and an equivalent number of symbols
    # join, and drop the first symbol
    return " ".join(i for l in zip(
        [random.choice(SYMBOLS) for _ in range(n_words)],
        words
    ) for i in l)[2:]

if __name__ == "__main__":
    # fileinput.input allows us to iterate over stdin
    for line in fileinput.input():
        rng_delim_line = rng_delimitor(line)
        sys.stdout.write(rng_delim_line + "\n")


text:
/**
 * Allows you to add twits to the global database.
 */

/*
* AetheBot - A Discord Chatbot
*
* Created by Tyrone Trevorrow on 09/02/22.
* Copyright (c) 2022 Tyrone Trevorrow. All rights reserved.
*
* This source code is licensed under the permissive MIT license.
*/

import { GlobalFeature, MessageContext } from "../feature"
import { wait } from "../../util/wait"
import { Brain } from "../../brain"
import { Dril } from "./dril"
import { TOOTS_BY_ID } from "./twits"
import { TweetPoolContent } from "./tweetpool"

export interface PersistedTwits {
    [id: string]: TweetPoolContent
}

export const BRAIN_KEY = "twit:custom_toots"

export async function fetchCustomToots(brain: Brain): Promise<PersistedTwits> {
    const persistedTwitsStr = await brain.get(BRAIN_KEY)
    let persistedTwits: PersistedTwits
    if (!persistedTwitsStr) {
        persistedTwits = {}
    } else {
        persistedTwits = JSON.parse(persistedTwitsStr)
    }
    return persistedTwits
}

export class TwitThisFeature extends GlobalFeature {
    public handleMessage(context: MessageContext<this>): boolean {
        const tokens = this.commandTokens(context)
        if (tokens.length < 3) {
            return false
        }
        const command = tokens[0].toLowerCase()
        const action = tokens[1].toLowerCase()
        const acceptable = new Set(["this", "add", "new"])
        if (!(command === "twit" && acceptable.has(action))) {
            return false
        }
        const urlStr = tokens[2]
        let url: URL
        try {
            url = new URL(urlStr)
        } catch (exc) {
            context.sendNegativeReply("invalid url")
            return false
        }

        if (url.host !== "twitter.com") {
            context.sendNegativeReply("invalid url")
            return false
        }
        const pathComponents = url.pathname.split("/")
        if (pathComponents.length !== 4) {
            context.sendNegativeReply("invalid url")
            return false
        }
        if (pathComponents[2] !== "status") {
            context.sendNegativeReply("invalid url")
            return false
        }
        if (pathComponents[1] === "dril") {
            const dril = new Dril(this.bot.brain)
            const no = dril.getNo()
            const embed = dril.embedForContent(no)
            context.sendReply("", embed)
            return true
        }

        this.addFromMessage(context, url)
        return false
    }

    private async addFromMessage(context: MessageContext<this>, url: URL): Promise<void> {
        const hourglassReact = await context.message.react("⏳")
        const pathComponents = url.pathname.split("/")
        const authorUsername = pathComponents[1]
        const tweetId = pathComponents[3]
        const canonicalUrl = `https://twitter.com/${authorUsername}/status/${tweetId}`

        const persistedTwits = await fetchCustomToots(this.bot.brain)

        if (persistedTwits[tweetId] || TOOTS_BY_ID.has(tweetId)) {
            context.sendNegativeReply("already added a tweet with that id")
            return
        }

        let attempts = 0
        while (attempts < 5) {
            if (context.message.embeds.length > 0) {
                break
            }
            await wait(1.0)
            attempts = attempts + 1
        }
        hourglassReact.remove()
        if (context.message.embeds.length === 0) {
            // gave up waiting for discord to embed
            context.sendNegativeReply("gave up waiting for discord to embed the tweet. try again later")
            return
        }
        const embed = context.message.embeds[0]
        if (!embed.author ||
            !embed.author.name ||
            !embed.author.proxyIconURL ||
            !embed.description)
        {
            context.sendNegativeReply("couldn't parse it. did discord change their shit?")
            return
        }
        const retweetsField = embed.fields.find(field => field.name === "Retweets")
        const likesField = embed.fields.find(field => field.name === "Likes")
        let retweets = 0
        let likes = 0
        if (retweetsField) {
            retweets = parseInt(retweetsField.value, 10)
        }
        if (likesField) {
            likes = parseInt(likesField.value, 10)
        }
        if (isNaN(retweets) || isNaN(likes)) {
            context.sendNegativeReply("couldn't parse it. did discord change their shit?")
            return
        }
        const description = embed.description.replace(/\*/g, "\\*")
        const content: TweetPoolContent = {
            avatar: embed.author.proxyIconURL,
            author: embed.author.name,
            content: description,
            url: canonicalUrl,
            likes,
            retweets,
        }
        if (embed.image && embed.image.proxyURL) {
            content.image = embed.image.proxyURL
        }

        persistedTwits[tweetId] = content
        const newJSON = JSON.stringify(persistedTwits)
        await this.bot.brain.set(BRAIN_KEY, newJSON)
        context.sendReply("ok")
    }
}


text:
package org.apache.flink.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * TCP EchoServer for test purposes.
 */
public class EchoServer extends Thread implements AutoCloseable {
	private final ServerSocket serverSocket = new ServerSocket(0);
	private final int socketTimeout;
	private final List<EchoWorkerThread> workerThreads = Collections.synchronizedList(new ArrayList<>());

	private volatile boolean close = false;
	private Exception threadException;

	public EchoServer(int socketTimeout) throws IOException {
		serverSocket.setSoTimeout(socketTimeout);
		this.socketTimeout = socketTimeout;
	}

	public int getLocalPort() {
		return serverSocket.getLocalPort();
	}

	@Override
	public void run() {
		while (!close) {
			try {
				EchoWorkerThread thread = new EchoWorkerThread(serverSocket.accept(), socketTimeout);
				thread.start();
			} catch (IOException e) {
				threadException = e;
			}
		}
	}

	@Override
	public void close() throws Exception {
		for (EchoWorkerThread thread : workerThreads) {
			thread.close();
			thread.join();
		}
		close = true;
		if (threadException != null) {
			throw threadException;
		}
		serverSocket.close();
		this.join();
	}

	private static class EchoWorkerThread extends Thread implements AutoCloseable {
		private final PrintWriter output;
		private final BufferedReader input;

		private volatile boolean close;
		private Exception threadException;

		public EchoWorkerThread(Socket clientSocket, int socketTimeout) throws IOException {
			output = new PrintWriter(clientSocket.getOutputStream(), true);
			input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			clientSocket.setSoTimeout(socketTimeout);
		}

		@Override
		public void run() {
			try {
				String inputLine;
				while (!close && (inputLine = input.readLine()) != null) {
					output.println(inputLine);
				}
			} catch (IOException e) {
				threadException = e;
			}
		}

		@Override
		public void close() throws Exception {
			close = true;
			if (threadException != null) {
				throw threadException;
			}
			input.close();
			output.close();
			this.join();
		}
	}
}


text:
package edu.caravane.guitare.application;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

public class Main extends Application {
	protected Stage primaryStage;
	// FIXME: troisième fois qu'on trouve le même code moche.. mon dieur...
	protected static final String osBarre = System.getProperty("os.name").charAt(0) == 'W' ? "\\" : "/";

	/**
	 * This function take a path and search in each folder recursively the first
	 * .git directory and return the list of git objects in the .git/object/* as
	 * String.
	 *
	 * @author Eloan
	 *
	 * @param path
	 *            of the file to explore
	 * @return the list of absolute path of all objects
	 * @throws an
	 *             exception if there is no object
	 */
	protected String[] searchGitObject(String path) throws Exception {
		Queue<String> filePasTrie = new LinkedList<String>();
		filePasTrie.add(path);
		File[] currentListFiles;
		File currentFile = new File(path);
		File gitRepository = new File(path);
		int indexLongueur = 0;
		boolean drap = false;
		while (filePasTrie.size() != 0 && drap == false) {
			currentFile = new File(filePasTrie.element());

			if (currentFile.isDirectory()) {
				currentListFiles = currentFile.listFiles();
				for (File f : currentListFiles) {
					if (f.getAbsolutePath().contains(osBarre + ".git" + osBarre + "objects" + osBarre)) {
						indexLongueur = f.getAbsolutePath().indexOf("git" + osBarre + "objects" + osBarre)
								+ ("git" + osBarre + "objects" + osBarre).length();

						gitRepository = new File(f.getAbsolutePath().substring(0, indexLongueur));

						drap = true;
						break;
					} else if (f.isDirectory() && f.listFiles().length != 0)
						filePasTrie.add(f.toString());
				}
				filePasTrie.remove();
			}
		}
		// Exception pas levee pour une raison inconnue
		if (!gitRepository.getAbsolutePath().contains(".git")) {
			MainWindow.errorMessageBox("ERROR !! :'(", "Il n'existe pas de .git dans le repertoire");
			throw new Exception("Il n'existe pas de .git dans le repertoire");
		}

		ArrayList<String> listGitObjects = new ArrayList<String>();
		if (drap == true) {
			for (File f : gitRepository.listFiles()) {
				if (f.isDirectory() && f.listFiles().length > 1) {
					for (File ff : f.listFiles())
						listGitObjects.add(ff.toString());
				} else if (f.isDirectory() && f.listFiles().length == 1)
					listGitObjects.add(f.listFiles()[0].toString());
			}
		}

		String gitObjectArray[] = new String[listGitObjects.size()];

		for (int i = 0; i < listGitObjects.size(); ++i)
			gitObjectArray[i] = listGitObjects.get(i);

		if (gitObjectArray.length == 0)
			throw new Exception();

		return gitObjectArray;
	}

	/**
	 * Start the main window, the git objects' explorer, and hide this current
	 * drag & drop window;
	 *
	 * @author VieVie31
	 *
	 * @param path
	 * @throws an
	 *             exception if it's impossible (eg. the Eloan function crash)
	 */
	protected void startMainWindow(String path) throws Exception {
		primaryStage.hide();
		MainWindow explorerMainWindow = new MainWindow();
		explorerMainWindow.start(primaryStage, searchGitObject(path));
	}

	@Override
	public void start(final Stage primaryStage) throws Exception {
		this.primaryStage = primaryStage;

		Parent root;
		AnchorPane dragPane;
		Scene scene;

		root = FXMLLoader.load(getClass().getResource("FirstScene.fxml"));
		dragPane = (AnchorPane) root.lookup("#dragPane");
		scene = new Scene(root);

		dragPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
			/**
			 * When the window is clicked the user can choose the directory to
			 * scan for exploring the git objects.
			 *
			 * @author VieVie31
			 */
			@Override
			public void handle(MouseEvent event) {
				event.consume();

				File selectedDir;
				selectedDir = new DirectoryChooser().showDialog(primaryStage);

				if (selectedDir == null)
					return; // no selection ignore the event

				try {
					startMainWindow(selectedDir.getAbsolutePath());
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
		});

		dragPane.setOnDragOver(new EventHandler<DragEvent>() {
			/**
			 * Enable the drag and drop function for files transfert.
			 *
			 * @author VieVie31
			 */
			@Override
			public void handle(DragEvent event) {
				if (event.getDragboard().hasFiles())
					event.acceptTransferModes(TransferMode.COPY);
				else
					event.consume();
			}
		});

		dragPane.setOnDragDropped(new EventHandler<DragEvent>() {
			/**
			 * When something is dropped, if it's a directory we open it in the
			 * git objects' explorer. Else ignore.
			 *
			 * @author VieVie31
			 */
			@Override
			public void handle(DragEvent event) {
				Dragboard db = event.getDragboard();
				if (db.hasFiles()) {
					event.setDropCompleted(true);
					event.consume();

					// on ne traite qu'un seul dossier donc on prend le premier
					File file = db.getFiles().get(0);

					// si c'est un fichier simple on ne traite pas ces merdes...
					if (file.isFile()) {
						MainWindow.errorMessageBox("ERROR !! :'(", // abrutit va
								"Draguer un repertoire, pas un ficher !!");
						return;
					} else {
						try {
							startMainWindow(file.getAbsolutePath());
						} catch (Exception e) {
							System.out.println(e.getMessage());
						}
					}

				} else
					event.setDropCompleted(true);

			}
		});

		primaryStage.setTitle("Drag Your Folder Here");
		primaryStage.setMinWidth(600);
		primaryStage.setMinHeight(400);
		primaryStage.setScene(scene);
		primaryStage.show();
	}

	public static void main(String[] args) {
		launch(args);
	}
}


text:
<!--
  Copyright (c) 2017 Seva Safris

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  You should have received a copy of The MIT License (MIT) along with this
  program. If not, see <http://opensource.org/licenses/MIT/>.
-->
<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.safris</groupId>
  <artifactId>java</artifactId>
  <version>0.0.0</version>
  <packaging>pom</packaging>
  <name>${project.groupId}:${project.artifactId}</name>
  <modules>
    <module>lib4j</module>
    <module>libx4j</module>
  </modules>
  <distributionManagement>
    <repository>
      <uniqueVersion>false</uniqueVersion>
      <id>mvn.repo.safris.org</id>
      <name>liv4j.org repository</name>
      <url>file://localhost/var/lib/mvn/safris/m2</url>
    </repository>
  </distributionManagement>
</project>


text:
using System;
using System.Runtime.InteropServices;

namespace DpiGonzales.Win32Helpers
{
    public class DpiAwarenessHelper
    {
        public static bool SetPerMonitorDpiAware()
        {
            switch (SetProcessDpiAwareness(ProcessDpiAwareness.ProcessPerMonitorDpiAware))
            {
                case EAccessDenied:
                    // TODO: throw a custom exception type so the caller can specifically catch it.
                    throw new InvalidOperationException("Access denied.");
                case SOk:
                    return true;
                default:
                    throw new InvalidOperationException("Failed to set per monitor DPI awareness.");
            }
        }

        private const int SOk = 0x00000000;
        private const int EAccessDenied = unchecked((int)0x80070005);

        [DllImport("Shcore")]
        private static extern int SetProcessDpiAwareness(ProcessDpiAwareness awareness);

        private enum ProcessDpiAwareness
        {
            ProcessDpiUnaware = 0,
            ProcessSystemDpiAware = 1,
            ProcessPerMonitorDpiAware = 2,
        }
    }
}


text:
---
type: post97
title:  Gateway Components
categories: XAP97
parent: multi-site-replication-overview.html
weight: 200
---

{{% ssummary %}} {{% /ssummary %}}

A replication gateway is used in order to send replication events from one space to another space by acting as the delegator of outgoing replication from one space to another, and by receiving incoming replication from a remote gateway and dispatching it to the local space. The gateway is composed of two components that handle this operation, a delegator and a sink. These components are configured in a standard `pu.xml` and usually the gateway should be deployed as a single processing unit (with one instance) into the service grid on each site configured with the local site relevant properties.

![wan_gatway_archi.jpg](/attachment_files/wan_gatway_archi.jpg)

## Gateway Delegator

The gateway's delegator main purpose is to delegate outgoing replication from one site to another, the need for the delegator arises from the common gateway usage topology, which is replicating data between spaces across the WAN. In this case, usually each space instance machine cannot open a direct socket to the remote site, therefor it uses the local delegator which is deployed on the local network in order to create a replication connection to the remote site. The machine on which the delegator is deployed, should have access to the remote site over the WAN and the ability to open sockets with the ports for discovery and communication which are configured in the gateway. Because the delegator is an outgoing communication point for replication, it is also used in the [Bootstrap](./replication-gateway-bootstrapping-process.html) process to delegate the bootstrap related communication from the bootstrapped site to the bootstrap source site.

The delegator configuration block in the gateway `pu.xml` looks as follows:

```xml
<os-gateway:delegator id="delegator" local-gateway-name="NEWYORK" gateway-lookups="gatewayLookups">
  <os-gateway:delegations>
    <os-gateway:delegation target="LONDON"/>
    <os-gateway:delegation target="HONGKONG"/>
  </os-gateway:delegations>
</os-gateway:delegator>
```

In this example, this is a delegator of New-York's gateway which acts as a delegation point for two targets, London and Hong-Kong. This will be the mediation point for the two replication channels to London and Hong-Kong of each space instance. It is important to understand that the delegator is not in charge of broadcasting each packet to all the targets but it receives the relevant packet from each source channel and delegate it to the correct target according to the channel endpoint.

## Gateway Sink

The gateway sink main purpose is to handle incoming replication, which is received by a remote gateway delegator from a remote site, and dispatches it into the local space. The sink has a special proxy to the local space that it uses in order to dispatch the replication into the space. The sink is also used the [Bootstrap](./replication-gateway-bootstrapping-process.html) process in both ends, it is used to initiate the bootstrap process and to fill in the local space with the data. It is also used at the bootstrap source site as the communication mediator between the remote sink and the local space which is used as the source for bootstrapping.

The sink configuration block in the gateway `pu.xml` looks as follows:

```xml
<os-gateway:sink id="sink"
  local-gateway-name="NEWYORK" gateway-lookups="gatewayLookups"
  local-space-url="jini://*/*/myNYSpace">
  <os-gateway:sources>
    <os-gateway:source name="LONDON" />
    <os-gateway:source name="HONGKONG" />
  </os-gateway:sources>
</os-gateway:sink>
```

In this example, this is the sink of New-York gateway that is open for incoming replication from London and Hong-Kong and will dispatch this incoming replication to the local space named "myNYSpace".

# Gateway Lookup Mechanism

In the above configuration samples, there is a `gateway-lookup` attribute, this attribute points to the lookup related configuration parameters.

The gateway components should locate each other in order to communicate with each other. This lookup is done both across sites and in some cases locally. Additionally the local space needs to locate the gateway delegator it needs to use for delegation, and the gateway sink needs to locate the local space in order to dispatch incoming replication to it.

We will split the lookup described here into two categories:

1. Local site lookup - locating components which reside in the local site (network)
1. Cross site lookup - locating components between sites (different networks), this lookup is only relevant for gateway components locating each other.

## Local Site Lookup

This lookup is done using the locally deployed lookup services which are already used by the service grid components and spaces in order to locate each other. The gateway components register in the local lookup services and therefor can be located by all the local services and components. e.g a space locates the local delegator to the remote target via the local lookup service.

## Cross Site Lookup

In most common scenarios, each site resides on a different LAN, and there is no direct network connection between the machines on different sites. However, the machines hosting the gateways of each site, needs to have some network connectivity available in order for the gateway to connect to each other and send the replication data between the sites. For the gateway to be able to communicate and locate each other, they need to be able to use two available ports, one used for the discovery process and the other for the communication between the gateways. These are known as the discovery ports (Lookup service port) and the communication port (LRMI port). By default, each gateway will start an embedded lookup service which is used for the discovery process, that lookup service will be started with the specified discovery port for that gateway. This is not mandatory, and the gateway can use an already existing lookup service which will be explained later on.
Each component, delegator and sink, will publish themselves in the lookup services in order for the other gateway components to be able to locate them between the sites.

The configuration which specifies the discovery and communication ports, along with the lookup service machine host (which by default should be the gateway machine it self as it starts the embedded lookup service) is described in each gateway `pu.xml` as follows:

```xml
<os-gateway:lookups id="gatewayLookups">
  <os-gateway:lookup gateway-name="NEWYORK" host="ny-gateway-host-machine"
    discovery-port="10001" communication-port="7000" />
  <os-gateway:lookup gateway-name="LONDON" host="london-gateway-host-machine"
    discovery-port="10002" communication-port="8000" />
  <os-gateway:lookup gateway-name="HONGKONG" host="hk-gateway-host-machine"
    discovery-port="10003" communication-port="9000" />
</os-gateway:lookups>
<!-- The above ports and host names are randomly selected and have no
     meaning, all sites could designate the same ports as well-->
```

The host and discovery port are used for the lookup process only, the communication port is used for the actual replication process after the relevant gateway component have discovered its target (e.g a delegator locates the target sink). The discovery and communication port should be permitted in the firewalls between the lookup services machines and between the gateway, when using the default, the lookup services are started inside the gateways, so this ports needs to be permitted between the gateway machines only.

When using the default configuration, in which the gateway starts the lookup service as embedded, the gateway should be deployed on the machine specified in its lookup entry as the `host` attribute, this can be achieved by having a [GigaSpaces Agent](/product_overview/service-grid.html#gsa) running on that machine with a dedicated zone, and configuring the gateway to be deployed to that specific zone (see [Configuring the Processing Unit SLA](./configuring-the-processing-unit-sla.html)). Once deployed, the gateway will check if the [Container](/product_overview/service-grid.html#gsc) it was deployed into is started with the proper ports, if not it will relocate itself to a proper container, and it may instantiate a new container managed by the agent on that machine if needed.

The communication port is optional, if there is no firewall between the gateways or all ports are permitted, this is not needed. Its purpose is to ease the gateway deployment by having the gateway automatically detect whether it is instantiated a GSC which was started with the specified communication port (LRMI), and if not it will spawn a new GSC with the correct LRMI port and relocate itself into that GSC thus saving you the need to pre-start a GSC with this specific port. If the GSC that is supposed to host the gateway is already configured with the right LRMI port, or alternatively, the communication port is not defined, the gateway will not spawn a new GSC and will not relocate itself.

If there is no firewall, and all ports are available, there is no need to specify a communication port as any communication port specified by the OS will work.

This process of spawning a new GSC and gateway relocation done as well when the gateway is configured to start an embedded lookup service (default) and the hosting GSC is not started with the matching discovery (lookup) port. This will not happen if the gateway is not configured to start an embedded gateway and is using an already existing one that is determined by the `host` and `discovery-port` attributes. In order to disable the creation of an embedded lookup service all the gateway components in the gateway processing unit (Both delegator and sink) should be configured with the following:

```xml
<os-gateway:delegator id="delegator" local-gateway-name=... gateway-lookups=... start-embedded-lus="false">
  ...
</os-gateway:delegator>
```

```xml
<os-gateway:sink id="sink"
  local-gateway-name=... gateway-lookups=... start-embedded-lus="false" local-space-url=...>
  ...
</os-gateway:sink>
```

In some scenarios, for example when there are many sites, it is more reasonable to use pre-started limited number of lookup services to avoid the creation of lookup services as the number of sites.
In this case, the `start-embedded-lus="false"` should be used and the `host` and `discovery-port` of the lookup attributes should point to the existing lookup services location. For example:

```xml
<os-gateway:lookups id="gatewayLookups">
  <os-gateway:lookup gateway-name="NEWYORK" host="lookup1-host-machine"
    discovery-port="10001" communication-port=... />
  <os-gateway:lookup gateway-name="LONDON" host="lookup2-host-machine"
    discovery-port="10002" communication-port=... />
  <os-gateway:lookup gateway-name="HONGKONG" host="lookup1-host-machine"
    discovery-port="10001" communication-port=... />
</os-gateway:lookups>
<!-- The above ports and host names are randomly selected and have no
     meaning, all sites could designate the same ports as well-->
```

In this case it is not that important which `host` and `discovery-port` is specified in which site, but it is recommended to use the "nearest" available lookup service configuration per site. However, each existing lookup service should appear at least once under one of the `os-gateway:lookup` entries in order for it to be used in the lookup process.

# Full Gateway Configuration Example File

Below is an example `pu.xml` file for the gateway of New-York

```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:os-core="http://www.openspaces.org/schema/core"
  xmlns:os-events="http://www.openspaces.org/schema/events"
  xmlns:os-remoting="http://www.openspaces.org/schema/remoting"
  xmlns:os-sla="http://www.openspaces.org/schema/sla"
  xmlns:os-gateway="http://www.openspaces.org/schema/core/gateway"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.openspaces.org/schema/core
    http://www.openspaces.org/schema/{{% currentversion %}}/core/openspaces-core.xsd
    http://www.openspaces.org/schema/events
    http://www.openspaces.org/schema/{{% currentversion %}}/events/openspaces-events.xsd
    http://www.openspaces.org/schema/remoting
    http://www.openspaces.org/schema/{{% currentversion %}}/remoting/openspaces-remoting.xsd
    http://www.openspaces.org/schema/sla
    http://www.openspaces.org/schema/{{% currentversion %}}/sla/openspaces-sla.xsd
    http://www.openspaces.org/schema/core/gateway
    http://www.openspaces.org/schema/{{% currentversion %}}/core/gateway/openspaces-gateway.xsd">

  <os-gateway:delegator id="delegator" local-gateway-name="NEWYORK"
    gateway-lookups="gatewayLookups">
    <os-gateway:delegation target="LONDON"/>
    <os-gateway:delegation target="HONGKONG"/>
  </os-gateway:delegator>

  <os-gateway:sink id="sink" local-gateway-name="NEWYORK"
    gateway-lookups="gatewayLookups" local-space-url="jini://*/*/myNYSpace">
    <os-gateway:sources>
      <os-gateway:source name="LONDON" />
      <os-gateway:source name="HONGKONG" />
    </os-gateway:sources>
  </os-gateway:sink>

  <os-gateway:lookups id="gatewayLookups">
    <os-gateway:lookup gateway-name="NEWYORK" host="ny-gateway-host-machine"
      discovery-port="10001" communication-port="7000" />
    <os-gateway:lookup gateway-name="LONDON" host="london-gateway-host-machine"
      discovery-port="10002" communication-port="8000" />
    <os-gateway:lookup gateway-name="HONGKONG" host="hk-gateway-host-machine"
      discovery-port="10003" communication-port="9000" />
  </os-gateway:lookups>
  <!-- The above ports and host names are randomly selected
       and have no meaning, all sites could designate the same ports as well-->
</beans>
```

# Indirect Delegation (Delegation via other gateways)

Some topologies may require in direct delegation, for example in the above topology, there bandwidth between London and Hong-Kong be very poor or maybe there is no direct connection between this two sites but they should still replicate to each other. This replication can be delegated from London to Hong-Kong via New-York and the other way around as well. This is accomplished by chaining delegators together, in this case the delegator of London to Hong-Kong will be actually connected to the delegator of New-York to Hong-Kong thus delegating the replication communication via New-York. In this case the gateway of London should be configured as follows:

```xml
<os-gateway:delegator id="delegator"
  local-gateway-name="LONDON" gateway-lookups="gatewayLookups">
  <os-gateway:delegations>
    <os-gateway:delegation target="NEWYORK"/>
    <os-gateway:delegation target="HONGKONG" delegate-through="NEWYORK"/>
  </os-gateway:delegations>
</os-gateway:delegator>

<os-gateway:sink id="sink" local-gateway-name="LONDON"
  gateway-lookups="gatewayLookups" local-space-url="jini://*/*/myNYSpace">
  <os-gateway:sources>
    <os-gateway:source name="LONDON" />
    <os-gateway:source name="HONGKONG" />
  </os-gateway:sources>
</os-gateway:sink>

<os-gateway:lookups id="gatewayLookups">
  <os-gateway:lookup gateway-name="NEWYORK" host="ny-gateway-host-machine"
    discovery-port="10001" communication-port="7000" />
  <os-gateway:lookup gateway-name="LONDON" host="london-gateway-host-machine"
    discovery-port="10002" communication-port="8000" />
</os-gateway:lookups>
<!-- The above ports and host names are randomly selected and
     have no meaning, all sites could designate the same ports as well-->
</beans>
```

In this configuration we have specifies that the delegator to Hong Kong should be routed via New York. This chaining can contain one or more delegators, i.e New York delegator could have been connected to Hong Kong via some other 4th site. The Hong Kong gateway should be configured in the same way. Another important thing to notice is that the lookup entry for Hong Kong is removed in London's gateway since it should never lookup Hong Kong directly.

In Direct delegation can be used by a [Bootstrap](./replication-gateway-bootstrapping-process.html) in the same manner, since the gateway sink in the bootstrapping site is using the local delegator in order to locate the bootstrap source site sink and therefor it will go through the same delegation path.

![wan-delegation.jpg](/attachment_files/wan-delegation.jpg)

# Seperating or Bundling The Gateway Components

The delegator and sink components are actually isolated and can even be deployed in separate processing units but the most simple deployment would be to bundle theses two together. However, in some cases you might want to separate this into two or more machines due to system loads or other reasons. This is done by simple creating two different processing units for the gateway, for example one can run the delegator and the other can run the sink.

Delegator pu.xml:

```xml
<?xml version="1.0" encoding="UTF-8"?>
  ...

  <os-gateway:delegator id="delegator" local-gateway-name="NEWYORK"
    gateway-lookups="gatewayLookups">
    <os-gateway:delegation target="LONDON"/>
    <os-gateway:delegation target="HONGKONG"/>
  </os-gateway:delegator>

  <os-gateway:lookups id="gatewayLookups">
    <os-gateway:lookup gateway-name="NEWYORK" host="ny-gateway-host-machine"
      discovery-port="10001" communication-port="7000" />
    <os-gateway:lookup gateway-name="LONDON" host="london-gateway-host-machine"
      discovery-port="10002" communication-port="8000" />
    <os-gateway:lookup gateway-name="HONGKONG" host="hk-gateway-host-machine"
      discovery-port="10003" communication-port="9000" />
  </os-gateway:lookups>
  <!-- The above ports and host names are randomly selected
       and have no meaning, all sites could designate the same ports as well-->
</beans>
```

Sink pu.xml:

```xml
<?xml version="1.0" encoding="UTF-8"?>
  ...

  <os-gateway:sink id="sink" local-gateway-name="NEWYORK"
    gateway-lookups="gatewayLookups" local-space-url="jini://*/*/myNYSpace">
    <os-gateway:sources>
      <os-gateway:source name="LONDON" />
      <os-gateway:source name="HONGKONG" />
    </os-gateway:sources>
  </os-gateway:sink>

  <os-gateway:lookups id="gatewayLookups">
    <os-gateway:lookup gateway-name="NEWYORK" host="ny-gateway-host-machine"
      discovery-port="10001" communication-port="7000" />
    <os-gateway:lookup gateway-name="LONDON" host="london-gateway-host-machine"
      discovery-port="10002" communication-port="8000" />
    <os-gateway:lookup gateway-name="HONGKONG" host="hk-gateway-host-machine"
      discovery-port="10003" communication-port="9000" />
  </os-gateway:lookups>
  <!-- The above ports and host names are randomly selected
       and have no meaning, all sites could designate the same ports as well-->
</beans>
```

It is also possible to bundle more than one sink and/or delegator in one processing unit, thus having one processing unit acting as the gateway of multiple spaces.
It is important to understand that a gateway is a logical and not a physical term which relates to all of the deployed processing units that contains at least one of the gateway components with the same name (sink or delegator).
Additionally, one can bundle two different gateways (i.e gateway components, sinks or delegators, with different names) in the same processing unit.

# NAT Configuration

When having Network Address Translation (NAT) data transit across different routing devices over the WAN, you should use the [NAT mapping configuration]({{%currentadmurl%}}/network-over-nat.html) with your WAN Gateway. Each site gateway should have a NAT mapping file that maps the remote site local IP to the public IP, therefore each site should have a different mapping file because it should not map its own local IP to the public IP. Additionally, in each site you should place the public IP in the Gateway lookup element of the remote sites Gateway, and the local IP in the lookup element of the local site Gateway, once again, in this case the gateways lookup element in the pu.xml of the Gateways will not be symmetric since the local gateway lookup element should contain the local IP at each site. After the lookup process is done, both Gateways connect directly as usual.

# Security

{{%note "Space PU Security Before addressing the gateway security, first make sure your space PU is deployed as secured."%}}

On Multiple Site topologies, securing grid components and spaces is done as described in GigaSpaces [Security](./security.html) page. When using a secured environment it is required to provide security credentials for the Gateway components (Sink & Delegator).
The security credentials are used for accessing a secured space and for performing administrative operations such as creating a new GSC for the gateway components if necessary.

Providing the security credentials can be done in two ways:

- On deployment (bean level properties)
- In the gateway component's pu.xml.

### Providing security credentials on deployment

The following bean level properties should be set:

- "security.username"
- "security.password"

### Providing security credentials in gateway component's pu.xml

Setting the security credentials is done using the "security" element in the "os-gateway" namespace:

```xml
<os-gateway:delegator id="delegator" local-gateway-name="USA" gateway-lookups="gatewayLookups">
  <os-gateway:delegations>
    <os-gateway:delegation target="FRANCE" />
  </os-gateway:delegations>
  <os-gateway:security username="${security.username}" password="${security.password}" />
</os-gateway:delegator>

<os-gateway:sink id="sink" local-gateway-name="USA" gateway-lookups="gatewayLookups"
         local-space-url="jini://*/*/usaSpace">
  <os-gateway:sources>
    <os-gateway:source name="FRANCE" />
  </os-gateway:sources>
  <os-gateway:security username="gs" password="1234" />
</os-gateway:sink>
```

It is also possible to set a "com.gigaspaces.security.directory.UserDetails" implementation instead of using the username and password attributes:

```xml
<bean id="userDetailsBean" class="com.gigaspaces.security.directory.User">
  <constructor-arg>
    <value>${username}</value>
  </constructor-arg>
  <constructor-arg>
    <value>${password}</value>
  </constructor-arg>
</bean>

<os-gateway:delegator id="delegator" local-gateway-name="USA" gateway-lookups="gatewayLookups">
  <os-gateway:delegations>
    <os-gateway:delegation target="FRANCE" />
  </os-gateway:delegations>
  <os-gateway:security user-details="userDetailsBean" />
</os-gateway:delegator>

<os-gateway:sink id="sink" local-gateway-name="USA" gateway-lookups="gatewayLookups"
        local-space-url="jini://*/*/usaSpace">
  <os-gateway:sources>
    <os-gateway:source name="FRANCE" />
  </os-gateway:sources>
  <os-gateway:security user-details="userDetailsBean" />
</os-gateway:sink>
```


text:
'use strict';

var winston = require('winston');
var SerialPort = require('serialport').SerialPort;
var modbus = require('h5.modbus');
var BufferReader = require('h5.buffers').BufferReader;
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var util = require('./util');
var fs = require('fs');
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));

var reMsg = /(\w+)\s(read|write)\s?([\w\.]+)?/;
var host = config.host;
var port = config.port;
var defaultPollIntervalMs = config.defaultPollIntervalMs;
var modbusMasters = {};
var registersWithDefaultPollInterval = [];
var registerCache = {};

var loglevel = 'info';
var args = process.argv.slice(2);
if (args.indexOf('-v') != -1) {
  loglevel = 'verbose';
} else if (args.indexOf('-vv') != -1) {
  loglevel = 'debug';
}

var logger = module.exports = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      colorize: 'all',
      level: loglevel,
      timestamp: true
    })
  ]
});

function setUpNetwork(master) {
  var name = config.modbusNetworks[i].name;
  modbusMasters[name] = config.modbusNetworks[i];
  modbusMasters[name].connected = false;

  var serialPort = new SerialPort(config.modbusNetworks[i].serialport,
    config.modbusNetworks[i].options);

  modbusMasters[name].instance = modbus.createMaster({
    transport: {
      type: 'rtu',

      // End Of Frame Timeout - after any data is received, the RTU transport
      // waits eofTimeout milliseconds, and if no more data is received, then
      // an end of frame is assumed. If more data arrives before the eofTimeout
      // ms, then the end of frame timer is restarted. Workaround for
      // 'at least 3 1⁄2 character times of silence between frames'
      // in MODBUS RTU (see http://en.wikipedia.org/wiki/Modbus#Frame_format).
      eofTimeout: 500,
      connection: {
        type: 'serial',
        serialPort: serialPort
      }
    },
    suppressTransactionErrors: false,
    retryOnException: true,
    maxConcurrentRequests: 1,
    defaultUnit: 0,
    defaultMaxRetries: 1,
    defaultTimeout: 1000
  });

  modbusMasters[name].instance.on('error', function(err) {
    logger.log('error', 'Master error', err);
  });

  modbusMasters[name].instance.on('connected', function() {
    logger.log('info', modbusMasters[name].name + ' connected');
    modbusMasters[name].connected = true;
  });

  modbusMasters[name].instance.on('disconnected', function() {
    logger.log('info', modbusMasters[name].name + ' disconnected');
    modbusMasters[name].connected = false;
  });
}

function setUpRegisters(master) {
  for (var i in master.registers) {
    var register = master.registers[i];
    if (register.polling === undefined) {
      registersWithDefaultPollInterval.push({
        master: master.name,
        register: register
      });
    }
  }
}

for (var i in config.modbusNetworks) {
  setUpNetwork(config.modbusNetworks[i]);
  setUpRegisters(config.modbusNetworks[i]);
}

var CronJob = require('cron').CronJob;
var job = new CronJob(config.defaultPoll, function() {
  for (var i in registersWithDefaultPollInterval) {
    pollRegisters(registersWithDefaultPollInterval[i]);
  }
}, function() {
  /* This function is executed when the job stops */
}, true /* Start the job right now */);

function sendValue(id, value) {
  if (id === '_') {
    logger.log('debug', 'Ignoring register named _');
    return;
  }

  registerCache[id] = value;
  var msg = id + ' ' + value;
  server.send(msg, 0, msg.length, port, host, function() {
    logger.log('verbose', msg);
  });
}

function pollRegisters(conf) {
  var master = modbusMasters[conf.master];
  var register = conf.register;
  if (!master.connected) return;

  var transaction;
  var options = {
    unit: register.slaveid,
    retryOnException: true,
    maxRetries: 2,
    timeout: 600
  };

  var registers = [].concat(register.id);

  var onError = function(err) {
    logger.error('Error polling register - ' + err);
  }

  var onComplete = function(err, response) {
    if (err !== null) {
      return;
    }

    logger.log('debug', 'Raw response: ' + response);
    if (register.type == 'coil' || register.type == 'discrete') {
      for (i in registers) {
        sendValue(registers[i], response.isOn(i));
      }
    } else if (register.converter == 'float32') {
      var buffer = new BufferReader(response.values);
      var length = buffer.length / registers.length;
      for (var i in registers) {
        var value = buffer.readFloat(0, false);
        sendValue(registers[i], value);
        buffer.skip(length);
      }
    } else {
      var buffer = new BufferReader(response.values);
      var length = buffer.length / registers.length;
      for (var i in registers) {
        var value = util.readInt(buffer, length);
        if (register.converter !== undefined) {
          value = util.convert(register.converter, value);
        }
        sendValue(registers[i], value);
        buffer.skip(length);
      }
    }
  };

  options.onComplete = onComplete;
  options.onError = onError;

  var readLength = (register.length !== undefined ? register.length : 1) * registers.length;
  if (register.type == 'input') {
    transaction = master.instance.readInputRegisters(
      register.address, readLength, options);
  } else if (register.type == 'holding') {
    transaction = master.instance.readHoldingRegisters(
      register.address, readLength, options);
  } else if (register.type == 'coil') {
    transaction = master.instance.readCoils(
      register.address, readLength, options);
  } else if (register.type == 'discrete') {
    transaction = master.instance.readDiscreteInputs(
      register.address, readLength, options);
  } else {
    logger.log('error', 'No valid type for register', register);
    return;
  }
}

function findSingleRegisterConf(id) {
  for (var i in registersWithDefaultPollInterval) {
    var index = registersWithDefaultPollInterval[i].register.id.indexOf(id);
    if (index > -1) {
      var register = registersWithDefaultPollInterval[i].register;
      var readLength = (register.length !== undefined) ? register.length : 1;
      var conf = {};
      conf.master = registersWithDefaultPollInterval[i].master;
      conf.register = {};
      conf.register.id = id;
      conf.register.slaveid = register.slaveid
      conf.register.converter = register.converter;
      conf.register.address = register.address + (readLength * index);
      conf.register.type = register.type;
      conf.register.writeOnAllChanges = register.writeOnAllChanges;
      return conf;
    }
  }
}

function read(id) {
  var conf = findSingleRegisterConf(id);
  if (conf !== undefined) {
    pollRegisters(conf);
  } else {
    logger.log('error', 'Unknown id ' + id);
  }
}

function writeSingleRegister(conf, value) {
  var master = modbusMasters[conf.master];
  var options = {
    unit: conf.register.slaveid,
    retryOnException: true,
    maxRetries: 2,
    timeout: 600
  };

  var onError = function(err) {
    logger.error('Error polling register - ' + err);
  }

  var onComplete = function(err, response) {
    if (err !== null) {
      logger.log('error', 'Error writing value to ' + conf.register.id + ' - ' + err);
      pollRegisters(conf);
      return;
    } else {
      logger.log('verbose', 'Wrote ' + response.value + ' to ' + conf.register.id);
      registerCache[conf.register.id] = response.value;
      sendValue(conf.register.id, response.value);
    }
  };

  options.onComplete = onComplete;
  options.onError = onError;
  master.instance.writeSingleRegister(conf.register.address, value, options);
}

function write(id, value) {
  var conf = findSingleRegisterConf(id);
  if (conf === undefined) {
    logger.log('error', 'Unknown id ' + id);
    return;
  }

  if (!conf.register.writeOnAllChanges && registerCache[id] == value) {
    logger.log('debug', 'Ignoring write request because value did not change');
  } else {
    writeSingleRegister(conf, value);
  }
}

server.on('message', function(msg, rinfo) {
  var match = msg.toString().match(reMsg);
  if (match === null) {
    logger.log('error', 'Unknown message - ' + msg);
    return;
  };

  if (match[2] == 'read') read(match[1]);
  if (match[2] == 'write') write(match[1], match[3]);
});

server.bind(config.localport);


text:
import InvalidProviderResponseStatusError from "./invalid-provider-response-status";

class ResourceNotFoundError extends InvalidProviderResponseStatusError {
    constructor(message: string, requestError: Error) {
        super(message, requestError);

        this.name = "ResourceNotFoundError";
    }
}

export { ResourceNotFoundError };

export default ResourceNotFoundError;


text:
using Rabbitual.Core;

namespace Rabbitual.Agents
{
    public abstract class Agent<TOptions> : IHaveOptions<TOptions> where TOptions : class
    {
        protected Agent(TOptions options)
        {
            Options = options;
        }

        public int Id { get; set; }
        public virtual void Start() { }
        public virtual void Stop() { }

        public TOptions Options { get; protected set; }
    }
}


text:
package org.apache.flink.table.data.util;

import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.types.RowKind;

/**
 * Utilities for {@link RowData}.
 */
public final class RowDataUtil {

	/**
	 * Returns true if the message is either {@link RowKind#INSERT} or {@link RowKind#UPDATE_AFTER},
	 * which refers to an accumulate operation of aggregation.
	 */
	public static boolean isAccumulateMsg(RowData row) {
		RowKind kind = row.getRowKind();
		return kind == RowKind.INSERT || kind == RowKind.UPDATE_AFTER;
	}

	/**
	 * Returns true if the message is either {@link RowKind#DELETE} or {@link RowKind#UPDATE_BEFORE},
	 * which refers to a retract operation of aggregation.
	 */
	public static boolean isRetractMsg(RowData row) {
		RowKind kind = row.getRowKind();
		return kind == RowKind.UPDATE_BEFORE || kind == RowKind.DELETE;
	}

	public static GenericRowData toGenericRow(
			RowData row,
			LogicalType[] types) {
		if (row instanceof GenericRowData) {
			return (GenericRowData) row;
		} else {
			GenericRowData newRow = new GenericRowData(row.getArity());
			newRow.setRowKind(row.getRowKind());
			for (int i = 0; i < row.getArity(); i++) {
				if (row.isNullAt(i)) {
					newRow.setField(i, null);
				} else {
					newRow.setField(i, RowData.get(row, i, types[i]));
				}
			}
			return newRow;
		}
	}
}


text:
@ECHO OFF
REM Copyright 2015 Ben Vanik. All Rights Reserved.

SET "DIR=%~dp0"

REM ============================================================================
REM Environment Validation
REM ============================================================================

CALL :check_python
IF %_RESULT% NEQ 0 (
  ECHO.
  ECHO Python 3.6+ must be installed and on PATH:
  ECHO https://www.python.org/
  GOTO :eof
)

REM ============================================================================
REM Trampoline into xenia-build
REM ============================================================================

"%PYTHON_EXE%" "%DIR%\xenia-build" %*
EXIT /b %ERRORLEVEL%

REM ============================================================================
REM Utilities
REM ============================================================================

:check_python
SETLOCAL ENABLEDELAYEDEXPANSION

SET FOUND_PATH=""

SET "CANDIDATE_PATHS[0]=C:\python37\python.exe"
SET "CANDIDATE_PATHS[1]=C:\python36\python.exe"
SET OUTPUT_INDEX=2

FOR /F "usebackq delims=" %%L IN (`2^>NUL where python3`) DO (
  IF %%~zL NEQ 0 (
    SET "CANDIDATE_PATHS[!OUTPUT_INDEX!]=%%L"
    SET /A OUTPUT_INDEX+=1
  )
)
FOR /F "usebackq delims=" %%L IN (`2^>NUL where python`) DO (
  IF %%~zL NEQ 0 (
    SET "CANDIDATE_PATHS[!OUTPUT_INDEX!]=%%L"
    SET /A OUTPUT_INDEX+=1
  )
)

SET CANDIDATE_INDEX=0
:check_candidate_loop
IF NOT DEFINED CANDIDATE_PATHS[%CANDIDATE_INDEX%] (
  GOTO :found_python
)
CALL SET CANDIDATE_PATH=%%CANDIDATE_PATHS[%CANDIDATE_INDEX%]%%
IF NOT EXIST "%CANDIDATE_PATH%" (
  SET /A CANDIDATE_INDEX+=1
  GOTO :check_candidate_loop
)
SET "FOUND_PATH=%CANDIDATE_PATH%"

:found_python
IF "%FOUND_PATH%"=="" (
  ECHO ERROR: no Python executable found on PATH.
  ECHO Make sure you can run 'python' or 'python3' in a Command Prompt.
  ENDLOCAL & SET _RESULT=1
  GOTO :eof
)

CMD /C ""%FOUND_PATH%" -c "import sys; sys.exit(1 if not sys.version_info[:2] ^>= (3, 6) else 0)"
IF %ERRORLEVEL% NEQ 0 (
  ECHO ERROR: Python version mismatch, not at least 3.6.
  ECHO Found Python executable was "%FOUND_PATH%".
  ENDLOCAL & SET _RESULT=1
  GOTO :eof
)

ENDLOCAL & (
  SET _RESULT=0
  SET "PYTHON_EXE=%FOUND_PATH%"
)
GOTO :eof


text:
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;

namespace Spect.Net.VsPackage.CustomEditors.TestEditor
{
    [Export(typeof(IViewTaggerProvider))]
    [ContentType("z80Test")]
    [TagType(typeof(TextMarkerTag))]
    public class Z80TestViewTaggerProvider : IViewTaggerProvider
    {
        /// <summary>Creates a tag provider for the specified view and buffer.</summary>
        /// <returns>The <see cref="T:Microsoft.VisualStudio.Text.Tagging.ITagAggregator`1" /> of the correct type for <paramref name="textView" />.</returns>
        /// <param name="textView">The <see cref="T:Microsoft.VisualStudio.Text.Editor.ITextView" />.</param>
        /// <param name="buffer">The <see cref="T:Microsoft.VisualStudio.Text.ITextBuffer" />.</param>
        /// <typeparam name="T">The type of the tag.</typeparam>
        public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag
        {
            string filePath = null;
            if (buffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument docProperty))
            {
                filePath = docProperty.FilePath;
            }
            var tagger = new Z80TestViewTagger(buffer, textView, filePath);
            return tagger as ITagger<T>;
        }
    }
}


text:
<?php

use CarouselTests\MockData\MockResponder;

use TRMS\Carousel\Models\Bulletin;
use TRMS\Carousel\Models\Media;
use TRMS\Carousel\Models\Zone;

use TRMS\Carousel\Models\BulletinTag;
use TRMS\Carousel\Models\ZoneTag;
use TRMS\Carousel\Models\MediaTag;

use TRMS\Carousel\Server\API;
use TRMS\Carousel\Exceptions\CarouselModelException;

class HasTagsTraitTest extends PHPUnit_Framework_TestCase
{

  function test_you_instantiate_a_bulletin_with_tags()
  {
    $props = json_decode(MockResponder::bulletin(),true);
    $bulletin = new Bulletin($props);

    $this->assertInstanceOf(BulletinTag::class, $bulletin->Tags[0]);
  }

  function test_you_instantiate_a_zone_with_tags()
  {
    $props = json_decode(MockResponder::zones(),true)[0];
    $zone = new Zone($props);

    $this->assertInstanceOf(ZoneTag::class, $zone->Tags[0]);
  }

  function test_you_instantiate_media_with_tags()
  {
    $props = json_decode(MockResponder::media(),true)[0];
    $media = new Media($props);

    $this->assertInstanceOf(MediaTag::class, $media->Tags[0]);
  }

  function test_you_can_add_a_tag_to_a_bulletin()
  {
    $bulletin = new Bulletin();

    $tag = new BulletinTag();
    $bulletin->addTag($tag);

    $this->assertInstanceOf(BulletinTag::class, $bulletin->Tags[0]);
  }

  function test_you_cannot_add_a_media_tag_to_a_bulletin()
  {
    $bulletin = new Bulletin();

    $tag = new MediaTag();
    try{
      $bulletin->addTag($tag);
    } catch (\TypeError $e){
      return;
    }

    $this->fail('an type error was not thrown');
  }

  function test_you_cannot_add_2_tags_with_the_same_id_to_a_bulletin()
  {
    $bulletin = new Bulletin();

    $tag = new BulletinTag(['id'=>'1']);
    $tag = new BulletinTag(['id'=>'1']);
    $bulletin->addTag($tag);

    $this->assertEquals(1, count($bulletin->Tags));
  }

  function test_you_can_remove_a_tag_from_a_bulletin()
  {
    $bulletin = new Bulletin();

    $tag1 = new BulletinTag(['id'=>'1']);
    $tag2 = new BulletinTag(['id'=>'2']);

    $bulletin->Tags = [$tag1, $tag2];

    $bulletin->removeTag($tag1);

    $this->assertEquals(1, count($bulletin->Tags));
    $this->assertEquals($tag2, $bulletin->Tags[0]);
  }

}


text:
require 'puppet/parameter/boolean'

Puppet::Type.newtype(:wildfly_cli) do
  desc 'Executes JBoss-CLI commmands'

  @isomorphic = false

  newparam(:command, :namevar => true) do
    desc 'The actual commmand to execute'
  end

  newparam(:unless) do
    desc 'If this parameter is set, then CLI command will only run if this command returns true'
  end

  newparam(:onlyif) do
    desc 'If this parameter is set, then CLI command will only run if this command returns false'
  end

  newparam(:refreshonly, :boolean => true, :parent => Puppet::Parameter::Boolean) do
    desc 'If this parameter is set, then CLI command will only run if the resource was notified'
    defaultto false
  end

  newparam(:username) do
    desc 'JBoss Management User'
  end

  newparam(:password) do
    desc 'JBoss Management User Password'
  end

  newparam(:host) do
    desc 'Host of Management API. Defaults to 127.0.0.1'
    defaultto '127.0.0.1'
  end

  newparam(:port) do
    desc 'Management port. Defaults to 9990'
    defaultto 9990
  end

  newparam(:secure) do
    desc 'Use TLS to connect with the management API'
    defaultto false
  end

  newproperty(:executed) do
    desc 'Whether the command should be executed or not'

    defaultto true

    def retrieve
      !provider.should_execute?
    end

    def sync
      provider.exec_command unless resource.refreshonly?
    end
  end

  def refresh
    if refreshonly? and provider.should_execute?
      Puppet.debug 'Executing wildfly_cli because resource received a refresh signal and refreshonly is true'
      provider.exec_command
    end
  end
end


text:
package writerexample

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scalaz.{MonadTell, WriterT}
import scalaz.std.list._
import scalaz.std.scalaFuture._
import scalaz.syntax.traverse._

/**
  * solution using scalaz is to simply use `WriterT`
  * the computation still happens in parallel,
  * but the result is a `Tuple2`, the first element
  * is aggregated log, second element is the computed result
  *
  * `WriterT` is a monad when the first type param is a monad
  * so for comprehension could be used to write
  * easy understandable and nearly imperative code
  */
object Solution extends App {

  type AsyncLogged[A] = WriterT[Future, List[String], A]
  val logger = MonadTell[AsyncLogged, List[String]]

  def step(id: String)(i: Int): AsyncLogged[Int] =
    WriterT.put(Future{ Thread.sleep(300); i})(List(s"executing step $i of $id"))

  def complexJob: AsyncLogged[List[Int]] = for {
    _       <- logger.tell(List("starting complex job"))
    results <- (0 to 30).toList.map({ i => step("complex job")(i) }).sequence
    _       <- logger.tell(List(s"complex job finished with $results"))
  } yield results

  def simpleJob: AsyncLogged[List[Int]] = for {
    _       <- logger.tell(List("starting simple job"))
    results <- (0 to 10).toList.map({ i => step("simple job")(i) }).sequence
    _       <- logger.tell(List(s"simple job finished with $results"))
  } yield results

  val jobs = List(complexJob, simpleJob).map(_.run)

  val res = Await.result(Future.sequence(jobs), Duration.Inf)
  res.map(_._1).flatten.foreach(println)
}


text:
<?php
/**
 *
 */
class Genome {

	private $genes = [];

	// Constructor
	function __construct($genomes_directory){

		$this->recursive_directory_search($genomes_directory);

	}

	/**
	 * Find genes by key value searching
	 *
	 * @param key (iso_code|state|name) to search
	 * @param value the value to find
	 *
	 * @retval a comma delimited text string
	 */
	function get_genes_by_key($key,$value){

		$string = '';

		foreach ($this->genes as $gene){

			if ($gene[$key] == $value){

				$string .= $gene['name'].",";
			}
		}

		return $string;
	}

	function get_genes(){

		$string = '';

		foreach ($this->genes as $gene){

			$string .= $gene['name'];
			if (next($this->genes) == true){

				$string .=",";
			}

		}

		return $string;
	}

	/**
	 * Populate our array of genes by scanning the Genome filestructure
	 * Genes are organized by ISO_CODE/STATE/NAME
	 *
	 * @param $dir the location of the Genome
	 */
	private function recursive_directory_search($dir){

		$iterator = new DirectoryIterator($dir);

		foreach ($iterator as $item) {

			if ($item->isDir() && !$item->isDot()){ // Ignore dots and anything that is not a directory

				// We only care about the path after Genome
				$trimmed_path = explode("Genome/",$item->getPathname());

				// Check for valid gene paths
				$gene = explode("/",end($trimmed_path));

				if (count($gene) == 3){

					$this->genes[] = [

						'iso_code'=> $gene[0],
						'state' => $gene[1],
						'name' => end($trimmed_path)
					];
				}

				// Iterate over only valid paths
				if ($gene[0] != '.git'){

					$this->recursive_directory_search("$dir/$item");
				}

			}
		}
	}

}
?>


text: Placeholder for user page


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Cesar B. Rocha | a post with images</title>
<meta name="description" content="Cesar B Rocha academic Web page
">

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.17.0/css/mdb.min.css" integrity="sha256-/SwJ2GDcEt5382i8zqDwl36VJGECxEoIcBIuoLmLR4g=" crossorigin="anonymous" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"  integrity="sha256-h20CPZ0QyXlBuAw7A+KluUYx/3pK+c7lYEpqLTlxjYQ=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:100,300,400,500,700|Material+Icons">

<link rel="shortcut icon" href="/assets/img/favicon.ico">
<link rel="stylesheet" href="/assets/css/main.css">

<link rel="canonical" href="/2015/05/15/images.html">

       Cesar B.  Rocha

      <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        Toggle navigation

      </button>

              about

                opportunities

                publications

                research

                résumé

                teaching

a post with images

May 15, 2015

Jean shorts raw denim Vice normcore, art party High Life PBR skateboard stumptown vinyl kitsch. Fingerstache four loko meh 8-bit, tousled banh mi tilde forage Schlitz dreamcatcher twee 3 wolf moon. Chambray asymmetrical paleo salvia, sartorial umami four loko master cleanse drinking vinegar brunch.

    A simple, elegant caption looks good between image rows, after each row, or doesn't have to be there at all.

Slow-carb four dollar toast Helvetica pop-up. Kale chips next level literally trust fund Pitchfork. Jean shorts Pinterest beard, farm-to-table irony craft beer swag tofu 8-bit Banksy. Quinoa forage fanny pack, pug hashtag Echo Park heirloom Schlitz tote bag artisan Neutra mumblecore 90's shabby chic raw denim.

    © Copyright 2021 Cesar B. Rocha.
    Powered by Jekyll with al-folio theme.

<link rel="stylesheet" href="https://gitcdn.link/repo/jwarby/jekyll-pygments-themes/master/github.css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.11.1/katex.min.css" integrity="sha256-V8SV2MO1FUb63Bwht5Wx9x6PVHNa02gv8BgH/uH3ung=" crossorigin="anonymous" />