text:
package com.groupdocs.ui.comparison.dropwizard.provider;

import com.groupdocs.ui.comparison.dropwizard.common.exception.LocalDiskException;
import com.groupdocs.ui.comparison.dropwizard.common.exception.TotalGroupDocsException;
import com.groupdocs.ui.comparison.dropwizard.config.LocalProviderConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.*;
import java.util.function.Consumer;

public class LocalFilesProvider extends FilesProvider {
    private static final Logger logger = LoggerFactory.getLogger(LocalFilesProvider.class);
    private final Path filesDirectory;
    private final Path resultDirectory;

    public LocalFilesProvider(LocalProviderConfiguration local) {
        final String filesDirectory = local.getFilesDirectory();
        final String resultDirectory = local.getResultDirectory();

        this.filesDirectory = makePathAbsoluteAndCreateDirectoriesIfNeed(filesDirectory);
        logger.debug("Files directory is '" + this.filesDirectory + "'");

        if (filesDirectory.equals(resultDirectory)) {
            this.resultDirectory = this.filesDirectory;
        } else {
            this.resultDirectory = makePathAbsoluteAndCreateDirectoriesIfNeed(resultDirectory);
        }
        logger.debug("Result directory is '" + this.resultDirectory + "'");
    }

    private Path makePathAbsoluteAndCreateDirectoriesIfNeed(String srcPath) {
        Path path = Paths.get(srcPath);
        final boolean isRelative = !path.isAbsolute();
        if (isRelative) {
            path = FileSystems.getDefault().getPath(path.toString()).toAbsolutePath();
        }
        try {
            if (Files.notExists(path)) {
                return Files.createDirectories(path);
            } else {
                return path;
            }
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't create files directory!", e);
        }
    }

    @Override
    public void visitDirectoryContent(String path, DirectoryContentVisitor visitor) throws LocalDiskException {
        logger.debug("Getting directory content for '" + path + "'");
        Path directoryPath = filesDirectory.resolve(path);
        try (final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directoryPath)) {

            directoryStream.forEach(itemPath -> {
                try {
                    final Path absolutePath = itemPath.toAbsolutePath();
                    final Path fileName = absolutePath.getFileName();
                    final boolean isDirectory = Files.isDirectory(itemPath);
                    final long size = isDirectory ? 0 : Files.size(itemPath);
                    visitor.visit(
                            absolutePath.toString(),
                            fileName.toString(),
                            isDirectory,
                            size
                    );
                } catch (Exception e) {
                    logger.warn("Can't get data for '" + directoryPath + "'", e);
                }
            });
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't list files in directory", e);
        }
    }

    @Override
    public void receiveFilesInputStream(String path, Consumer<InputStream> streamConsumer) throws LocalDiskException {
        logger.debug("Creating document input stream for '" + path + "'");
        try (final BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(filesDirectory.resolve(path)))) {
            streamConsumer.accept(inputStream);
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't receive file data! Try to reload page.", e);
        }
    }

    @Override
    public void receiveFilesOutputStream(String fileName, Consumer<OutputStream> streamConsumer) throws LocalDiskException {
        logger.debug("Creating document output stream for '" + fileName + "'");

        try (final BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(filesDirectory.resolve(fileName)))) {
            streamConsumer.accept(outputStream);
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't upload file data!", e);
        }
    }

    @Override
    public void receiveResultInputStream(String fileName, Consumer<InputStream> streamConsumer) throws LocalDiskException {
        logger.debug("Creating result input stream for '" + fileName + "'");

        try (final BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(resultDirectory.resolve(fileName)))) {
            streamConsumer.accept(inputStream);
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't receive result file data!", e);
        }
    }

    @Override
    public void receiveResultOutputStream(String fileName, Consumer<OutputStream> streamConsumer) throws LocalDiskException {
        logger.debug("Creating result output stream for '" + fileName + "'");

        try (final BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(resultDirectory.resolve(fileName)))) {
            streamConsumer.accept(outputStream);
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't upload result file data!", e);
        }
    }

    @Override
    public boolean isFileExists(String path) {
        logger.debug("Checking is file exists: '" + path + "'");
        return Files.exists(filesDirectory.resolve(path));
    }

    @Override
    public void deleteFile(String path) throws TotalGroupDocsException {
        logger.debug("Deleting the file: '" + path + "'");
        try {
            Files.delete(filesDirectory.resolve(path));
        } catch (IOException e) {
            throw new LocalDiskException("Storage exception: Can't delete the file!", e);
        }
    }
}


text:
layout: post
title:  "Extract Oracle JDK 8 in Windows(post 8u102)"
date:   2018-08-27 11:21:43 +0530
author: rajendarreddy jagapathi
categories: java
---

I would like to extract jdk from exe and point to it in eclipe.

## Extract JDK bin

- Download JDK from oracle(http://www.oracle.com/technetwork/java/javase/downloads/index.html).

- Extract exe file using 7-zip. It will be extracted to .rsrc directory.

- Open command prompt and go to .rsrc directory.

- Goto 1033\JAVA_CAB10 directory in .rsrc directory.

- Run below command to extract cab.

```
extrac32 111
```

- it is extracted to tools.zip in 1033\JAVA_CAB10.

- Extract tools.zip using 7-zip. It will be extracted to tools directory.

- Go to tools directory in 1033\JAVA_CAB10 directory.

- Run below command to extract jar.

```
for /r %x in (*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar"
```

## Extract src

- Goto 1033\JAVA_CAB9 directory in .rsrc directory.

- Run below command to extract cab.

```
extrac32 110
```
- it is extracted to src.zip in 1033/JAVA_CAB9.

- move src.zip to tools directory in 1033\JAVA_CAB10.

### Rename tools directory in 1033\JAVA_CAB10 to JDK8

### Add JDK8 to eclipse in installed JREs

redpajama_set_name: RedPajamaGithub


text:
enum NotificationType {
  NOTIF_TYPE_UNKNOWN = 0,
  NOTIF_TYPE_REACTION = 1
};

enum ReactionType {
  NOTIF_REACTION_LIKE = 1,
  NOTIF_REACTION_DISLIKE = 2
};

// File format: <reaction type> <user id> <text id>
struct ReactionNotif {
  enum ReactionType reactionType;
  int userId, textId;
};

// File format: <type> <notification specific data>
struct Notification {
  enum NotificationType type;
  union {
    struct ReactionNotif reaction;
  };
  struct Notification *next;
};

struct Notification *ReadNotifications(int userId, int clear);
void FreeNotifications(struct Notification *list);
int CountNotifications(int userId);
void AddNotification(int userId, struct Notification *notification);


text:
import * as util from "./util";
const path = require("path");

/**
 * Creates a toc object
 * @param  {Array} items       All items of the toc
 * @param  {Array} root   Only the root items
 * @return {Object}              Toc object
 */
const createToc = function (items, root) {
  if (items == null) items = [];
  if (root == null) root = [];

  return {
    items,
    root,
  };
};

const findByPath = util.findBy("path");

export const createTocFromFolderP = function (pathParam, toc, rootPath) {
  if (toc == null) toc = createToc();
  if (rootPath == null) rootPath = pathParam;

  return util.readdirP(pathParam).then((files) => {
    var localItemIds = [];
    var prom = Promise.resolve();
    files.forEach((f) => {
      var fullPath = path.join(pathParam, f);

      prom = prom
        .then(() => {
          return util.lstatP(fullPath);
        })
        .then((stats) => {
          var id =
            toc.items.push({
              ext: path.extname(f),
              isDir: stats.isDirectory(),
              absolutePath: fullPath,
              path: fullPath.replace(rootPath + path.sep, ""),
              name: f,
            }) - 1;
          localItemIds.push(id);

          if (toc.items[id].isDir) {
            return createTocFromFolderP(fullPath, toc, rootPath).then(
              (newToc) => {
                toc = newToc;
                toc.items[id].children = toc.root;
                toc.root = [];
              }
            );
          }
        });
    });

    prom = prom.then(() => {
      toc.root = localItemIds;
      return toc;
    });

    return prom;
  });
};

export const mergeTocConfigWithToc = function (toc, tocConfig) {
  var newToc = createToc();

  var addChildren = function (children) {
    var ids = [];
    children.forEach(function (childId) {
      var childItem = toc.items[childId];
      var id = newToc.items.push(childItem) - 1;
      ids.push(id);

      if (childItem.children != null) {
        childItem.children = addChildren(childItem.children);
      }
    });

    return ids;
  };
  var mergeItems = function (items, basePath) {
    if (basePath == null) basePath = "";

    var localItemIds = [];

    items.forEach((tocItem) => {
      var item = {};

      if (tocItem.path != null) {
        tocItem.path = path.join(basePath, tocItem.path);
        var origId = findByPath(toc.items, tocItem.path);
        if (origId !== false) {
          item = toc.items[origId];
        }
      }

      item.href = tocItem.href;
      if (tocItem.title != null) {
        item.title = tocItem.title;
      }

      var id = newToc.items.push(item) - 1;

      if (tocItem.children != null) {
        newToc.items[id].children = mergeItems(tocItem.children, tocItem.path);
        newToc.items[id].isDir = true;
      } else if (item.children != null) {
        newToc.items[id].children = addChildren(item.children);
      }

      localItemIds.push(id);
    });

    return localItemIds;
  };

  newToc.root = mergeItems(tocConfig);
  return newToc;
};

export const calculateItemLevels = function (toc, items, level) {
  if (level == null) level = 0;
  if (items == null) items = toc.root;
  items.forEach(function (itemId) {
    let item = toc.items[itemId];
    item.level = level;
    if (item.children != null) {
      calculateItemLevels(toc, item.children, level + 1);
    }
  });

  return toc;
};

export const getHtmlChapters = function (html) {
  const chapters = {
    root: [],
    items: [],
  };

  const headingRegexStr =
    '<h(\\d*)(?: id="(.*?)")?.*?>([\\s\\S]*?)<\\/h\\1(?: .*?)?>';
  const headingGlobalRegex = new RegExp(headingRegexStr, "g");
  const headingRegex = new RegExp(headingRegexStr);
  const htmlTagsRegex = /<(?:.|\n)*?>/gm;

  let matches = html.match(headingGlobalRegex);

  if (matches != null && matches.length > 0) {
    matches = matches.map(function (match) {
      const subMatches = match.match(headingRegex);
      const hash = subMatches[2];
      const heading = subMatches[3].replace(htmlTagsRegex, "");
      return { level: subMatches[1], heading: heading, hash };
    });

    const pushHeadingsRecursive = function (matches) {
      var head = matches[0];
      var tail = matches.slice(1);
      var rest = [];
      var broken = false;
      var children = [];
      tail.forEach(function (item) {
        if (item.level === head.level) {
          rest.push(item);
          broken = true;
        } else if (broken === false && head.level < item.level) {
          children.push(item);
        } else {
          rest.push(item);
        }
      });

      if (children.length > 0) {
        children = pushHeadingsRecursive(children);
      }

      head.children = children;

      if (rest.length > 0) {
        rest = pushHeadingsRecursive(rest);
      }

      return [head, ...rest];
    };

    const recursiveHeadings = pushHeadingsRecursive(matches);

    const normalizeRecursive = function (items) {
      return items.map(function (chapter) {
        const idx = chapters.items.push(chapter) - 1;
        chapter.id = idx;
        chapter.children = normalizeRecursive(chapter.children);
        return idx;
      });
    };

    chapters.root = normalizeRecursive(recursiveHeadings);
  }

  return chapters;
};


text:
<?php

/**
 * @see Zend_Controller_Response_Http
 */
require_once 'Zend/Controller/Response/Http.php';

/**
 * @author Geoffrey Tran
 * @license http://www.zym-project.com/license New BSD License
 * @category Zym
 * @package Zym_Controller
 * @subpackage Response
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 */
class Zym_Controller_Response_Http extends Zend_Controller_Response_Http
{
    /**
     * Cookies storage
     *
     * @var array
     */
    protected $_cookies = array();

    /**
     * Sets a cookie.
     *
     * @param string  $name      HTTP header name
     * @param string  $value     Value for the cookie
     * @param string  $expire    Cookie expiration period
     * @param string  $path      Path
     * @param string  $domain    Domain name
     * @param boolean $secure    If secure
     * @param boolean $httpOnly  If uses only HTTP (PHP 5.2 >=), not supported by all browsers
     * @return Zym_Controller_Response_Http
     */
    public function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false)
    {
        $this->canSendHeaders(true);

        // Validate expiration time
        if ($expire !== null && is_numeric($expire)) {
            $expire = (int) $expire;
        } else if ($expire !== null) {
            $expire = strtotime($expire);

            // Barf if its not valid
            if ($expire === false || $expire == -1) {
                /**
                 * @see Zym_Controller_Response_Exception
                 */
                require_once 'Zym/Controller/Response/Exception.php';
                throw new Zym_Controller_Response_Exception(
                    'Your expire parameter is not valid.'
                );
            }
        }

        $this->cookies[] = array(
            'name'     => $name,
            'value'    => $value,
            'expire'   => $expire,
            'path'     => $path,
            'domain'   => $domain,
            'secure'   => $secure ? true : false,
            'httpOnly' => $httpOnly
        );

        return $this;
    }

    /**
     * Clear cookies
     *
     * @return Zym_Controller_Response_Http
     */
    public function clearCookies()
    {
        $this->_cookies = array();

        return $this;
    }

    /**
     * Retrieves cookies from the current web response.
     *
     * @return array Cookies
     */
    public function getCookies()
    {
        $cookies = array();
        foreach ($this->cookies as $cookie){
            $cookies[$cookie['name']] = $cookie;
        }

        return $cookies;
    }

    /**
     * Return whether a cookie has been set
     *
     * @param string $name
     * @return boolean
     */
    public function hasCookie($name)
    {
        foreach ($this->_cookies as $cookie) {
            if ($cookie['name'] == $name) {
                return true;
            }
        }

        return false;
    }

    /**
     * Clear all headers, normal and raw
     *
     * @return Zym_Controller_Response_Http
     */
    public function clearAllHeaders()
    {
        // Clear cookies
        $this->clearCookies();

        return parent::clearAllHeaders();
    }

    /**
     * Send all headers
     *
     * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
     * has been specified, it is sent with the first header.
     *
     * @return Zym_Controller_Response_Http
     */
    public function sendHeaders()
    {
        // Only check if we can send headers if we have headers to send
        if (count($this->_cookies)) {
            $this->canSendHeaders(true);
        }

        // Send cookies
        foreach ($this->_cookies as $cookie) {
            setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'],
                         $cookie['domain'], $cookie['secure'], $cookie['httpOnly']);
        }

        return parent::sendHeaders();
    }
}


text:
<?php
  namespace ActiveCollab\FileToJson\File;

  /**
   * @package ActiveCollab\FileToJson\File\File
   */
  class TextFile implements File
  {

  }


text:
ActiveRecord::Schema.define(version: 20140116215314) do

  create_table "amounts", force: true do |t|
    t.integer  "artist_id"
    t.float    "percent"
    t.float    "amount"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "artists", force: true do |t|
    t.integer  "split_id"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "splits", force: true do |t|
    t.float    "total"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
package com.intel.databackend.datasources.hbase;

public final class KerberosProperties {
    private String user;
    private String password;
    private String realm;
    private String kdc;

    public String getUser() {
        return user;
    }

    public String getPassword() {
        return password;
    }

    public String getRealm() {
        return realm;
    }

    public String getKdc() {
        return kdc;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setRealm(String realm) {
        this.realm = realm;
    }

    public void setKdc(String kdc) {
        this.kdc = kdc;
    }
}


text:
using JetBrains.ReSharper.Psi.CSharp.Tree;

namespace MockMetrics.Eating.Statement
{
    public class ReturnStatementEater : StatementEater<IReturnStatement>
    {
        public ReturnStatementEater(IEater eater)
            : base(eater)
        {
        }

        public override void Eat(ISnapshot snapshot, IReturnStatement statement)
        {
            var condKind = Eater.Eat(snapshot, statement.Value);
            snapshot.Add(condKind, statement.Value);
        }
    }
}


text:
#!/usr/bin/env ruby -w
# encoding: UTF-8
class << ObjectSpace
  alias :每个对象 :each_object
  alias :定义回收回调 :define_finalizer
end


text:
class HomeController < ApplicationController

  def index
   if user_signed_in?

    redirect_to user_path(current_user)
   end
  end

end


text:
#ifndef _PROBE_H
#define _PROBE_H

#include <parted/parted.h>
#include <parted/endian.h>
#include <parted/debug.h>

#include "hfs.h"

int
hfsc_can_use_geom (PedGeometry* geom);

PedGeometry*
hfs_and_wrapper_probe (PedGeometry* geom);

PedGeometry*
hfsplus_probe (PedGeometry* geom);

PedGeometry*
hfs_probe (PedGeometry* geom);

PedGeometry*
hfsx_probe (PedGeometry* geom);

#endif /* _PROBE_H */


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "rspec/storage"
require "rspec/storage/s3"


text:
import copy
from corehq.apps.groups.fields import GroupField
from django import forms
from django.utils.translation import ugettext as _, ugettext_lazy
from corehq.apps.app_manager.fields import ApplicationDataSourceUIHelper
from corehq.apps.performance_sms import parser
from corehq.apps.performance_sms.exceptions import InvalidParameterException
from corehq.apps.performance_sms.models import TemplateVariable, ScheduleConfiguration, SCHEDULE_CHOICES
from corehq.apps.reports.daterange import get_simple_dateranges
from corehq.apps.userreports.ui.fields import JsonField
from crispy_forms.bootstrap import StrictButton
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
import corehq.apps.style.crispy as hqcrispy

class PerformanceMessageEditForm(forms.Form):
    recipient_id = forms.CharField()
    schedule = forms.ChoiceField(choices=[(choice, ugettext_lazy(choice)) for choice in SCHEDULE_CHOICES])
    template = forms.CharField(widget=forms.Textarea)
    time_range = forms.ChoiceField(
        choices=[(choice.slug, choice.description) for choice in get_simple_dateranges()]
    )

    def __init__(self, domain, config, *args, **kwargs):
        self.domain = domain
        self.config = config

        def _to_initial(config):
            initial = copy.copy(config._doc)
            initial['schedule'] = config.schedule.interval
            if config.template_variables:
                initial['application'] = config.template_variables[0].app_id
                initial['source'] = config.template_variables[0].source_id
                initial['time_range'] = config.template_variables[0].time_range
            return initial

        super(PerformanceMessageEditForm, self).__init__(initial=_to_initial(config), *args, **kwargs)

        self.fields['recipient_id'] = GroupField(domain=domain, label=_('Recipient Group'))

        self.app_source_helper = ApplicationDataSourceUIHelper(enable_cases=False)
        self.app_source_helper.bootstrap(self.domain)
        data_source_fields = self.app_source_helper.get_fields()
        self.fields.update(data_source_fields)

        self.helper = _get_default_form_helper()
        form_layout = self.fields.keys()
        form_layout.append(
            hqcrispy.FormActions(
                StrictButton(
                    _("Save Changes"),
                    type="submit",
                    css_class="btn btn-primary",
                ),
            )
        )
        self.helper.layout = Layout(
            *form_layout
        )

    def clean_template(self):
        return _clean_template(self.cleaned_data['template'])

    def clean_schedule(self):
        # todo: support other scheduling options
        return ScheduleConfiguration(interval=self.cleaned_data['schedule'])

    def save(self, commit=True):
        self.config.recipient_id = self.cleaned_data['recipient_id']
        self.config.schedule = self.cleaned_data['schedule']
        self.config.template = self.cleaned_data['template']
        template_variable = TemplateVariable(
            type=self.cleaned_data['source_type'],
            time_range=self.cleaned_data['time_range'],
            source_id=self.cleaned_data['source'],
            app_id=self.cleaned_data['application'],
        )
        self.config.template_variables = [template_variable]
        if commit:
            self.config.save()
        return self.config

    @property
    def app_id(self):
        if self.config.template_variables:
            return self.config.template_variables[0].app_id
        return ''

    @property
    def source_id(self):
        if self.config.template_variables:
            return self.config.template_variables[0].source_id
        return ''

def _get_default_form_helper():
    helper = FormHelper()
    helper.label_class = 'col-sm-3 col-md-2'
    helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
    helper.form_class = "form-horizontal"
    helper.form_id = "performance-form"
    helper.form_method = 'post'
    return helper

def _clean_template(template):
    try:
        parser.validate(template)
    except InvalidParameterException as e:
        raise forms.ValidationError(unicode(e))
    return template

class AdvancedPerformanceMessageEditForm(forms.Form):
    recipient_id = forms.CharField()
    schedule = forms.ChoiceField(choices=[(choice, ugettext_lazy(choice)) for choice in SCHEDULE_CHOICES])
    template = forms.CharField(widget=forms.Textarea)
    template_variables = JsonField(expected_type=list)

    def __init__(self, domain, config, *args, **kwargs):
        self.domain = domain
        self.config = config
        super(AdvancedPerformanceMessageEditForm, self).__init__(initial=config.to_json(), *args, **kwargs)

        self.fields['recipient_id'] = GroupField(domain=domain, label=_('Recipient Group'))

        self.helper = _get_default_form_helper()
        form_layout = self.fields.keys()
        form_layout.append(
            hqcrispy.FormActions(
                StrictButton(
                    _("Save Changes"),
                    type="submit",
                    css_class="btn btn-primary",
                ),
            )
        )
        self.helper.layout = Layout(
            *form_layout
        )

    def clean_template(self):
        return _clean_template(self.cleaned_data['template'])

    def clean_schedule(self):
        # todo: support other scheduling options
        return ScheduleConfiguration(interval=self.cleaned_data['schedule'])

    def save(self, commit=True):
        self.config.recipient_id = self.cleaned_data['recipient_id']
        self.config.schedule = self.cleaned_data['schedule']
        self.config.template = self.cleaned_data['template']
        self.config.template_variables = self.cleaned_data['template_variables']
        if commit:
            self.config.save()
        return self.config

    def clean_template_variables(self):
        template_vars = self.cleaned_data['template_variables']
        if not isinstance(template_vars, list):
            raise forms.ValidationError(_('Template variables must be a list!'))
        wrapped_vars = []
        for var in template_vars:
            try:
                wrapped = TemplateVariable.wrap(var)
                wrapped.validate()
                wrapped_vars.append(wrapped)
            except Exception as e:
                raise forms.ValidationError(_(u'Problem wrapping template variable! {}').format(e))
        return wrapped_vars


text:
/* @flow */
"use strict";

/**
 * Find the at-rule in which a rule is nested.
 *
 * Returns `null` if the rule is not nested within an at-rule.
 */
module.exports = function findAtRuleContext(
  rule /*: postcss$rule */
) /*: ?postcss$node*/ {
  const parent = rule.parent;

  if (parent.type === "root") {
    return null;
  }
  if (parent.type === "atrule") {
    return parent;
  }
  return findAtRuleContext(parent);
};


text:
/// <reference path="../bower_components/DefinitelyTyped/jquery/jquery.d.ts"/>
/// <reference path="../bower_components/DefinitelyTyped/requirejs/require.d.ts"/>
/// <reference path="jquery.fadebyscroll.d.ts"/>
/**
 * @summary JQuery plugin which applies a fade effect on an element according to the scroll position
 * @class
 * @author Cyril Schumacher
 * @version 1.1.0
 */
var FadeByScroll = (function () {
    /**
     * @summary Constructor.
     * @constructor
     * @public
     * @param {JQuery}              _element     Element.
     * @param {number}              _percentage  Percentage to which the animation is running.
     * @param {FadeByScrollOptions} _options     Options.
     */
    function FadeByScroll(_element, _percentage, _options) {
        var _this = this;
        this._element = _element;
        this._percentage = _percentage;
        this._options = _options;
        /**
         * @summary Appy fade effect on the element.
         * @private
         * @param {number} opacity Opacity of the element.
         */
        this._applyFadeEffect = function (opacity) {
            _this._options.element.css('opacity', opacity);
        };
        /**
         * @summary Compute opacity by scroll position and element.
         * @private
         * @param {number} scrollPosition   Position of scroll.
         * @param {number} positionByScroll Element position by scroll.
         */
        this._computeOpacityByScroll = function (scrollPosition, positionByScroll) {
            var opacity = _this._options.opacityMax;
            if (scrollPosition >= positionByScroll) {
                opacity = 1 - ((scrollPosition - positionByScroll) / positionByScroll);
            }
            return opacity;
        };
        /**
         * @summary Checks if the opacity value is in a defined interval.
         * @private
         * @param {number} opacity Opacity to check.
         */
        this._checkOpacityInterval = function (opacity) {
            return Math.min(Math.max(opacity, _this._options.opacityMin), _this._options.opacityMax);
        };
        /**
         * @summary Specifies the function to be called when the window is scrolled.
         * @private
         */
        this._onScroll = function () {
            // Obtains the position of scroll and
            // computes the position compared to position of scroll.
            var scrollPosition = $(window).scrollTop();
            var positionByScroll = (_this._element.height() * _this._percentage) / 100;
            // If the position of scroll exceeds the position, we update the opacity.
            var opacity = _this._computeOpacityByScroll(scrollPosition, positionByScroll);
            // Checks if it doesn't exceeds the minimum and maximum opacity value.
            opacity = _this._checkOpacityInterval(opacity);
            // Apply fade effect.
            _this._applyFadeEffect(opacity);
        };
        this._options = $.extend({ opacityMin: 0, opacityMax: 1, element: this._element.find('*') }, this._options);
        this._applyFadeEffect(this._options.opacityMax);
        $(window).scroll(this._onScroll);
    }
    /**
     * @summary Create a plugin instance.
     * @public
     * @param   {JQuery}                percentage  Percentage to which the animation is running.
     * @param   {FadeByScrollOptions}   options     Options.
     * @return  {object}                            Object that was iterated.
     */
    FadeByScroll.fadeByScroll = function (percentage, options) {
        var element = this;
        return element.each(function () {
            new FadeByScroll(element, percentage, options);
        });
    };
    return FadeByScroll;
})();
// Uses AMD or browser globals to create a jQuery plugin.
(function (factory) {
    if ((typeof define === 'function') && define.amd) {
        // AMD.
        define(['jquery'], factory);
    }
    else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {
    $.fn.fadeByScroll = FadeByScroll.fadeByScroll;
}));


text:
using System.ComponentModel.DataAnnotations;

namespace Umbraco.Cms.Core.PropertyEditors;

/// <summary>
///     Defines a value validator.
/// </summary>
public interface IValueValidator
{
    /// <summary>
    ///     Validates a value.
    /// </summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="valueType">The value type.</param>
    /// <param name="dataTypeConfiguration">A datatype configuration.</param>
    /// <returns>Validation results.</returns>
    /// <remarks>
    ///     <para>
    ///         The value can be a string, a Json structure (JObject, JArray...)... corresponding to what was posted by an
    ///         editor.
    ///     </para>
    /// </remarks>
    IEnumerable<ValidationResult> Validate(object? value, string? valueType, object? dataTypeConfiguration);
}


text:
@import Foundation;

#define BTUILocalizedString(KEY) [BTUILocalizedString KEY]

@interface BTUILocalizedString : NSObject

+ (NSString *)CARD_NUMBER_PLACEHOLDER;
+ (NSString *)CVV_FIELD_PLACEHOLDER;
+ (NSString *)EXPIRY_PLACEHOLDER_FOUR_DIGIT_YEAR;
+ (NSString *)EXPIRY_PLACEHOLDER_TWO_DIGIT_YEAR;
+ (NSString *)PAYPAL_CARD_BRAND;
+ (NSString *)POSTAL_CODE_PLACEHOLDER;
+ (NSString *)TOP_LEVEL_ERROR_ALERT_VIEW_OK_BUTTON_TEXT;

#pragma mark Card Brands

+ (NSString *)CARD_TYPE_AMERICAN_EXPRESS;
+ (NSString *)CARD_TYPE_DISCOVER;
+ (NSString *)CARD_TYPE_DINERS_CLUB;
+ (NSString *)CARD_TYPE_MASTER_CARD;
+ (NSString *)CARD_TYPE_VISA;
+ (NSString *)CARD_TYPE_JCB;
+ (NSString *)CARD_TYPE_MAESTRO;
+ (NSString *)CARD_TYPE_UNION_PAY;
+ (NSString *)CARD_TYPE_SWITCH;
+ (NSString *)CARD_TYPE_SOLO;
+ (NSString *)CARD_TYPE_LASER;
+ (NSString *)PAYMENT_METHOD_TYPE_PAYPAL;
@end


text:
<?php
/**
 * Wrapper around PDO to simplify using prepared statements.
 */

class Database {
   private static $me;

   public $pdo;
   private $dsn, $username, $password;

   private $is_connected;
   private $affected_rows;
   private $insert_id;
   private $last_error_retry_time;

   // Singleton
   public static function getDatabase() {
      if (is_null(self::$me)) {
         self::$me = new Database();
      }
      return self::$me;
   }

   public function __construct($dsn = null, $username = null, $password = null) {
      $this->dsn = $dsn ?: Config::get('db.dsn');
      $this->username = $username ?: @Config::get('db.username');
      $this->password = $password ?: @Config::get('db.password');
      $this->connect();
   }

   public function connect() {
      $this->pdo = new PDO($this->dsn, $this->username, $this->password, array(
         PDO::ATTR_PERSISTENT => true
      ));
      return ($this->is_connected = (bool)$this->pdo);
   }

   public function disconnect() {
      $this->pdo = null;
      $this->is_connected = false;
   }

   public function isConnected() {
      return $this->is_connected;
   }

   public function query($sql, $params = null, $types = null) {
      if (!$this->isConnected())
         return false;

      // Execute as a non-prepared statement if possible (for performance).
      if (is_null($params)) {
         if (!($stmt = $this->pdo->query($sql))) {
            $error = $this->pdo->errorInfo();
            trigger_error("Query failed: ({$error[0]}) " .
                          "{$error[2]}\n\n{$sql}\n\n");
            return false;
         }
         return $stmt;
      }

      // Prepare.
      if (!($stmt = $this->pdo->prepare($sql))) {
         $error = $this->pdo->errorInfo();
         trigger_error("Prepare failed: ({$error[0]}) " .
                       "{$error[2]}\n\n{$sql}\n\n");
         return false;
      }

      // Bind.
      $isAssociative = array_is_assoc($params);
      foreach ($params as $key => &$value) {
         $type = self::PDOType(@$types[$key]);
         $key = $isAssociative ? $key : $key + 1;
         if (!$stmt->bindParam($key, $value, $type)) {
            $error = $stmt->errorInfo();
            trigger_error("Binding parameters failed: ({$error[0]}) " .
                          "{$error[2]}\n\n{$sql}\n\n");
         }
      }

      // Execute.
      if (!$stmt->execute()) {
         list($sqlCode, $errCode, $errMsg) = $stmt->errorInfo();

         // If database connection was lost, reconnect and try again.
         // (max once per 30 seconds)
         if (strpos($errMsg, 'server has gone away') !== false ||
             strpos($errMsg, 'Error while sending QUERY packet') !== false) {
            $elapsed = time() - $this->last_error_retry_time;
            if ($elapsed > 30 && $this->connect()) {
               $this->last_error_retry_time = time();
               return $this->query($sql, $params, $types);
            }
         }

         trigger_error("Execute failed: ({$sqlCode}) [{$errCode}] " .
                       "{$errMsg}\n\n{$sql}\n\n");
      }

      $is_write = preg_match('/^ *(INSERT|UPDATE|REPLACE|DELETE)/i', $sql);
      if ($is_write) {
         $this->affected_rows = $stmt->rowCount();
         $this->insert_id = $this->pdo->lastInsertId();
      }

      return $stmt;
   }

   public function begin() {
     return $this->pdo->beginTransaction();
   }

   public function commit() {
     return $this->pdo->commit();
   }

   public function rollback() {
     return $this->pdo->rollBack();
   }

   public function affectedRows() {
      return $this->affected_rows;
   }

   public function insertId() {
      return $this->insert_id;
   }

   public function getValue($stmt) {
      return $stmt->fetchColumn();
   }

   public function getValues($stmt) {
      return $stmt->fetchAll(PDO::FETCH_COLUMN);
   }

   public function getAllAssoc($stmt, $key, $value = null) {
      $result = array();
      $rows = $this->getRows($stmt);
      foreach ($rows as $row) {
         $result[$row[$key]] = $value ? $row[$value] : $row;
      }
      return $result;
   }

   public function getRow($stmt) {
      return $stmt->fetch(PDO::FETCH_ASSOC);
   }

   public function getRows($stmt) {
      return $stmt->fetchAll(PDO::FETCH_ASSOC);
   }

   private function PDOType($char) {
      switch ($char) {
      case 'b': return PDO::PARAM_BOOL;
      case 'n': return PDO::PARAM_NULL;
      case 'i': return PDO::PARAM_INT;
      case 'l': return PDO::PARAM_LOB;
      case 's': default: return PDO::PARAM_STR;
      }
   }
}


text:
using System;
#if !TUNING
using System.Collections.Generic;
#endif
using System.IO;
#if !TUNING
using System.Linq;
#endif
using Renci.SshNet.Common;
using System.Globalization;
using Renci.SshNet.Sftp.Responses;
using System.Text;

namespace Renci.SshNet.Sftp
{
    internal abstract class SftpMessage : SshData
    {
        public static SftpMessage Load(uint protocolVersion, byte[] data, Encoding encoding)
        {
#if TUNING
            var messageType = (SftpMessageTypes) data[4]; // skip packet length bytes
#else
            var messageType = (SftpMessageTypes)data.FirstOrDefault();
#endif

            return Load(protocolVersion, data, messageType, encoding);
        }

        protected override int ZeroReaderIndex
        {
            get
            {
#if TUNING
                // 4 bytes for the length of the SFTP data
                // 1 byte for the SFTP message type
                return 5;
#else
                return 1;
#endif
            }
        }

#if TUNING
        /// <summary>
        /// Gets the size of the message in bytes.
        /// </summary>
        /// <value>
        /// The size of the messages in bytes.
        /// </value>
        protected override int BufferCapacity
        {
            get { return ZeroReaderIndex; }
        }
#endif

        public abstract SftpMessageTypes SftpMessageType { get; }

        protected override void LoadData()
        {
        }

        protected override void SaveData()
        {
            Write((byte) SftpMessageType);
        }

#if TUNING
        /// <summary>
        /// Writes the current message to the specified <see cref="SshDataStream"/>.
        /// </summary>
        /// <param name="stream">The <see cref="SshDataStream"/> to write the message to.</param>
        protected override void WriteBytes(SshDataStream stream)
        {
            const int sizeOfDataLengthBytes = 4;

            var startPosition = stream.Position;

            // skip 4 bytes for the length of the SFTP message data
            stream.Seek(sizeOfDataLengthBytes, SeekOrigin.Current);

            // write the SFTP message data to the stream
            base.WriteBytes(stream);

            // save where we were positioned when we finished writing the SSH message data
            var endPosition = stream.Position;

            // determine the length of the SSH message data
            var dataLength = endPosition - startPosition - sizeOfDataLengthBytes;

            // write the length of the SFTP message where we were positioned before we started
            // writing the SFTP message data
            stream.Position = startPosition;
            stream.Write((uint) dataLength);

            // move back to we were positioned when we finished writing the SFTP message data
            stream.Position = endPosition;
        }
#endif

        protected SftpFileAttributes ReadAttributes()
        {
#if TUNING
            return SftpFileAttributes.FromBytes(DataStream);
#else
            var flag = ReadUInt32();

            long size = -1;
            var userId = -1;
            var groupId = -1;
            uint permissions = 0;
            var accessTime = DateTime.MinValue;
            var modifyTime = DateTime.MinValue;
            IDictionary<string, string> extensions = null;

            if ((flag & 0x00000001) == 0x00000001)   //  SSH_FILEXFER_ATTR_SIZE
            {
                size = (long)ReadUInt64();
            }

            if ((flag & 0x00000002) == 0x00000002)   //  SSH_FILEXFER_ATTR_UIDGID
            {
                userId = (int)ReadUInt32();

                groupId = (int)ReadUInt32();
            }

            if ((flag & 0x00000004) == 0x00000004)   //  SSH_FILEXFER_ATTR_PERMISSIONS
            {
                permissions = ReadUInt32();
            }

            if ((flag & 0x00000008) == 0x00000008)   //  SSH_FILEXFER_ATTR_ACMODTIME
            {
                var time = ReadUInt32();
                accessTime = DateTime.FromFileTime((time + 11644473600) * 10000000);
                time = ReadUInt32();
                modifyTime = DateTime.FromFileTime((time + 11644473600) * 10000000);
            }

            if ((flag & 0x80000000) == 0x80000000)   //  SSH_FILEXFER_ATTR_ACMODTIME
            {
                var extendedCount = ReadUInt32();
                extensions = ReadExtensionPair();
            }
            var attributes = new SftpFileAttributes(accessTime, modifyTime, size, userId, groupId, permissions, extensions);

            return attributes;
#endif
        }

#if !TUNING
        protected void Write(SftpFileAttributes attributes)
        {
            if (attributes == null)
            {
                Write((uint)0);
                return;
            }

            UInt32 flag = 0;

            if (attributes.IsSizeChanged && attributes.IsRegularFile)
            {
                flag |= 0x00000001;
            }

            if (attributes.IsUserIdChanged|| attributes.IsGroupIdChanged)
            {
                flag |= 0x00000002;
            }

            if (attributes.IsPermissionsChanged)
            {
                flag |= 0x00000004;
            }

            if (attributes.IsLastAccessTimeChanged || attributes.IsLastWriteTimeChanged)
            {
                flag |= 0x00000008;
            }

            if (attributes.IsExtensionsChanged)
            {
                flag |= 0x80000000;
            }

            Write(flag);

            if (attributes.IsSizeChanged && attributes.IsRegularFile)
            {
                Write((UInt64)attributes.Size);
            }

            if (attributes.IsUserIdChanged|| attributes.IsGroupIdChanged)
            {
                Write((UInt32)attributes.UserId);
                Write((UInt32)attributes.GroupId);
            }

            if (attributes.IsPermissionsChanged)
            {
                Write(attributes.Permissions);
            }

            if (attributes.IsLastAccessTimeChanged || attributes.IsLastWriteTimeChanged)
            {
                var time = (uint)(attributes.LastAccessTime.ToFileTime() / 10000000 - 11644473600);
                Write(time);
                time = (uint)(attributes.LastWriteTime.ToFileTime() / 10000000 - 11644473600);
                Write(time);
            }

            if (attributes.IsExtensionsChanged)
            {
                Write(attributes.Extensions);
            }
        }
#endif

        private static SftpMessage Load(uint protocolVersion, byte[] data, SftpMessageTypes messageType, Encoding encoding)
        {
            SftpMessage message;

            switch (messageType)
            {
                case SftpMessageTypes.Version:
                    message = new SftpVersionResponse();
                    break;
                case SftpMessageTypes.Status:
                    message = new SftpStatusResponse(protocolVersion);
                    break;
                case SftpMessageTypes.Data:
                    message = new SftpDataResponse(protocolVersion);
                    break;
                case SftpMessageTypes.Handle:
                    message = new SftpHandleResponse(protocolVersion);
                    break;
                case SftpMessageTypes.Name:
                    message = new SftpNameResponse(protocolVersion, encoding);
                    break;
                case SftpMessageTypes.Attrs:
                    message = new SftpAttrsResponse(protocolVersion);
                    break;
                case SftpMessageTypes.ExtendedReply:
                    message = new SftpExtendedReplyResponse(protocolVersion);
                    break;
                default:
                    throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Message type '{0}' is not supported.", messageType));
            }

#if TUNING
            message.Load(data);
#else
            message.LoadBytes(data);

            message.ResetReader();

            message.LoadData();
#endif

            return message;
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.CurrentCulture, "SFTP Message : {0}", SftpMessageType);
        }
    }
}


text:
tf_chef_delivery CHANGELOG
==========================

This file is used to list changes made in each version of the Terraform plan.

v1.0.0 (2016-05-02)
-------------------
- [Brian Menges] - Add `accept_license` to handle Chef MLSA
- [Brian Menges] - Add `delivery_version` to install specific Delivery version. Default: `latest`
- [Brian Menges] - Add `root_volume_size` and `root_volume_type` variables to handle larger than default root volumes

v0.3.9 (2016-04-26)
-------------------
- [Brian Menges] - Missing double quote in delivery credentials file write resource

v0.3.8 (2016-04-26)
-------------------
- [Brian Menges] - Source data bag files contained trailing newline, using tr to remove

v0.3.7 (2016-04-26)
-------------------
- [Brian Menges] - Fix unterminated line in [outputs.tf](outputs.tf)

v0.3.6 (2016-04-26)
-------------------
- [Brian Menges] - Remove delivery data bag, leave keys data bag
- [Brian Menges] - Improve scripting and sed magic
- [Brian Menges] - Replace `credentials` with `credentials_file` in [outputs.tf](outputs.tf)

v0.3.5 (2016-04-25)
-------------------
- [Brian Menges] - Use `client_version`

v0.3.4 (2016-04-25)
-------------------
- [Brian Menges] - Can't set permissions to user that doesn't exist

v0.3.3 (2016-04-25)
-------------------
- [Brian Menges] - Add AWS provisioner

v0.3.2 (2016-04-25)
-------------------
- [Brian Menges] - Merge error, trying v0.3.1 again

v0.3.1 (2016-04-25)
-------------------
- [Brian Menges] - Add outputs `private_ip` and `public_ip`

v0.3.0 (2016-04-25)
-------------------
- [Brian Menges] - Documentation updates
- [Brian Menges] - Implemented `wait_on` dependency chain usage
- [Brian Menges] - Added variables `wait_on`, `log_to_file`, `public_ip`, `root_delete_termination`, `client_version`
- [Brian Menges] - Updated `main.tf` to use new variables
- [Brian Menges] - Updated HEREDOC style usage in plan
- [Brian Menges] - Updated `attributes-json.tpl` and added chef_client
- [Brian Menges] - Specify provider so that defaults can be overwritten

v0.2.2 (2016-03-23)
-------------------
- [Brian Menges] - Added handle for internal DNS on Route53
- [Brian Menges] - Added tag to aws_instance

v0.2.1 (2016-03-21)
-------------------
- [Brian Menges] - Code consistency update; align with other TF modules
- [Brian Menges] - Re-ordered several variables (alphabetize)
- [Brian Menges] - Update some comment lines
- [Brian Menges] - Fix databag issue (forgot to upload after creating)

v0.2.0 (2016-03-21)
-------------------
- [Brian Menges] - Re-wrote most of the code
- [Brian Menges] - Some formatting to make reading easier
- [Brian Menges] - Syntax updates for Terraform 0.6.14
- [Brian Menges] - Add Route53 controls
- [Brian Menges] - Add SSL certificate controls
- [Brian Menges] - Replace hostname computation from basename and count to just hostname and domain
- [Brian Menges] - Implement user and AMI mapping per [tf_chef_server](https://github.com/mengesb/tf_chef_server)
- [Brian Menges] - Remove specific IPTables handles, disabling IPTables or UFW globally
- [Brian Menges] - Better handle on delivery and keys databags
- [Brian Menges] - Provisioning using Chef provisioner and attributes_json
- [Brian Menges] - Using cookbooks at Chef server to govern system settings better than scripting EC2 variable hooks
- [Brian Menges] - Using templates instead of all HEREDOC
- [Brian Menges] - Doc and version updates

v0.1.5 (2016-02-16)
-------------------
- [Brian Menges] - Trimmed down some of the commands executed
- [Brian Menges] - Ordering
- [Brian Menges] - Broke down one long remote-exec to several based on task
- [Brian Menges] - Put only the files necessary where they need to go

v0.1.4 (2016-02-15)
-------------------
- [Brian Menges] - Putting it all back
- [Brian Menges] - Fixed the real problem; sourcing the right file!
- [Brian Menges] - Need to copy in delivery.pem to /etc/delivery still (cookbook requirement)

v0.1.3 (2016-02-15)
-------------------
- [Brian Menges] - Breaking out key generation

v0.1.2 (2016-02-15)
-------------------
- [Brian Menges] - Documentation cleanup and consisteny with other tf_chef works
- [Brian Menges] - More control around delivery user creation
- [Brian Menges] - Reordered some things
- [Brian Menges] - shortened some variables
- [Brian Menges] - Adjustments required as a result of tf_chef_server updates

v0.1.1 (2016-02-14)
-------------------
- [Brian Menges] - Fixing databag issues
- [Brian Menges] - Remove org from name tag
- [Brian Menges] - Adding security group rules between server and delivery

v0.1.0 (2016-02-11)
-------------------
- [Brian Menges] - Made delivery less directly dependent on tf_chef_server
- [Brian Menges] - Working now with encrpyted data bag 'keys' for builders (may move this)
- [Brian Menges] - Handles 'delivery' user creation @ chef server
- [Brian Menges] - Variable changes

v0.0.1 (2016-02-05)
-------------------
- [Brian Menges] - Create repo

- - -
Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown.

The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.


text:
package resource

import (
	"fmt"

	"github.com/fluxcd/flux/pkg/image"
	"github.com/fluxcd/flux/pkg/resource"
)

// Types that daemonsets, deployments, and other things have in
// common.

type ObjectMeta struct {
	Labels      map[string]string
	Annotations map[string]string
}

type PodTemplate struct {
	Metadata ObjectMeta
	Spec     PodSpec
}

func (t PodTemplate) Containers() []resource.Container {
	var result []resource.Container
	// FIXME(https://github.com/fluxcd/flux/issues/1269): account for possible errors (x2)
	for _, c := range t.Spec.Containers {
		im, _ := image.ParseRef(c.Image)
		result = append(result, resource.Container{Name: c.Name, Image: im})
	}
	for _, c := range t.Spec.InitContainers {
		im, _ := image.ParseRef(c.Image)
		result = append(result, resource.Container{Name: c.Name, Image: im})
	}
	return result
}

func (t PodTemplate) SetContainerImage(container string, ref image.Ref) error {
	for i, c := range t.Spec.Containers {
		if c.Name == container {
			t.Spec.Containers[i].Image = ref.String()
			return nil
		}
	}
	for i, c := range t.Spec.InitContainers {
		if c.Name == container {
			t.Spec.InitContainers[i].Image = ref.String()
			return nil
		}
	}
	return fmt.Errorf("container %q not found in workload", container)
}

type PodSpec struct {
	ImagePullSecrets []struct{ Name string }
	Volumes          []Volume
	Containers       []ContainerSpec
	InitContainers   []ContainerSpec `yaml:"initContainers"`
}

type Volume struct {
	Name   string
	Secret struct {
		SecretName string
	}
}

type ContainerSpec struct {
	Name  string
	Image string
	Args  Args
	Ports []ContainerPort
	Env   Env
}

type Args []string

type ContainerPort struct {
	ContainerPort int
	Name          string
}

type VolumeMount struct {
	Name      string
	MountPath string
	ReadOnly  bool
}

// Env is a bag of Name, Value pairs that are treated somewhat like a
// map.
type Env []EnvEntry

type EnvEntry struct {
	Name, Value string
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<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">

  <name>File Plugins</name>
  <groupId>io.cdap.cdap</groupId>
  <artifactId>file-plugins</artifactId>
  <version>3.0.0</version>
  <modelVersion>4.0.0</modelVersion>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
      <comments>A business-friendly OSS license</comments>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>CDAP</name>
      <email>cdap-dev@googlegroups.com</email>
      <organization>CDAP</organization>
      <organizationUrl>http://www.cdap.io</organizationUrl>
    </developer>
  </developers>

  <repositories>
       <repository>
      <id>snapshots</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>
    <repository>
      <id>sonatype</id>
      <url>https://oss.sonatype.org/content/groups/public</url>
    </repository>
  </repositories>
  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <app.parents>system:cdap-data-pipeline[6.0.0-SNAPSHOT,7.0.0-SNAPSHOT),system:cdap-data-streams[6.0.0-SNAPSHOT,7.0.0-SNAPSHOT)</app.parents>
    <cdap.version>6.0.0-SNAPSHOT</cdap.version>
    <hadoop.version>2.3.0</hadoop.version>
    <junit.version>4.11</junit.version>
    <guava.version>13.0.1</guava.version>
  </properties>

  <scm>
    <connection>scm:git:https://github.com/data-integrations/file.git</connection>
    <developerConnection>scm:git:git@github.com:data-integrations/file.git</developerConnection>
    <url>https://github.com/data-integrations/file.git</url>
    <tag>HEAD</tag>
  </scm>

  <issueManagement>
    <url>https://issues.cask.co/browse/CDAP</url>
  </issueManagement>

  <distributionManagement>
    <repository>
      <id>sonatype.release</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
    </repository>
    <snapshotRepository>
      <id>sonatype.snapshots</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <site>
      <id>cdap</id>
      <url>http://cdap.io</url>
    </site>
  </distributionManagement>

  <dependencies>
    <dependency>
      <groupId>io.cdap.cdap</groupId>
      <artifactId>cdap-api</artifactId>
      <version>${cdap.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>io.cdap.cdap</groupId>
      <artifactId>cdap-etl-api</artifactId>
      <version>${cdap.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>io.cdap.cdap</groupId>
      <artifactId>cdap-data-pipeline</artifactId>
      <version>${cdap.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>
    <dependency>

      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <version>${hadoop.version}</version>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
        <exclusion>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.avro</groupId>
          <artifactId>avro</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.zookeeper</groupId>
          <artifactId>zookeeper</artifactId>
        </exclusion>
        <exclusion>
          <artifactId>guava</artifactId>
          <groupId>com.google.guava</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jersey-core</artifactId>
          <groupId>com.sun.jersey</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jersey-json</artifactId>
          <groupId>com.sun.jersey</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jersey-server</artifactId>
          <groupId>com.sun.jersey</groupId>
        </exclusion>
        <exclusion>
          <artifactId>servlet-api</artifactId>
          <groupId>javax.servlet</groupId>
        </exclusion>
        <exclusion>
          <groupId>org.mortbay.jetty</groupId>
          <artifactId>jetty</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.mortbay.jetty</groupId>
          <artifactId>jetty-util</artifactId>
        </exclusion>
        <exclusion>
          <artifactId>jasper-compiler</artifactId>
          <groupId>tomcat</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jasper-runtime</artifactId>
          <groupId>tomcat</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jsp-api</artifactId>
          <groupId>javax.servlet.jsp</groupId>
        </exclusion>
        <exclusion>
          <artifactId>slf4j-api</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-mapreduce-client-core</artifactId>
      <version>${hadoop.version}</version>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.google.inject.extensions</groupId>
          <artifactId>guice-servlet</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-server</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-json</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.sun.jersey.contribs</groupId>
          <artifactId>jersey-guice</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.google.inject</groupId>
          <artifactId>guice</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>io.cdap.cdap</groupId>
      <artifactId>hydrator-test</artifactId>
      <version>${cdap.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-minicluster</artifactId>
      <version>${hadoop.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>3.3.0</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <_exportcontents>io.cdap.cdap.plugin.*;
              org.apache.commons.lang;org.apache.commons.logging.*;
              org.codehaus.jackson.*</_exportcontents>
            <Embed-Dependency>*;inline=false;scope=compile</Embed-Dependency>
            <Embed-Transitive>true</Embed-Transitive>
            <Embed-Directory>lib</Embed-Directory>
          </instructions>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>bundle</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>io.cdap</groupId>
        <artifactId>cdap-maven-plugin</artifactId>
        <version>1.1.0</version>
        <configuration>
          <cdapArtifacts>
            <parent>system:cdap-data-pipeline[6.0.0,7.0.0-SNAPSHOT)</parent>
            <parent>system:cdap-data-streams[6.0.0,7.0.0-SNAPSHOT)</parent>
          </cdapArtifacts>
        </configuration>
        <executions>
          <execution>
            <id>create-artifact-config</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>create-plugin-json</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>release</id>
      <build>
        <plugins>

          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>2.2.1</version>
            <configuration>
              <excludeResources>true</excludeResources>
            </configuration>
            <executions>
              <execution>
                <id>attach-sources</id>
                <phase>package</phase>
                <goals>
                  <goal>jar-no-fork</goal>
                </goals>
              </execution>
            </executions>
          </plugin>

          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.9.1</version>
            <configuration>
              <links>
                <link>http://download.oracle.com/javase/${jee.version}/docs/api/</link>
              </links>
              <doctitle>${project.name} ${project.version}</doctitle>
              <bottom>
                <![CDATA[Copyright © {currentYear} CDAP Licensed under the Apache License, Version 2.0.]]>
              </bottom>
            </configuration>
            <executions>
              <execution>
                <id>attach-javadoc</id>
                <phase>package</phase>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>

          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.5</version>
            <configuration>
              <passphrase>${gpg.passphrase}</passphrase>
              <useAgent>${gpg.useagent}</useAgent>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
/**
 * Created by bigbl on 12/14/2016.
 */
import { injectReducer } from '../../store/reducers';

export default (store) => ({
  path : 'creature-list',
  /*  Async getComponent is only invoked when route matches   */
  getComponent (nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
     and embed an async module loader (jsonp) when bundling   */
    require.ensure([], (require) => {
      /*  Webpack - use require callback to define
       dependencies for bundling   */
      const CreatureList = require('./containers/CreatureListContainer').default;
      const reducer = require('./modules/creatureList').default;

      /*  Add the reducer to the store on key 'counter'  */
      injectReducer(store, { key: 'creatureList', reducer });

      /*  Return getComponent   */
      cb(null, CreatureList);

      /* Webpack named bundle   */
    }, 'creatureList');
  }
});


text:
module Twilio
  module REST
    class Taskrouter < Domain
      class V1 < Version
        class WorkspaceContext < InstanceContext
          class EventList < ListResource
            ##
            # Initialize the EventList
            # @param [Version] version Version that contains the resource
            # @param [String] workspace_sid The sid
            # @return [EventList] EventList
            def initialize(version, workspace_sid: nil)
              super(version)

              # Path Solution
              @solution = {workspace_sid: workspace_sid}
              @uri = "/Workspaces/#{@solution[:workspace_sid]}/Events"
            end

            ##
            # Lists EventInstance records from the API as a list.
            # Unlike stream(), this operation is eager and will load `limit` records into
            # memory before returning.
            # @param [Time] end_date The end_date
            # @param [String] event_type The event_type
            # @param [String] minutes The minutes
            # @param [String] reservation_sid The reservation_sid
            # @param [Time] start_date The start_date
            # @param [String] task_queue_sid The task_queue_sid
            # @param [String] task_sid The task_sid
            # @param [String] worker_sid The worker_sid
            # @param [String] workflow_sid The workflow_sid
            # @param [Integer] limit Upper limit for the number of records to return. stream()
            #    guarantees to never return more than limit.  Default is no limit
            # @param [Integer] page_size Number of records to fetch per request, when
            #    not set will use the default value of 50 records.  If no page_size is defined
            #    but a limit is defined, stream() will attempt to read the limit with the most
            #    efficient page size, i.e. min(limit, 1000)
            # @return [Array] Array of up to limit results
            def list(end_date: :unset, event_type: :unset, minutes: :unset, reservation_sid: :unset, start_date: :unset, task_queue_sid: :unset, task_sid: :unset, worker_sid: :unset, workflow_sid: :unset, limit: nil, page_size: nil)
              self.stream(
                  end_date: end_date,
                  event_type: event_type,
                  minutes: minutes,
                  reservation_sid: reservation_sid,
                  start_date: start_date,
                  task_queue_sid: task_queue_sid,
                  task_sid: task_sid,
                  worker_sid: worker_sid,
                  workflow_sid: workflow_sid,
                  limit: limit,
                  page_size: page_size
              ).entries
            end

            ##
            # Streams EventInstance records from the API as an Enumerable.
            # This operation lazily loads records as efficiently as possible until the limit
            # is reached.
            # @param [Time] end_date The end_date
            # @param [String] event_type The event_type
            # @param [String] minutes The minutes
            # @param [String] reservation_sid The reservation_sid
            # @param [Time] start_date The start_date
            # @param [String] task_queue_sid The task_queue_sid
            # @param [String] task_sid The task_sid
            # @param [String] worker_sid The worker_sid
            # @param [String] workflow_sid The workflow_sid
            # @param [Integer] limit Upper limit for the number of records to return. stream()
            #    guarantees to never return more than limit. Default is no limit.
            # @param [Integer] page_size Number of records to fetch per request, when
            #    not set will use the default value of 50 records. If no page_size is defined
            #    but a limit is defined, stream() will attempt to read the limit with the most
            #    efficient page size, i.e. min(limit, 1000)
            # @return [Enumerable] Enumerable that will yield up to limit results
            def stream(end_date: :unset, event_type: :unset, minutes: :unset, reservation_sid: :unset, start_date: :unset, task_queue_sid: :unset, task_sid: :unset, worker_sid: :unset, workflow_sid: :unset, limit: nil, page_size: nil)
              limits = @version.read_limits(limit, page_size)

              page = self.page(
                  end_date: end_date,
                  event_type: event_type,
                  minutes: minutes,
                  reservation_sid: reservation_sid,
                  start_date: start_date,
                  task_queue_sid: task_queue_sid,
                  task_sid: task_sid,
                  worker_sid: worker_sid,
                  workflow_sid: workflow_sid,
                  page_size: limits[:page_size],
              )

              @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
            end

            ##
            # When passed a block, yields EventInstance records from the API.
            # This operation lazily loads records as efficiently as possible until the limit
            # is reached.
            def each
              limits = @version.read_limits

              page = self.page(page_size: limits[:page_size],)

              @version.stream(page,
                              limit: limits[:limit],
                              page_limit: limits[:page_limit]).each {|x| yield x}
            end

            ##
            # Retrieve a single page of EventInstance records from the API.
            # Request is executed immediately.
            # @param [Time] end_date The end_date
            # @param [String] event_type The event_type
            # @param [String] minutes The minutes
            # @param [String] reservation_sid The reservation_sid
            # @param [Time] start_date The start_date
            # @param [String] task_queue_sid The task_queue_sid
            # @param [String] task_sid The task_sid
            # @param [String] worker_sid The worker_sid
            # @param [String] workflow_sid The workflow_sid
            # @param [String] page_token PageToken provided by the API
            # @param [Integer] page_number Page Number, this value is simply for client state
            # @param [Integer] page_size Number of records to return, defaults to 50
            # @return [Page] Page of EventInstance
            def page(end_date: :unset, event_type: :unset, minutes: :unset, reservation_sid: :unset, start_date: :unset, task_queue_sid: :unset, task_sid: :unset, worker_sid: :unset, workflow_sid: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
              params = Twilio::Values.of({
                  'EndDate' => Twilio.serialize_iso8601_datetime(end_date),
                  'EventType' => event_type,
                  'Minutes' => minutes,
                  'ReservationSid' => reservation_sid,
                  'StartDate' => Twilio.serialize_iso8601_datetime(start_date),
                  'TaskQueueSid' => task_queue_sid,
                  'TaskSid' => task_sid,
                  'WorkerSid' => worker_sid,
                  'WorkflowSid' => workflow_sid,
                  'PageToken' => page_token,
                  'Page' => page_number,
                  'PageSize' => page_size,
              })
              response = @version.page(
                  'GET',
                  @uri,
                  params
              )
              EventPage.new(@version, response, @solution)
            end

            ##
            # Retrieve a single page of EventInstance records from the API.
            # Request is executed immediately.
            # @param [String] target_url API-generated URL for the requested results page
            # @return [Page] Page of EventInstance
            def get_page(target_url)
              response = @version.domain.request(
                  'GET',
                  target_url
              )
              EventPage.new(@version, response, @solution)
            end

            ##
            # Provide a user friendly representation
            def to_s
              '#<Twilio.Taskrouter.V1.EventList>'
            end
          end

          class EventPage < Page
            ##
            # Initialize the EventPage
            # @param [Version] version Version that contains the resource
            # @param [Response] response Response from the API
            # @param [Hash] solution Path solution for the resource
            # @return [EventPage] EventPage
            def initialize(version, response, solution)
              super(version, response)

              # Path Solution
              @solution = solution
            end

            ##
            # Build an instance of EventInstance
            # @param [Hash] payload Payload response from the API
            # @return [EventInstance] EventInstance
            def get_instance(payload)
              EventInstance.new(@version, payload, workspace_sid: @solution[:workspace_sid],)
            end

            ##
            # Provide a user friendly representation
            def to_s
              '<Twilio.Taskrouter.V1.EventPage>'
            end
          end

          class EventContext < InstanceContext
            ##
            # Initialize the EventContext
            # @param [Version] version Version that contains the resource
            # @param [String] workspace_sid The workspace_sid
            # @param [String] sid The sid
            # @return [EventContext] EventContext
            def initialize(version, workspace_sid, sid)
              super(version)

              # Path Solution
              @solution = {workspace_sid: workspace_sid, sid: sid,}
              @uri = "/Workspaces/#{@solution[:workspace_sid]}/Events/#{@solution[:sid]}"
            end

            ##
            # Fetch a EventInstance
            # @return [EventInstance] Fetched EventInstance
            def fetch
              params = Twilio::Values.of({})

              payload = @version.fetch(
                  'GET',
                  @uri,
                  params,
              )

              EventInstance.new(@version, payload, workspace_sid: @solution[:workspace_sid], sid: @solution[:sid],)
            end

            ##
            # Provide a user friendly representation
            def to_s
              context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
              "#<Twilio.Taskrouter.V1.EventContext #{context}>"
            end
          end

          class EventInstance < InstanceResource
            ##
            # Initialize the EventInstance
            # @param [Version] version Version that contains the resource
            # @param [Hash] payload payload that contains response from Twilio
            # @param [String] workspace_sid The sid
            # @param [String] sid The sid
            # @return [EventInstance] EventInstance
            def initialize(version, payload, workspace_sid: nil, sid: nil)
              super(version)

              # Marshaled Properties
              @properties = {
                  'account_sid' => payload['account_sid'],
                  'actor_sid' => payload['actor_sid'],
                  'actor_type' => payload['actor_type'],
                  'actor_url' => payload['actor_url'],
                  'description' => payload['description'],
                  'event_data' => payload['event_data'],
                  'event_date' => Twilio.deserialize_iso8601_datetime(payload['event_date']),
                  'event_type' => payload['event_type'],
                  'resource_sid' => payload['resource_sid'],
                  'resource_type' => payload['resource_type'],
                  'resource_url' => payload['resource_url'],
                  'sid' => payload['sid'],
                  'source' => payload['source'],
                  'source_ip_address' => payload['source_ip_address'],
                  'url' => payload['url'],
              }

              # Context
              @instance_context = nil
              @params = {'workspace_sid' => workspace_sid, 'sid' => sid || @properties['sid'],}
            end

            ##
            # Generate an instance context for the instance, the context is capable of
            # performing various actions.  All instance actions are proxied to the context
            # @return [EventContext] EventContext for this EventInstance
            def context
              unless @instance_context
                @instance_context = EventContext.new(@version, @params['workspace_sid'], @params['sid'],)
              end
              @instance_context
            end

            ##
            # @return [String] The account_sid
            def account_sid
              @properties['account_sid']
            end

            ##
            # @return [String] The actor_sid
            def actor_sid
              @properties['actor_sid']
            end

            ##
            # @return [String] The actor_type
            def actor_type
              @properties['actor_type']
            end

            ##
            # @return [String] The actor_url
            def actor_url
              @properties['actor_url']
            end

            ##
            # @return [String] The description
            def description
              @properties['description']
            end

            ##
            # @return [String] The event_data
            def event_data
              @properties['event_data']
            end

            ##
            # @return [Time] The event_date
            def event_date
              @properties['event_date']
            end

            ##
            # @return [String] The event_type
            def event_type
              @properties['event_type']
            end

            ##
            # @return [String] The resource_sid
            def resource_sid
              @properties['resource_sid']
            end

            ##
            # @return [String] The resource_type
            def resource_type
              @properties['resource_type']
            end

            ##
            # @return [String] The resource_url
            def resource_url
              @properties['resource_url']
            end

            ##
            # @return [String] The sid
            def sid
              @properties['sid']
            end

            ##
            # @return [String] The source
            def source
              @properties['source']
            end

            ##
            # @return [String] The source_ip_address
            def source_ip_address
              @properties['source_ip_address']
            end

            ##
            # @return [String] The url
            def url
              @properties['url']
            end

            ##
            # Fetch a EventInstance
            # @return [EventInstance] Fetched EventInstance
            def fetch
              context.fetch
            end

            ##
            # Provide a user friendly representation
            def to_s
              values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
              "<Twilio.Taskrouter.V1.EventInstance #{values}>"
            end

            ##
            # Provide a detailed, user friendly representation
            def inspect
              values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
              "<Twilio.Taskrouter.V1.EventInstance #{values}>"
            end
          end
        end
      end
    end
  end
end


text:
package org.vash.vate.nativeutils;

import com.sun.jna.Native;

public class VTMinimalNativeUtils implements VTNativeUtilsImplementation
{
  private VTMinimalCLibrary cLibray = (VTMinimalCLibrary) Native.load("c", VTMinimalCLibrary.class);

  public int system(String command)
  {
    return cLibray.system(command);
  }

  public int getchar()
  {
    return cLibray.getchar();
  }

  public void printf(String format, Object... args)
  {
    cLibray.printf(format, args);
  }

  /* public boolean beep(int freq, int dur) { return false; } */

  public boolean beep(int freq, int dur, boolean block)
  {
    return false;
  }

  public boolean openCD()
  {
    return false;
  }

  public boolean closeCD()
  {
    return false;
  }

  public void exit(int status)
  {
    cLibray.exit(status);
  }

  public void abort()
  {
    cLibray.abort();
  }

  public int raise(int signal)
  {
    return cLibray.raise(signal);
  }

  public int rand()
  {
    return cLibray.rand();
  }

  public void srand(int seed)
  {
    cLibray.srand(seed);
  }

  public String getenv(String env)
  {
    return cLibray.getenv(env);
  }

  public int putenv(String env)
  {
    return cLibray.putenv(env);
  }

  public int getpid()
  {
    return 0;
  }

  public int isatty(int fd)
  {
    return cLibray.isatty(fd);
  }

  public boolean detachConsole()
  {
    return false;
  }

  public boolean attachConsole()
  {
    return false;
  }

  public boolean hideConsole()
  {
    return false;
  }

  public int getch()
  {
    return getchar();
  }

  public void unbuffered()
  {
    try
    {
      Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "stty -icanon min 1 < /dev/tty" });
    }
    catch (Throwable t)
    {

    }
  }

  public void noecho()
  {
    try
    {
      Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "stty -echo < /dev/tty" });
    }
    catch (Throwable t)
    {

    }
  }

  public void normal()
  {
    try
    {
      Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "stty icanon echo < /dev/tty" });
    }
    catch (Throwable t)
    {

    }
  }

  public boolean checkANSI()
  {
    if (isatty(0) != 0 && isatty(1) != 0)
    {
      return true;
    }
    return false;
  }

  /* public int true_putenv(String env) { return cLibray.putenv(env); } */
}


text:
<?php

require(__DIR__."/../vendor/autoload.php");

use PHPUnit\Framework\TestCase;

////////////////////
/// Setup Aliasing
////////////////////

use Simnang\LoanPro\Constants\FILE_ATTACHMENT as FILE_ATTACHMENT,
    Simnang\LoanPro\Constants\BASE_ENTITY as BASE_ENTITY
    ;

////////////////////
/// Done Setting Up Aliasing
////////////////////

class FileAttachmentTest extends TestCase
{
    public static function setUpBeforeClass(){
        \Simnang\LoanPro\BaseEntity::SetStrictMode(true);
    }
    /**
     * @group create_correctness
     * @group offline
     */
    public function testFileAttachmentInstantiate(){
        // FileAttachments aren't exposed via LoanProSDK since they are saved and operated on differently
        $doc = new \Simnang\LoanPro\Loans\FileAttachmentEntity();

        $rclass = new \ReflectionClass('Simnang\LoanPro\Constants\FILE_ATTACHMENT');
        $consts = $rclass->getConstants();

        // make sure every other field is null
        foreach($consts as $key=>$field){
            $this->assertNull(null,$doc->Get($field));
        }
    }

    /**
     * @group set_correctness
     * @group offline
     */
    public function testLoanCannotSetNull(){
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Value for 'fileMime' is null. The 'Set' function Cannot unset items, please use 'Rem' instead for class Simnang\\LoanPro\\Loans\\FileAttachmentEntity");
        (new \Simnang\LoanPro\Loans\FileAttachmentEntity())
            /* should throw exception when setting LOAN_AMT to null */ ->Set(FILE_ATTACHMENT::FILE_MIME, null);
    }

    /**
     * @group set_correctness
     * @group offline
     */
    public function testLoanCheckValidProp(){
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid property \''.\Simnang\LoanPro\Constants\LOAN_SETUP::AMT_DOWN.'\'');
        $ls = (new \Simnang\LoanPro\Loans\FileAttachmentEntity());
        $ls->Set(BASE_ENTITY::ID, 120);

        /* should throw exception when setting AGENT to null */
        $ls->Set(\Simnang\LoanPro\Constants\LOAN_SETUP::AMT_DOWN, 1280.32);
    }

    /**
     * @group del_correctness
     * @group offline
     */
    public function testFileAttachmentDel(){
        $doc = (new \Simnang\LoanPro\Loans\FileAttachmentEntity())->Set([FILE_ATTACHMENT::FILE_MIME=> 1]);
        $this->assertEquals(1, $doc->Get(FILE_ATTACHMENT::FILE_MIME));
        /* deletions should have 'get' return 'null' */
        $this->assertNull($doc->Rem(FILE_ATTACHMENT::FILE_MIME)->Get(FILE_ATTACHMENT::FILE_MIME));
        /* deletions should also not affect the original object (just return a copy) */
        $this->assertEquals(1, $doc->Get(FILE_ATTACHMENT::FILE_MIME));
    }
}


text:
package csrf

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/securecookie"
)

// Check store implementations
var _ store = &cookieStore{}

// brokenSaveStore is a CSRF store that cannot, well, save.
type brokenSaveStore struct {
	store
}

func (bs *brokenSaveStore) Get(*http.Request) ([]byte, error) {
	// Generate an invalid token so we can progress to our Save method
	return generateRandomBytes(24)
}

func (bs *brokenSaveStore) Save(realToken []byte, w http.ResponseWriter) error {
	return errors.New("test error")
}

// Tests for failure if the middleware can't save to the Store.
func TestStoreCannotSave(t *testing.T) {
	s := http.NewServeMux()
	bs := &brokenSaveStore{}
	s.HandleFunc("/", testHandler)
	p := Protect(testKey, setStore(bs))(s)

	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	rr := httptest.NewRecorder()
	p.ServeHTTP(rr, r)

	if rr.Code != http.StatusForbidden {
		t.Fatalf("broken store did not set an error status: got %v want %v",
			rr.Code, http.StatusForbidden)
	}

	if c := rr.Header().Get("Set-Cookie"); c != "" {
		t.Fatalf("broken store incorrectly set a cookie: got %v want %v",
			c, "")
	}

}

// TestCookieDecode tests that an invalid cookie store returns a decoding error.
func TestCookieDecode(t *testing.T) {
	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	var age = 3600

	// Test with a nil hash key
	sc := securecookie.New(nil, nil)
	sc.MaxAge(age)
	st := &cookieStore{cookieName, age, true, true, sc}

	// Set a fake cookie value so r.Cookie passes.
	r.Header.Set("Cookie", fmt.Sprintf("%s=%s", cookieName, "notacookie"))

	_, err = st.Get(r)
	if err == nil {
		t.Fatal("cookiestore did not report an invalid hashkey on decode")
	}
}

// TestCookieEncode tests that an invalid cookie store returns an encoding error.
func TestCookieEncode(t *testing.T) {
	var age = 3600

	// Test with a nil hash key
	sc := securecookie.New(nil, nil)
	sc.MaxAge(age)
	st := &cookieStore{cookieName, age, true, true, sc}

	rr := httptest.NewRecorder()

	err := st.Save(nil, rr)
	if err == nil {
		t.Fatal("cookiestore did not report an invalid hashkey on encode")
	}
}


text:
class AddQuotaColumnToEvent < ActiveRecord::Migration[5.1]
  def change
    add_column :events, :quota, :integer, null: false
  end
end


text:
(function($, Backbone, _, App){

    App.view.CombinedForm = App.View.extend({
        manyToManyFields : [], readOnly : false,
        select2Els : [],
        datePickers : [],
        typeAheadFields : [],
        events : { //TODO
            "submit form" : "ignoreSubmit",
            "click .buttons .btn" : "submitForm"
        },
        remove: function() {
            _.each(this.datePickers, function(view) {
                view.remove()
            });
            _.each(this.typeAheadFields, function(view) { view.remove()});
            _.each(this.select2Els, function(elem){
                var $select2 = this.$(elem);
                if($select2) $select2.select2("destroy");
            }, this);
            return App.View.prototype.remove.apply(this, arguments);
        },
        ignoreSubmit : function() {
            var $btn = this.$(".buttons .btn:focus");
            if($btn && $btn.data("nojs")) {
                return true;
            }
            App.logDebug("ignoreSubmit");
            return false;
        },
        submitForm : function(evt) {
            var $btn = $(evt.currentTarget);
            $btn.attr('disabled','disabled');
            if($btn.data("nojs")) {
                var $form = $btn.closest("form");
                if($btn.data("url")) {
                    $form.attr("action", $btn.data("url"));
                }
                $form.submit();
                $btn.removeAttr('disabled');
                return false;
            }
            var form = this.serializeForm();
            var actionUrl = $btn.data("url") || form.action;
            App.logDebug("actionUrl " + actionUrl +", action " + $btn.data("action"));
            if($btn.data("action") && actionUrl) { // not yet tested, must alter the UI
                // e.g. <button data-action="showDialogBeforeSubmit" ... then define the customActions in App.view.TableFormTabs
                this.publishEvt("form:action:"+ $btn.data("action"),
                    { url : actionUrl, form : form});
            } else {
                App.logErr("Must set data-action and/or data-url in the button ");
            }
            $btn.removeAttr('disabled');
            return false;
        },
        serializeForm : function(form) {
            var $form = form ? $(form) : this.$("form:first");
            var formData = this.getFormDataWithFilter($form, function(k) { return $.trim(k.value) != ""; });

            if(!formData.action) {
                formData.action = $form.attr('action');
            }
            return formData;
        },
        getFormDataWithFilter : function($form, filterCallback) {
            var formData = {};
            _($form.serializeArray().filter(filterCallback)).each(function (nvp) {
                formData[nvp.name] = nvp.value;
            });
            return formData;
        },
        initialize: function(opt) {
            this.formId = opt.formId;
            this.readOnly = opt.readOnly || this.readOnly;
            this.setupDatePickerFields();
            this.setupTypeAheadFields();
            this.setupSelect2(this.readOnly);
//            this.setupManyToManyFields(this.readOnly);
        },
        setupDatePickerFields : function(parentEl) {
            var $datePickers = parentEl == undefined ? this.$(".date") : this.$(parentEl + " .date");
            _.each($datePickers, function(elem){
                var dpEl = this.$el.selector + " #" + elem.id;
                if($(dpEl).data('readonly') != "true") { // add this checking. TODO: verify
                    this.datePickers.push(new App.view.DatePicker({ el : dpEl, pubSub : this.pubSub}));
                }
            }, this);
        },
        setupTypeAheadFields : function(parentEl) {
            var $typeAhead = parentEl == undefined ? this.$(".type-ahead") : this.$(parentEl + " .type-ahead");
            _.each($typeAhead, function(elem){
                var dpEl = this.$el.selector + " #" + elem.id;
//                App.logDebug("setup type ahead dpEl:"+ dpEl);
                if($(dpEl).data('readonly') != "true") { // add this checking. TODO: verify
                    this.typeAheadFields.push(new App.view.TypeAhead({ el : dpEl, pubSub : this.pubSub}));
                }
            }, this);
        },
        setupSelect2 : function(readOnly, parentEl) {
            var $select2Simples = parentEl == undefined ? this.$(".select2-simple") : this.$(parentEl + " .select2-simple");
            _.each($select2Simples, function(elem){
                var mmEl = this.$el.selector + " #" + elem.id;
                var $mmEl = $(mmEl);
                var isReadOnly = readOnly || ($mmEl.attr("readonly"));
                var $select2 = $mmEl.select2();
                if(isReadOnly) {
                    $select2.select2("readonly", true);
                }
                this.select2Els.push(mmEl);
            }, this);
            var $select2Remotes = parentEl == undefined ? this.$(".select2-remote") : this.$(parentEl + " .select2-remote");
            _.each($select2Remotes, function(elem){
                var mmEl = this.$el.selector + " #" + elem.id;
                var $mmEl = $(mmEl);
                var isReadOnly = readOnly || ($mmEl.attr("readonly")) || $mmEl.data("readonly");
                var domainId = $mmEl.data("id"), domainName = $mmEl.data("from"), initUrl = $mmEl.data("initurl"), dataType = $mmEl.data("datatype") || "json";
                var formatResult = App.template.select2.formatResult[$mmEl.data("resulttmpl") || domainName] || function(state) { return state.text; };
                var formatSelection = App.template.select2.formatSelection[$mmEl.data("selectiontmpl")] || formatResult;
                var multiple = $mmEl.data("multiple") == "yes";
                var select2Opts = {
                    placeholder : $mmEl.data("placeholder") || "search item",
                    minimumInputLength: 1,
                    ajax : {
                        url : App.url + "/typeAhead/" + domainName,
                        dataType : dataType,
                        data : function(term, page) { return { query: term } },
                        results : function(data, page) {
                            return { results : data };
                        }
                    },
                    multiple : multiple,
                    formatResult: formatResult, // omitted for brevity, see the source of this page
                    formatSelection: formatSelection,  // omitted for brevity, see the source of this page
                    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
                    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
                };
                if(!multiple) {
                    select2Opts.initSelection = function(element, callback) {
                        App.logDebug("initSelection , domainId " + domainId);
                        if(domainId) {
                            App.logDebug("init debug. call " + initUrl);
                            $.ajax(initUrl, {data : {id : domainId}, dataType: dataType}).done(function(data) { callback(data); });
                        }
                    }
                }
                if(multiple && domainId) {
                    var renderDataCallback = (function($mmEl){
                        return function(data) {
                            $mmEl.select2("data", data);
                        };
                    })($mmEl);
                    App.logDebug("load initial data");
                    $.ajax(initUrl, {data : {id : domainId}, dataType: dataType}).done(renderDataCallback);
                }
                var $select2 = $mmEl.select2(select2Opts);
                if(isReadOnly) $select2.select2("readonly", true);
                this.select2Els.push(mmEl);
            }, this);
        }
//        ,
//        setupManyToManyFields : function(readOnly) {
//            //might be set as deprecated
//            _.each(this.$(".many-to-many"), function(elem){
//                var mmEl = this.$el.selector + " #" + elem.id; // so many-to-many element must have ID
//                this.manyToManyFields.push(new App.view.ManyToManyView({ el : mmEl, pubSub : this.pubSub, readOnly : readOnly}));
//            }, this);
//
//        }
    });

    App.view.CombinedFormWithEmbeddedTable = App.view.CombinedForm.extend({
        addEmbeddedTableRow : function(tablePrefix, relativeUrl) { // #labors
            var $table = this.$(tablePrefix + "-table");
            var i = $table.find("tbody tr").length - 1;
            var newRowEl = tablePrefix + i; // this should match _shift.gsp
            var $lastRow = $table.find("tbody tr:eq("+ i +")");
            App.logDebug("add "+ tablePrefix + " row "+ i);
            this.getHtml(App.url + relativeUrl, {i : i}, function(row) {
                $lastRow.before(row);
                this.setupTypeAheadFields(newRowEl);
                this.setupDatePickerFields(newRowEl);
                this.setupSelect2(this.readOnly, newRowEl);
            } );
        },
        deleteRow : function(e) {
            App.logDebug(" delete row ");
            $(e.currentTarget).closest("tr").remove();
        },
        getHtml : function(url, option, callback) {
            return $.ajax({
                type: "GET",
                url: url,
                data: option || {},
                success: callback || function(){},
                context : this // make sure this BB view is the context
            });
        }
    });

})(jQuery, Backbone, _, App);


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitd6aeb4ce95d12d546036438d534e4dac::getLoader();


text:
package org.neo4j.graphdb.traversal;

import org.neo4j.graphdb.PathExpander;

/**
 * A catalog of convenient branch ordering policies.
 *
 * Copied from kernel package so that we can hide kernel from the public API.
 */
public enum BranchOrderingPolicies implements BranchOrderingPolicy
{
    PREORDER_DEPTH_FIRST
    {
        public BranchSelector create( TraversalBranch startSource, PathExpander expander )
        {
            return new PreorderDepthFirstSelector( startSource, expander );
        }
    },
    POSTORDER_DEPTH_FIRST
    {
        public BranchSelector create( TraversalBranch startSource, PathExpander expander )
        {
            return new PostorderDepthFirstSelector( startSource, expander );
        }
    },
    PREORDER_BREADTH_FIRST
    {
        public BranchSelector create( TraversalBranch startSource, PathExpander expander )
        {
            return new PreorderBreadthFirstSelector( startSource, expander );
        }
    },
    POSTORDER_BREADTH_FIRST
    {
        public BranchSelector create( TraversalBranch startSource, PathExpander expander )
        {
            return new PostorderBreadthFirstSelector( startSource, expander );
        }
    };
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Soc. cient. argent. 12(4): 177 (1881)

#### Original name
Scutellum paradoxum Speg.

### Remarks
null