text:
from xml.etree import ElementTree
from lxml import etree

class migrate_view():

    '''
    Migrate architecture view to use it in the verision 7
    '''

    def __init__(self, l_file=None):
        '''
        Maiker to init path with the xml files
        @param l_file List with xml file path
        '''

        self.files = l_file and type(l_file) is list and l_file or l_file \
            and [l_file]

    def change_xpath(self, xml_f):
        '''
        Change the path from xpath using the relative rute
        @param xml_f Type Object xpath from lxml.tree library
        '''
        xpath_list = xml_f.xpath('//xpath')
        if xpath_list:
            for xpaths in xpath_list:
                expr = xpaths.attrib.get('expr', False)
                if expr:
                    m = '//' in expr and expr or  expr.split('/') and \
                        '//%s' % expr.split('/')[-1]
                    xpaths.set('expr', m)

        return True

    def remove_depreciated(self, xml_o):
        '''
        Remove depreceated methos in the architecture view
        @param xml_o Type Object xpath from lxml.tree library

        '''
        types = xml_o.xpath('//field[@name="type"]')
        if types:
            for line in types:
                parent = line.getparent()
                parent.remove(line)
        types = xml_o.xpath('//field[@mode]')
        if types:
            for line in types:
                line.attrib.get('mode', False) and \
                    line.attrib.pop('mode')

        return True

    def version_7(self, xml_o):
        '''
        Add Version 7 in tags form
        @param xml_o Type Object xpath from lxml.tree library

        '''
        x = xml_o.xpath('//form')
        if x:
            for i in x:
                i.set('version', '7.0')

        return True

    def get_attr(self, xml_f, xpaths, attrb):
        '''
        Send the attribute in the specification tag
        @param xml_f Type Object xpath from lxml.tree library
        @param xpaths Point of search
        @param attrb Attribute to return
        '''
        xpath_list = xml_f.xpath('//%s' % xpaths)
        expr = []
        if xpath_list:
            for xpaths in xpath_list:
                for i in xpaths.getchildren():

                    expr.append((i.tag, i.attrib.items()))

        return expr

    def search_model(self, l_files, t_search='model', mo_list=None):
        '''
        Search model in view to show if module or module  was
        changed or deleted
        @param l_files List with file path xml
        @param t_search Type search, in this field you can search if the views
        are inherit with some module or model
                        'model' Only search model in the view
                        'module' Only search modules in the view
                        'all' Search model and modules that are inside mo_list
        '''

        l_files = self.files or l_files and type(l_files) is list or \
            l_files and [l_files]

        for files in mo_list and l_files or []:

            filex = open(files)
            tree = etree.parse(filex)
            read = tree.xpath('//record[@model="ir.ui.view"]')
            xpaths_list = []
            for line in read:
                inherit = t_search.lower() in ('module', 'all') and \
                    line.xpath('//field[@name="inherit_id"]') or\
                    []

                for tags in inherit:
                    name = tags.attrib.get('ref', False)
                    name = name and name.split('.')
                    name = name and name[0]
                    if name in mo_list:
                        filex.close()
                        return self.get_attr(line, 'xpath', 'expr')

                model = t_search.lower() in ('model', 'all') and \
                    line.xpath('//field[@name="model"]') or\
                    []

                for tags in model:
                    name = tags.text
                    if name in mo_list:
                        filex.close()
                        return self.get_attr(line, 'xpath', 'expr')

            filex.close()
            return False

    def modify_arch(self, l_files, types='a'):
        '''
        Modifie architecture view to use in openerp V7
        Remove depreciate values and add version description view
        @param l_files List with file path xml
        @param types Type change
               'a' Change all include xpath rute with relative way
               't' Basicaly change to work with V7 standard
               'x' Only change xpath route to use the realative way
        '''
        l_files = self.files or l_files and type(l_files) is list or \
            l_files and [l_files]

        for files in l_files:

            filex = open(files)
            tree = etree.parse(filex)
            read = tree.xpath('//record[@model="ir.ui.view"]')
            for line in read:
                inherit = types in ('a', 'x') and \
                    line.xpath('//field[@name="inherit_id"]')

                inherit and line.xpath('//xpath') and self.change_xpath(line)

                line.xpath('//field[@name="type"]') and \
                    self.remove_depreciated(line)
                line.xpath('//form') and self.version_7(line)

            out = open('%s' % files, 'w')
            tree.write(out, xml_declaration=True, encoding='UTF-8')
            out.close()

            return True


text:
<?xml version="1.0"?>

<!-- The most complicated edit mode ever, for plain text mode -->

<!DOCTYPE MODE SYSTEM "xmode.dtd">

<MODE>
	<RULES>
		<TERMINATE AT_CHAR="0" />
	</RULES>
</MODE>

redpajama_set_name: RedPajamaGithub


text:
import { connect } from 'react-redux';
import FilterGroupModal from 'filters/components/FilterGroupModal';
import { LAYER_TYPES, FLAG_FILTER_GROUP_VALUES } from 'constants';
import {
  saveFilterGroup,
  setFilterGroupModalVisibility
} from 'filters/filterGroupsActions';

const mapStateToProps = (state) => {
  const currentlyEditedFilterGroup = state.filterGroups.currentlyEditedFilterGroup;
  const filterValuesKeys = currentlyEditedFilterGroup && Object.keys(currentlyEditedFilterGroup.filterValues);

  // prepare layers list for component, add a filterActivated prop to set checkbox status
  const layers = state.layers.workspaceLayers.filter(elem => elem.type === LAYER_TYPES.Heatmap).map((l) => {
    l.filterActivated = currentlyEditedFilterGroup && currentlyEditedFilterGroup.checkedLayers[l.id] === true;
    return l;
  });

  // prepare filters: dedupe filters that have the same id, set default values
  const filteredLayers = layers.filter(l => l.filterActivated === true && l.header.filters !== undefined);
  const availableFilters = filteredLayers.map(l => l.header.filters);
  const flattenedFilters = [].concat(...availableFilters);
  const filtersById = {};
  // this will remove duplicates by filter.id (ie category / flag_id)
  flattenedFilters.forEach((f) => {
    filtersById[f.id] = f;
    if (f.useDefaultValues === true) {
      if (f.id === 'flag') {
        filtersById[f.id].values = FLAG_FILTER_GROUP_VALUES;
      }
    }
  });
  const filters = Object.values(filtersById);

  // prepare save button status: at least one layer must be checked, and at least one filter defined
  const anyLayerChecked = currentlyEditedFilterGroup && Object.keys(currentlyEditedFilterGroup.checkedLayers)
    .some(key => currentlyEditedFilterGroup.checkedLayers[key] === true);
  const anyFilterSelected = currentlyEditedFilterGroup && Object.keys(currentlyEditedFilterGroup.filterValues).length > 0;
  const disableSave = anyLayerChecked === false || anyFilterSelected === false;

  // prepare warnings, when a filter is applied to a layer that doesn't support it
  let warningFilterId;
  const warningLayer = filteredLayers.find((layer) => {
    const layerFiltersIds = layer.header.filters.map(f => f.id);
    return !filterValuesKeys.every((filterId) => {
      if (layerFiltersIds.indexOf(filterId) === -1) {
        warningFilterId = filterId;
        return false;
      }
      return true;
    });
  });

  let warning;
  if (warningLayer) {
    if (!state.literals.filter_groups_warning) {
      console.warn('filter_groups_warning is missing from your literals.json file.');
      warning = '';
    } else {
      warning = state.literals.filter_groups_warning
        .replace('$LAYER', warningLayer.title)
        .replace('$FILTER', filters.find(f => f.id === warningFilterId).label);
    }
  }

  // take all the displayed labels to set default filter group label
  const defaultLabel = (!filters.length) ? '' : filterValuesKeys.map((filterId) => {
    const currentFilterValues = currentlyEditedFilterGroup.filterValues[filterId];
    const filterValues = filters.find(filter => filter.id === filterId).values;
    const filterValueLabel = filterValues
      .filter(filterValue => currentFilterValues.indexOf(parseInt(filterValue.id, 10)) > -1)
      .map(f => f.label)
      .join(', ');
    return filterValueLabel;
  }).join(' ');

  return {
    disableSave,
    warning,
    layers,
    currentlyEditedFilterGroup,
    filters,
    label: currentlyEditedFilterGroup && currentlyEditedFilterGroup.label,
    defaultLabel,
    isNewFilter: state.filterGroups.editFilterGroupIndex === null
  };
};

const mapDispatchToProps = dispatch => ({
  onSaveClicked: () => {
    dispatch(setFilterGroupModalVisibility(false));
    dispatch(saveFilterGroup());
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(FilterGroupModal);


text:
<?php

namespace Rcms\Template;

use Psr\Http\Message\StreamInterface;

/**
 * A template for the site settings.
 */
final class SiteSettingsTemplate extends Template {

    public function writeText(StreamInterface $stream) {
        $text = $this->text;

        $tokenName = RequestToken::FIELD_NAME;
        $tokenHtml = htmlSpecialChars($this->token->getTokenString());

        if ($this->saved) {
            $top_message = <<<EOT
                {$text->t("site_settings.site_settings")} {$text->t("editor.are_changed")}
                getUrlPage("admin")}">
                    {$text->t("main.admin")}

EOT;
        }

        return <<<EOT

                {$text->t("site_settings.editing_site_settings.explained")}

                {$text->t("main.fields_required")}

            <form action="{$text->url("site_settings")}" method="post">

                    {$text->t("site_settings.title")}:*

                    <input type="text" name="option_title" id="option_title" value="{$this->title}" />

                    {$text->t("site_settings.title.explained")}

                    {$text->t("site_settings.copyright")}:

                    <input type="text" name="option_copyright" id="option_copyright" value="{$this->copyright}" />

                    {$text->t("site_settings.copyright.explained")}

                    {$text->t("site_settings.password")}:

                    <input type="text" name="option_password" id="option_password" value="{$this->password}" />

                    {$text->t("site_settings.password.explained")}

                    {$text->t("site_settings.language")}:*

                    {$this->get_dropdown_list("option_language", $languages, $this->language, true)}

                    {$text->t("site_settings.language.explained")}

                    {$text->t("site_settings.theme")}:*

                    {$this->get_dropdown_list("option_theme", $themes, $this->theme, true)}

                    {$text->t("site_settings.theme.explained")}

                        <input class="checkbox" type="checkbox" name="option_user_account_creation" id="option_user_account_creation" $user_account_creation_checked />
                        {$text->t("site_settings.user_account_creation")}

                    {$text->t("site_settings.user_account_creation.explained")}

                    <input type="hidden" name="$tokenName" value="$tokenHtml" />
                    <input type="submit" name="submit" class="button primary_button" value="{$text->t("editor.save")}" />
                    url("admin")} class="button">{$text->t("editor.save")}

            </form>
EOT;
    }

}


text:
//#include "BaseLib/Containers/StringMap.h"
#include "BaseLib/Reflection/Class.h"
#include "BaseLib/Strings/NumberFormat.h"
#include "BaseLib/ErrorHandling.h"

namespace BaseLib {
namespace Reflection {

using namespace BaseLib::ErrorHandling;

AbstractGetEnumPropertyFunctor::AbstractGetEnumPropertyFunctor(EnumProperty* forProperty)
	: property(forProperty)
{
}

BaseLib::Strings::String AbstractGetEnumPropertyFunctor::getProperty(const void* instance, const NumberFormat* numberFormat/*, int arrayIndex*/) const
{
	if (numberFormat == NULL) numberFormat = NumberFormat::getDefault();
	int intResult = getPropertyAsInt(instance/*, arrayIndex*/);
	EnumProperty::Enums::ConstIterator result = property->getEnums().findValue(intResult);
	if (result != property->getEnums().end())
	{
		return result->first;
	}
	else
	{
		resultError("Invalid enum-value!" ERROR_AT);
		return Empty();
	}
}

bool AbstractGetEnumPropertyFunctor::getPropertyAsBool(const void* instance, const NumberFormat* numberFormat/*, int arrayIndex*/) const
{
	BaseLib::Strings::String stringResult = getProperty(instance/*, arrayIndex*/);
	bool result = false;
	if (stringResult.tryParse(result) == false)
	{
		stateError(CANT_CONVERT_STRING_PROPERTY_TO_BOOL(property->getName(), stringResult));
	}
	return result;
}

float AbstractGetEnumPropertyFunctor::getPropertyAsFloat(const void* instance, const NumberFormat* numberFormat/*, int arrayIndex*/) const
{
	return static_cast<float>(getPropertyAsInt(instance/*, arrayIndex*/));
}

double AbstractGetEnumPropertyFunctor::getPropertyAsDouble(const void* instance, const NumberFormat* numberFormat/*, int arrayIndex*/) const
{
	return getPropertyAsInt(instance/*, arrayIndex*/);
}

} // namespace Reflection
} // namespace BaseLib


text:
<?php $view->extend('::base.html.twig') ?>

<?php $view['slots']->set('title', 'yellowarmyMainBundle:Admin:home') ?>

<?php $view['slots']->start('body') ?>

Welcome to the Admin:home page

<?php $view['slots']->stop() ?>


text:
package com.amazonaws.services.databasemigrationservice.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum MigrationTypeValue {

    FullLoad("full-load"),
    Cdc("cdc"),
    FullLoadAndCdc("full-load-and-cdc");

    private String value;

    private MigrationTypeValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return MigrationTypeValue corresponding to the value
     */
    public static MigrationTypeValue fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (MigrationTypeValue enumEntry : MigrationTypeValue.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
require 'spec_helper'

describe Adm::BackersController do
  subject{ response }
  let(:admin) do
    u = Factory(:user)
    u.admin = true
    u.save!
    u
  end

  let(:unconfirmed_backer) do
    b = Factory(:backer)
    b.confirmed = false
    b.save!
    b
  end

  describe "PUT confirm" do
    context "when I'm not logged in" do
      before do
        put :confirm, :locale => :pt, :id => 1
      end
      it{ should redirect_to login_path }
    end

    context "when I'm logged as admin" do
      before do
        controller.stubs(:current_user).returns(admin)
        put :confirm, :locale => :pt, :id => unconfirmed_backer.id
      end

      it 'backer should be confirmed' do
        unconfirmed_backer.reload
        unconfirmed_backer.confirmed.should be_true
      end
    end
  end

  describe "GET index" do
    context "when I'm not logged in" do
      before do
        get :index, :locale => :pt
      end
      it{ should redirect_to login_path }
    end

    context "when I'm logged as admin" do
      before do
        controller.stubs(:current_user).returns(admin)
        get :index, :locale => :pt
      end
      its(:status){ should == 200 }
    end
  end

  describe ".menu" do
    it "should add a menu entry to the menu_items class variable when we pass a parameter and retrieve when we have no parameters" do
      Adm::BackersController.menu "Test Menu" => "/path"
      Adm::BaseController.menu.should include("Test Menu")
    end
  end
end


text:
<?php
/**
 * Access Policy English lexicon topic
 *
 * @language en
 * @package modx
 * @subpackage lexicon
 */
$_lang['active_of'] = '[[+active]] of [[+total]]';
$_lang['active_permissions'] = 'Active Permissions';
$_lang['no_policy_option'] = ' (no policy) ';
$_lang['permission'] = 'Käyttöoikeus';
$_lang['permission_add'] = 'Add Permission';
$_lang['permission_add_template'] = 'Add Permission to Template';
$_lang['permission_err_ae'] = 'Permission already exists for this policy.';
$_lang['permission_err_nf'] = 'Permission not found.';
$_lang['permission_err_ns'] = 'Permission not specified.';
$_lang['permission_err_remove'] = 'An error occurred while trying to remove this permission.';
$_lang['permission_err_save'] = 'An error occurred while trying to save this permission.';
$_lang['permission_new'] = 'New Permission';
$_lang['permission_remove'] = 'Delete Permission';
$_lang['permission_remove_confirm'] = 'Are you sure you want to remove this permission?';
$_lang['permission_update'] = 'Update Permission';
$_lang['permissions'] = 'Käyttöoikeudet';
$_lang['permissions_desc'] = 'Here you can define specific permissions that this policy will contain. All user groups with this policy will inherit these permissions.';
$_lang['policies'] = 'Access Policies';
$_lang['policy'] = 'Access Policy';
$_lang['policy_create'] = 'Create Access Policy';
$_lang['policy_data'] = 'Policy Data';
$_lang['policy_desc'] = 'Access policies are generic policies that restrict or enable certain actions with MODX.';
$_lang['policy_desc_name'] = 'The name of the Access Policy';
$_lang['policy_desc_description'] = 'Optional. A short description of the Access Policy';
$_lang['policy_desc_template'] = 'The Policy Template used for this Policy. Policies get their Permission lists from their Template.';
$_lang['policy_desc_lexicon'] = 'Optional. The Lexicon Topic that this Policy uses to translate the Permissions it owns.';
$_lang['policy_duplicate'] = 'Duplicate Policy';
$_lang['policy_duplicate_confirm'] = 'Are you sure you want to duplicate this policy and all of its data?';
$_lang['policy_err_ae'] = 'A Policy already exists with the name `[[+name]]`. Please select another name.';
$_lang['policy_err_nf'] = 'Policy not found.';
$_lang['policy_err_ns'] = 'Policy not specified.';
$_lang['policy_err_remove'] = 'An error occurred while trying to remove the Policy.';
$_lang['policy_err_save'] = 'An error occurred while trying to save the Policy.';
$_lang['policy_export'] = 'Export Policy';
$_lang['policy_import'] = 'Import Policy';
$_lang['policy_import_msg'] = 'Select an XML file to import a Policy from. It must be in the correct XML Policy format.';
$_lang['policy_management'] = 'Access Policies';
$_lang['policy_management_msg'] = 'Access Policies manage how MODX handles permissions for specified actions.';
$_lang['policy_name'] = 'Policy Name';
$_lang['policy_property_create'] = 'Create Access Policy Property';
$_lang['policy_property_new'] = 'New Policy Property';
$_lang['policy_property_remove'] = 'Delete Access Policy Property';
$_lang['policy_property_specify_name'] = 'Please specify a policy property name:';
$_lang['policy_remove'] = 'Delete Policy';
$_lang['policy_remove_confirm'] = 'Are you sure you want to remove this Access Policy?';
$_lang['policy_remove_multiple'] = 'Delete Policies';
$_lang['policy_remove_multiple_confirm'] = 'Are you sure you want to remove these Access Policies? This is irreversible.';
$_lang['policy_update'] = 'Update Policy';
$_lang['policy_template'] = 'Policy Template';
$_lang['policy_template.desc'] = 'A Policy Template defines which Permissions will show up in the Permissions grid when editing a specific Policy. You can add or remove specific Permissions from this template below. Note that removing a Permission from a Template will remove it from any Policies that use this Template.';
$_lang['policy_template_create'] = 'Create Policy Template';
$_lang['policy_template_desc_name'] = 'The name of the Access Policy Template';
$_lang['policy_template_desc_description'] = 'Optional. A short description of the Access Policy Template';
$_lang['policy_template_desc_lexicon'] = 'Optional. The Lexicon Topic that this Policy Template uses to translate the Permissions it owns.';
$_lang['policy_template_desc_template_group'] = 'The Policy Template Group to use. This is used when selecting Policies from a dropdown menu; usually they are filtered by template group. Select an appropriate group for your Policy Template.';
$_lang['policy_template_duplicate'] = 'Duplicate Policy Template';
$_lang['policy_template_duplicate_confirm'] = 'Are you sure you want to duplicate this Policy Template?';
$_lang['policy_template_err_ae'] = 'A Policy Template already exists with the name `[[+name]]`. Please select another name.';
$_lang['policy_template_err_nf'] = 'Policy Template not found.';
$_lang['policy_template_err_ns'] = 'Policy Template not specified.';
$_lang['policy_template_err_remove'] = 'An error occurred while trying to remove the Policy Template.';
$_lang['policy_template_err_save'] = 'An error occurred while trying to save the Policy Template.';
$_lang['policy_template_export'] = 'Export Policy Template';
$_lang['policy_template_import'] = 'Import Policy Template';
$_lang['policy_template_import_msg'] = 'Select an XML file to import a Policy Template from. It must be in the correct XML Policy Template format.';
$_lang['policy_template_remove'] = 'Delete Policy Template';
$_lang['policy_template_remove_confirm'] = 'Are you sure you want to remove this Policy Template? It will remove all Policies attached to this Template as well - this could break your MODX installation if any active Policies are attached to this Template.';
$_lang['policy_template_remove_multiple'] = 'Delete Selected Policy Templates';
$_lang['policy_template_remove_multiple_confirm'] = 'Are you sure you want to remove these Policy Templates? It will remove all Policies attached to these Templates as well - this could break your MODX installation if any active Policies are attached to these Templates.';
$_lang['policy_template_update'] = 'Update Policy Template';
$_lang['policy_templates'] = 'Policy Templates';
$_lang['policy_templates.intro_msg'] = 'This is a list of Policy Templates which define lists of Permissions that are checked or unchecked in specific Policies.';
$_lang['template_group'] = 'Template Group';


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

<title>Overview List</title>
<meta name="date" content="2017-05-22">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

example.anoncomm

example.livestreaming

example.loadbalancing

example.nocem.anoncomm

example.nocem.livestreaming

example.nocem.loadbalancing

example.srr

racoon

racoon.core

racoon.design

racoon.input

racoon.input.parser

racoon.rationality

racoon.rationality.evolutionary

racoon.rationality.sequential

racoon.rsim

racoon.rsim.accountability

racoon.rsim.monitors

racoon.tuning

racoon.util


text:
<!DOCTYPE html>

<title>moxman Example</title>

<form method="post" action="dump.php">

Absolute URL

		<input type="hidden" id="url_abs" style="width:400px" />
		[Pick file]

Relative URL

		<input id="url_rel" style="width:400px" />
		[Pick file]

Relative URL from a specific location

		<input id="url_rel_loc" style="width:400px" />
		[Pick file]

Absolute URL without host

		<input id="url_abs_nohost" style="width:400px" />
		[Pick file]

Specify default path

		<input id="url_path" style="width:400px" />
		[Pick file]

Specify rootpath

		<input id="url_root" style="width:400px" />
		[Pick file]

Filtered file selection

		<input id="url_filtered" style="width:400px" />
		[Pick file]

Custom insert function

		[Pick file]

Edit image

		[Edit image]

Edit text

		[Edit text]

Upload

		[Upload]

TinyMCE

	<textarea></textarea>

</form>


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="#000000"
        android:textSize="100sp" />

</RelativeLayout>


text:
using System;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Moq;
using NUnit.Framework;

namespace TplDataflow.Tests.Blocks
{
    public abstract class TransformBlockBaseTests
    {
        private Mock<IPropagatorBlock<int, int>> _fakeBlock;
        private Mock<ITargetBlock<int>> _fakeTarget;
        private IPropagatorBlock<int, int> _block;

        [SetUp]
        public void SetUp()
        {
            _fakeBlock = MakeFakePropogatorBlock();
            _fakeTarget = new Mock<ITargetBlock<int>>();

            _block = CreateBlock(_fakeBlock.Object);
        }

        public abstract IPropagatorBlock<int, int> CreateBlock(IPropagatorBlock<int, int> internalBlock);

        [Test]
        public void Completion_Returns_Underlying_DataFlow_Block_Task()
        {
            Assert.That(_block.Completion, Is.EqualTo(_fakeBlock.Object.Completion));
        }

        [Test]
        public void Complete_Calls_Underlying_DataFlow_Block_Method()
        {
            _block.Complete();

            _fakeBlock.Verify(b => b.Complete(), Times.Once());
        }

        [Test]
        public void Fault_Calls_Underlying_Target_Block_Method()
        {
            _block.Fault(new Exception());

            _fakeBlock.Verify(b => b.Fault(It.IsAny<Exception>()), Times.Once());
        }

        [Test]
        public void LinkTo_Calls_Underlying_Target_Block_Method()
        {
            _block.LinkTo(_fakeTarget.Object, new DataflowLinkOptions());

            _fakeBlock.Verify(b => b.LinkTo(It.IsAny<ITargetBlock<int>>(), It.IsAny<DataflowLinkOptions>()), Times.Once());
        }

        [Test]
        public void ConsumeMessage_Calls_Underlying_Target_Block_Method()
        {
            bool consumed;
            _block.ConsumeMessage(new DataflowMessageHeader(1), _fakeTarget.Object, out consumed);

            _fakeBlock.Verify(b => b.ConsumeMessage(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>(), out consumed), Times.Once());
        }

        [Test]
        public void ReserveMessage_Calls_Underlying_Target_Block_Method()
        {
            _block.ReserveMessage(new DataflowMessageHeader(1), _fakeBlock.Object);

            _fakeBlock.Verify(b => b.ReserveMessage(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>()), Times.Once());
        }

        [Test]
        public void ReleaseReservation_Calls_Underlying_Target_Block_Method()
        {
            _block.ReleaseReservation(new DataflowMessageHeader(1), _fakeBlock.Object);

            _fakeBlock.Verify(b => b.ReleaseReservation(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>()), Times.Once());
        }

        [Test]
        public void OfferMessage_Calls_Underlying_Source_Block_Method()
        {
            const int message = -1;
            _block.OfferMessage(new DataflowMessageHeader(1), message, _fakeBlock.Object, true);

            _fakeBlock.Verify(b => b.OfferMessage(It.IsAny<DataflowMessageHeader>(), message, It.IsAny<ISourceBlock<int>>(), true), Times.Once());
        }

        private static Mock<IPropagatorBlock<int, int>> MakeFakePropogatorBlock()
        {
            var disposable = new Mock<IDisposable>().Object;
            var fakeBlock = new Mock<IPropagatorBlock<int, int>>(MockBehavior.Strict);
            fakeBlock.Setup(b => b.Completion).Returns(new Task(() => { }));
            fakeBlock.Setup(b => b.Complete());
            fakeBlock.Setup(b => b.Fault(It.IsAny<Exception>()));
            fakeBlock.Setup(b => b.LinkTo(It.IsAny<ITargetBlock<int>>(), It.IsAny<DataflowLinkOptions>())).Returns(disposable);
            bool consumed;
            fakeBlock.Setup(b => b.ConsumeMessage(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>(), out consumed)).Returns(It.IsAny<int>());
            fakeBlock.Setup(b => b.ReserveMessage(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>())).Returns(It.IsAny<bool>());
            fakeBlock.Setup(b => b.ReleaseReservation(It.IsAny<DataflowMessageHeader>(), It.IsAny<ITargetBlock<int>>()));
            fakeBlock.Setup(b => b.OfferMessage(It.IsAny<DataflowMessageHeader>(), It.IsAny<int>(), It.IsAny<ISourceBlock<int>>(), It.IsAny<bool>())).Returns(It.IsAny<DataflowMessageStatus>());
            return fakeBlock;
        }
    }
}


text:
<?php
return array(
    // the module name
    'name' => 'bundler',

    // the core class name
    'class' => 'Bundler',

    // whether Bundler is enabled (deprecated)
    'enabled' => FALSE,

    // container for all of the bundles
    'bundles' => array(),

    /**
     * Container for csstidy specific config options. See the CSSTidy module's
     * default configuration files for options. Suggested implementation is to
     * pull in your custom CSSTidy module options into this array dynamically.
     */
    'csstidy' => array(),

    /**
     * Container for gzip specific config options. See the GZip module's
     * default configuration file for options. Suggested implementation is to
     * pull in your custom GZip module options into this array dynamically.
     */
    'gzip' => array(),

    /**
     * Container for jsmin specific config options. See the JSMin module's
     * default configuration file for options. Suggested implementation is to
     * pull in your custom JSMin module options into this array dynamically.
     */
    'jsmin' => array(),

    /**
     * Container for s3 specific config options. See the S3 module's default
     * configuration file for options. Suggested implementation is to pull in your
     * custom S3 module options into this array dynamically.
     */
    's3' => array()
);


text:
require "spec_helper"

describe Veil::Utils do
  let(:mixed_hash) do
    {
      :foo => "bar",
      bar: "baz",
      "fizz" => :buzz
    }
  end

  let(:symbolized_hash) do
    {
      foo: "bar",
      bar: "baz",
      fizz: :buzz
    }
  end

  describe "#symbolize_keys" do
    it "symbolizes a hashes keys" do
      expect(described_class.symbolize_keys(mixed_hash)).to eq(symbolized_hash)
    end
  end
end


text:
"""
Base formatter implementation
"""

import abc
import typing

import packer.errors

class Formatter(metaclass=abc.ABCMeta):
    """
    Base formatter implementation
    """

    formatters: typing.ClassVar[typing.Dict[str, typing.Type]] = {}

    def __init_subclass__(cls):
        """
        Register any subclasses as possible formatters
        """

        if not hasattr(cls, 'format_name'):
            raise packer.errors.PackerError(
                f'{cls} is missing the format_name attribute',
            )

        format_name = getattr(cls, 'format_name')
        Formatter.formatters[format_name] = cls

    def __init__(self, data_stream: typing.Any) -> None:
        """
        Creates a formatter loaded with the given data in a parsed form
        """

        if hasattr(data_stream, 'readable'):
            self.data = self.parse(data_stream)
        else:
            self.data = data_stream

    @abc.abstractmethod
    def format_pretty(self) -> str:
        """
        Formats the data in a human friendly form
        """

    @abc.abstractmethod
    def format_compact(self) -> str:
        """
        Formats the data in a compact form
        """

    @abc.abstractmethod
    def parse(self, data_stream: typing.IO[typing.Any]) -> typing.Any:
        """
        Parses the data stream and returns the parsed data
        """

    @classmethod
    def get_formatter_class(cls, format_name: str) -> typing.Type:
        """
        Gets a class for the given format type
        """

        if format_name not in cls.formatters:
            raise packer.errors.PackerUnknownFormatType(
                f'Unrecognized format type: {format_name}',
            )

        return cls.formatters[format_name]


text:
package org.radeox.macro.api;

import java.io.IOException;
import java.io.Writer;

/**
 * Base class for API converters, stores a base URL
 *
 * @author Stephan J. Schmidt
 * @version $Id: BaseApiConverter.java,v 1.4 2003/05/23 10:47:25 stephan Exp $
 */

public abstract class BaseApiConverter implements ApiConverter {
  protected String baseUrl;

  public abstract void appendUrl(Writer writer, String className) throws IOException ;

  public void setBaseUrl(String baseUrl) {
    this.baseUrl = baseUrl;
  }

  public String getBaseUrl() {
    return this.baseUrl;
  }

  public abstract String getName();
}


text:
/**
 * Red Hat Open Innovation Labs Console API
 * Specification for interaction between the Labs Console front-end and back-end. Additionally, this API will be used to experiment with new concepts in order to allow the Automation API (https://github.com/rht-labs/automation-api) to remain stable.
 *
 * OpenAPI spec version: 0.1.0
 * Contact: rhc-open-innovation-labs@redhat.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function(root, factory) {
  if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'), require('../model/ErrorModel'), require('../model/Body'), require('../model/Build'));
  } else {
    // Browser globals (root is window)
    if (!root.RedHatOpenInnovationLabsConsoleApi) {
      root.RedHatOpenInnovationLabsConsoleApi = {};
    }
    root.RedHatOpenInnovationLabsConsoleApi.BuildApi = factory(root.RedHatOpenInnovationLabsConsoleApi.ApiClient, root.RedHatOpenInnovationLabsConsoleApi.ErrorModel, root.RedHatOpenInnovationLabsConsoleApi.Body, root.RedHatOpenInnovationLabsConsoleApi.Build);
  }
}(this, function(ApiClient, ErrorModel, Body, Build) {
  'use strict';

  /**
   * Build service.
   * @module api/BuildApi
   * @version 0.1.0
   */

  /**
   * Constructs a new BuildApi.
   * @alias module:api/BuildApi
   * @class
   * @param {module:ApiClient} apiClient Optional API client implementation to use,
   * default to {@link module:ApiClient#instance} if unspecified.
   */
  var exports = function(apiClient) {
    this.apiClient = apiClient || ApiClient.instance;

    /**
     * Callback function to receive the result of the addBuild operation.
     * @callback module:api/BuildApi~addBuildCallback
     * @param {String} error Error message, if any.
     * @param data This operation does not return a value.
     * @param {String} response The complete HTTP response.
     */

    /**
     * Add a new build
     *
     * @param {Object} opts Optional parameters
     * @param {module:model/Body} opts.body Build object that needs to be added to the store
     * @param {module:api/BuildApi~addBuildCallback} callback The callback function, accepting three arguments: error, data, response
     */
    this.addBuild = function(opts, callback) {
      opts = opts || {};
      var postBody = opts['body'];

      var pathParams = {
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = [];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = Object;

      return this.apiClient.callApi(
        '/builds', 'POST',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType, callback
      );
    }

    /**
     * Update an existing build
     *
     * @param {Integer} id Build ID
     * @param {Object} opts Optional parameters
     * @param {module:model/Build} opts.body User object that needs to be updated in the store
     * @param {module:api/BuildApi~updateBuildCallback} callback The callback function, accepting three arguments: error, data, response
     */
    this.updateBuild = function(id, opts, callback) {
      opts = opts || {};
      var postBody = opts['body'];

      // verify the required parameter 'id' is set
      if (id == undefined || id == null) {
        throw "Missing the required parameter 'id' when calling updateBuild";
      }

      var pathParams = {
        'id': id
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = [];
      var contentTypes = ['application/json'];
      var accepts = ['application/json'];
      var returnType = null;

      return this.apiClient.callApi(
        '/builds/{id}', 'PUT',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType, callback
      );
    }

    /**
     * Callback function to receive the result of the buildsGet operation.
     * @callback module:api/BuildApi~buildsGetCallback
     * @param {String} error Error message, if any.
     * @param {Array.<module:model/Build>} data The data returned by the service call.
     * @param {String} response The complete HTTP response.
     */

    /**
     * Gets `Build` objects.
     * @param {module:api/BuildApi~buildsGetCallback} callback The callback function, accepting three arguments: error, data, response
     * data is of type: {@link Array.<module:model/Build>}
     */
    this.buildsGet = function(callback) {
      var postBody = null;

      var pathParams = {
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = [];
      var contentTypes = [];
      var accepts = [];
      var returnType = [Build];

      return this.apiClient.callApi(
        '/builds', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType, callback
      );
    }

    /**
     * Callback function to receive the result of the buildsIdGet operation.
     * @callback module:api/BuildApi~buildsIdGetCallback
     * @param {String} error Error message, if any.
     * @param {module:model/Build} data The data returned by the service call.
     * @param {String} response The complete HTTP response.
     */

    /**
     * Gets a `Build` object by ID.
     * @param {Integer} id Build ID
     * @param {module:api/BuildApi~buildsIdGetCallback} callback The callback function, accepting three arguments: error, data, response
     * data is of type: {@link module:model/Build}
     */
    this.buildsIdGet = function(id, callback) {
      var postBody = null;

      // verify the required parameter 'id' is set
      if (id == undefined || id == null) {
        throw "Missing the required parameter 'id' when calling buildsIdGet";
      }

      var pathParams = {
        'id': id
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = [];
      var contentTypes = [];
      var accepts = [];
      var returnType = Build;

      return this.apiClient.callApi(
        '/builds/{id}', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType, callback
      );
    }

    /**
     * Callback function to receive the result of the downloadEngagement operation.
     * @callback module:api/BuildApi~downloadEngagementCallback
     * @param {String} error Error message, if any.
     * @param {module:model/Build} data The data returned by the service call.
     * @param {String} response The complete HTTP response.
     */

    /**
     * Gets a `Build` object by ID.
     * @param {Integer} id Topology ID
     * @param {module:api/BuildApi~downloadEngagementCallback} callback The callback function, accepting three arguments: error, data, response
     * data is of type: {@link module:Object}
     */
    this.downloadEngagement = function(id, callback) {
      var postBody = null;

      // verify the required parameter 'id' is set
      if (id == undefined || id == null) {
        throw "Missing the required parameter 'id' when calling downloadEngagement";
      }

      var pathParams = {
        'id': id
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = [];
      var contentTypes = [];
      var accepts = [];
      var returnType = Object;

      return this.apiClient.callApi(
        '/downloadEngagement/{id}', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType, callback
      );
    }
  };

  return exports;
}));


text:
namespace ArtGallery.SqlLiteData
{
    using System;
    using System.Data.Entity;
    using System.Linq;

    using SQLite.CodeFirst;

    public class ArtGalleryDbInitializer : SqliteDropCreateDatabaseAlways<ArtGallerySqlLiteDbContext>
    {
        public ArtGalleryDbInitializer(DbModelBuilder modelBuilder)
            : base(modelBuilder)
        {
        }

        protected override void Seed(ArtGallerySqlLiteDbContext context)
        {
        }
    }
}


text:
package org.dasein.cloud.flexiant.network;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.flexiant.FCOProvider;
import org.dasein.cloud.flexiant.FCOProviderUtils;
import org.dasein.cloud.network.AbstractNetworkFirewallSupport;
import org.dasein.cloud.network.Direction;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.network.FirewallRule;
import org.dasein.cloud.network.Permission;
import org.dasein.cloud.network.Protocol;
import org.dasein.cloud.network.RuleTarget;

import com.extl.jade.user.Condition;
import com.extl.jade.user.ExtilityException;
import com.extl.jade.user.FilterCondition;
import com.extl.jade.user.FirewallProtocol;
import com.extl.jade.user.FirewallRuleAction;
import com.extl.jade.user.FirewallTemplate;
import com.extl.jade.user.Ip;
import com.extl.jade.user.Nic;
import com.extl.jade.user.ResourceState;
import com.extl.jade.user.ResourceType;
import com.extl.jade.user.SearchFilter;
import com.extl.jade.user.UserService;

/**
 * The AbstractNetworkFirewallSupport implementation for the Dasein FCO implementation
 *
 * This functionality is currently not supported by the FCO user service so this will not be available to the implementation
 *
 * @version 2013.12 initial version
 * @since 2013.12
 */
public class FCONetworkFirewallSupport extends AbstractNetworkFirewallSupport {

	private UserService userService = null;

	public FCONetworkFirewallSupport(FCOProvider provider) {
		super(provider);
		userService = FCOProviderUtils.getUserServiceFromContext(provider.getContext());
	}

	@Override
	public String getProviderTermForNetworkFirewall(Locale locale) {
		return "Firewall";
	}

	@Override
	public boolean isSubscribed() throws CloudException, InternalException {
		return true;
	}

	@Override
	public Collection<Firewall> listFirewalls() throws InternalException, CloudException {
		List<Firewall> firewalls = new ArrayList<Firewall>();
		try {
			List<Object> fcoFirewalls = FCOProviderUtils.listAllResources(userService, null, ResourceType.FIREWALL).getList();
			if(fcoFirewalls.size() == 0){
				return firewalls;
			}
			for(Object obj : firewalls){
				Firewall firewall = createFirewall((com.extl.jade.user.Firewall)obj);
				firewalls.add(firewall);
			}
		} catch (ExtilityException e) {
			e.printStackTrace();
			throw new CloudException(e.getLocalizedMessage());
		}
		return firewalls;
	}

	@Override
	public Iterable<FirewallRule> listRules(String firewallId) throws InternalException, CloudException {
		List<FirewallRule> firewallRules = new ArrayList<FirewallRule>();
		try {
			SearchFilter filter = new SearchFilter();
			FilterCondition fc = new FilterCondition();
			fc.setCondition(Condition.IS_EQUAL_TO);
			fc.setField("resourceUUID");
			fc.getValue().add(firewallId);
			filter.getFilterConditions().add(fc);

			List<Object> fcoFirewalls = FCOProviderUtils.listAllResources(userService, filter, ResourceType.FIREWALL).getList();
			if(fcoFirewalls.size() == 0){
				return firewallRules;
			}
			com.extl.jade.user.Firewall fcoFirewall = (com.extl.jade.user.Firewall)fcoFirewalls.get(0);

			filter = new SearchFilter();
			fc = new FilterCondition();
			fc.setCondition(Condition.IS_EQUAL_TO);
			fc.setField("resourceUUID");
			fc.getValue().add(fcoFirewall.getTemplateUUID());
			filter.getFilterConditions().add(fc);

			List<Object> fcoFirewallTemplates = FCOProviderUtils.listAllResources(userService, filter, ResourceType.FIREWALL_TEMPLATE).getList();
			if(fcoFirewallTemplates.size() == 0){
				return firewallRules;
			}
			FirewallTemplate fcoFwTemplate = (FirewallTemplate)fcoFirewallTemplates.get(0);
			List<com.extl.jade.user.FirewallRule> fcoFirewallRules = fcoFwTemplate.getFirewallInRuleList();
			for(com.extl.jade.user.FirewallRule rule: fcoFirewallRules){
				firewallRules.add(createFirewallRule(rule, fcoFirewall.getResourceUUID(), "IN", fcoFwTemplate.getServiceNetworkUUID()));
			}
		} catch (ExtilityException e) {
			e.printStackTrace();
			throw new CloudException(e.getLocalizedMessage());
		}
		return firewallRules;
	}

	@Override
	public void removeFirewall(String... firewallIds) throws InternalException, CloudException {
		if(firewallIds != null && firewallIds.length > 0)
			try {
				for(String firewallId : firewallIds)
					userService.deleteResource(firewallId, true, null);
			} catch (ExtilityException e) {
				e.printStackTrace();
				throw new CloudException(e.getLocalizedMessage());
			}
	}

	@Override
	public Firewall getFirewall(String arg0) throws InternalException,
			CloudException {
		Firewall firewall = null;
		if(arg0 == null)
			return firewall;
		SearchFilter filter = new SearchFilter();
		FilterCondition fc = new FilterCondition();
		fc.setCondition(Condition.IS_EQUAL_TO);
		fc.setField("resourceUUID");
		fc.getValue().add(arg0);
		filter.getFilterConditions().add(fc);
		try {
			List<Object> fcoFirewalls = FCOProviderUtils.listAllResources(userService, filter, ResourceType.FIREWALL).getList();
			if(fcoFirewalls.size() == 0){
				return firewall;
			}
			firewall = createFirewall((com.extl.jade.user.Firewall)fcoFirewalls.get(0));
		} catch (ExtilityException e) {
			e.printStackTrace();
			throw new CloudException(e.getMessage());
		}

		return firewall;
	}

	@Override
	public Iterable<ResourceStatus> listFirewallStatus()
			throws InternalException, CloudException {
		List<ResourceStatus> resourceStatesList = new ArrayList<ResourceStatus>();
		try {
			List<Object> fcoFirewalls = FCOProviderUtils.listAllResources(userService, null, ResourceType.FIREWALL).getList();
			if(fcoFirewalls.size() == 0){
				return resourceStatesList;
			}
			for(Object obj : fcoFirewalls){
				com.extl.jade.user.Firewall firewall = (com.extl.jade.user.Firewall)obj;
				ResourceStatus status = new ResourceStatus(firewall.getResourceUUID(), null);
				resourceStatesList.add(status);
			}
		} catch (ExtilityException e) {
			e.printStackTrace();
			throw new CloudException(e.getMessage());
		}
		return super.listFirewallStatus();
	}

	private Firewall createFirewall(com.extl.jade.user.Firewall fcoFirewall) throws CloudException{
		Firewall firewall = new Firewall();
		firewall.setActive(fcoFirewall.getResourceState() == ResourceState.ACTIVE);
		firewall.setName(fcoFirewall.getResourceName());
		firewall.setProviderFirewallId(fcoFirewall.getResourceUUID());
		firewall.setDescription("Firewall : "+fcoFirewall.getResourceName());

		SearchFilter filter = new SearchFilter();
		FilterCondition fc = new FilterCondition();
		fc.setCondition(Condition.IS_EQUAL_TO);
		fc.setField("ipAddresses.ipAddress");
		fc.getValue().add(fcoFirewall.getIpAddress());
		filter.getFilterConditions().add(fc);

		try {
			List<Object> nics = FCOProviderUtils.listWithChildren(userService, filter, ResourceType.NIC).getList();
			if(nics.size() > 0){
				Nic nic = (Nic)nics.get(0);
				firewall.setProviderVlanId(nic.getNetworkUUID());
				firewall.setRegionId(nic.getClusterUUID());
				for(Ip ip : nic.getIpAddresses()){
					if(fcoFirewall.getIpAddress().equals(ip.getIpAddress()))
						firewall.setSubnetAssociations(new String[]{ip.getSubnetUUID()});
				}
			}
		} catch (ExtilityException e) {
			e.printStackTrace();
			throw new CloudException(e.getLocalizedMessage());
		}
		return firewall;
	}

	@SuppressWarnings("deprecation")
	private FirewallRule createFirewallRule(com.extl.jade.user.FirewallRule fcoFirewallRule,String firewallId,String inOrOut,String vlanId){
		Direction direction = null;
		if("IN".equals(inOrOut))
			direction = Direction.INGRESS;
		else
			direction = Direction.EGRESS;
		FirewallProtocol fcoProtocol = fcoFirewallRule.getProtocol();
		Protocol protocol = null;
		switch (fcoProtocol) {
			case ANY:
				protocol = Protocol.ANY;
				break;
			case ICMP:
				protocol = Protocol.ICMP;
				break;
			case TCP:
				protocol = Protocol.TCP;
				break;
			case UDP:
				protocol = Protocol.UDP;
				break;
			default:
				break;
		}

		Permission permission = null;
		if(fcoFirewallRule.getAction() == FirewallRuleAction.ALLOW){
			permission = Permission.ALLOW;
		}else if (fcoFirewallRule.getAction() == FirewallRuleAction.REJECT){
			permission = Permission.DENY;
		}
		RuleTarget target = RuleTarget.getVlan(vlanId);
		String fwRuleId = FirewallRule.getRuleId(firewallId, fcoFirewallRule.getIpAddress(), direction,
				protocol, permission, target, fcoFirewallRule.getLocalPort(), fcoFirewallRule.getRemotePort());
		FirewallRule rule = FirewallRule.getInstance(fwRuleId, firewallId, fcoFirewallRule.getIpAddress(), direction, protocol, permission, target, fcoFirewallRule.getRemotePort());
		return rule;
	}

}


text:
package com.exlibris.dps.delivery.vpp.filePath;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.exlibris.core.infra.common.exceptions.logging.ExLogger;
import com.exlibris.core.sdk.storage.handler.StorageHandler;
import com.exlibris.digitool.common.dnx.DnxDocument;
import com.exlibris.digitool.common.storage.StorageHandlerLocator;
import com.exlibris.dps.sdk.access.AccessException;
import com.exlibris.dps.sdk.delivery.AbstractViewerPreProcessor;
import com.exlibris.dps.sdk.delivery.SmartFilePath;

public class FilePathVppPlugin extends AbstractViewerPreProcessor{

	private String pid = null;
	private static final ExLogger logger = ExLogger.getExLogger(FilePathVppPlugin.class);

	//This method will be called by the delivery framework before the call for the execute Method
	@Override
	public void init(DnxDocument dnx, Map<String, String> viewContext, HttpServletRequest request, String dvs,String ieParentId, String repParentId)
			throws AccessException {
		super.init(dnx, viewContext, request, dvs, ieParentId, repParentId);
		this.pid = getPid();
	}

	//Does the pre-viewer processing tasks.
	public void execute() throws Exception {
		Map<String, Object> paramMap = getAccess().getViewerDataByDVS(getDvs()).getParameters();
		// add params to session
		SmartFilePath filePath = null;
		String localFilePath = null;
		try {
			filePath = getAccess().getFilePathByDVS(dvs, this.pid);
			// try to access the file in a smarter way
			if (filePath.getStorageId() != null & filePath.getStoredEntityIdentifier() != null) {
				StorageHandler storageHandler = StorageHandlerLocator.getStorageHandlerByStorageId(filePath.getStorageId());
				localFilePath = storageHandler.getLocalFilePath(filePath.getStoredEntityIdentifier());
			}
			// default way
			else {
				localFilePath = filePath.getFilePath();
			}
		} catch (Exception e) {
			logger.error("Error In File Path VPP - cannot retreive the files to view", e, pid);
			throw new AccessException();
		}
		paramMap.put("filePath", localFilePath);
		getAccess().setParametersByDVS(getDvs(), paramMap);
	}
}


text:
(function (a$, $, jT) {

	function SubstanceKit(settings) {
		this.rootElement = settings.target;
		$(this.rootElement).addClass('jtox-toolkit'); // to make sure it is there even when manually initialized

		this.settings = $.extend(true, {}, SubstanceKit.defaults, settings);

		this.pageStart = this.settings.pageStart;
		this.pageSize = this.settings.pageSize;

		if (!this.settings.noInterface) {
			var self = this;

			if (this.settings.embedComposition && this.settings.onDetails == null) {
				this.settings.onDetails = function (root, data) {
					new jT.ui.Composition(root, $.extend({},
						self.settings,
						(typeof self.settings.embedComposition == 'object' ? self.settings.embedComposition : {}), {
							compositionUri: data.URI + '/composition'
						}
					));
				};
			}

			jT.ui.putTemplate('all-substance', ' ? ', this.rootElement);
			this.init(settings);
		}

		// finally, if provided - make the query
		if (!!this.settings.substanceUri)
			this.querySubstance(self.settings.substanceUri)
	};

	SubstanceKit.prototype.init = function (settings) {
		var self = this;

		// deal if the selection is chosen
		var colId = self.settings.columns.substance['Id'];
		if (colId) {
			jT.tables.putActions(self, colId);
			colId.title = '';
		}

		// Leave that here, because `self` is used...
		self.settings.columns.substance['Owner'].render = function (data, type, full) {
			return (type != 'display') ? data : '' + data + '';
		};

		var opts = { "dom": "rti" };
		if (self.settings.showControls) {
			jT.tables.bindControls(self, {
				nextPage: function () { self.nextPage(); },
				prevPage: function () { self.prevPage(); },
				sizeChange: function () { self.queryEntries(self.pageStart, parseInt($(this).val())); },
				filter: function () { $(self.table).dataTable().filter($(this).val()).draw(); }
			});

			opts['infoCallback'] = function (oSettings, iStart, iEnd, iMax, iTotal, sPre) {
				var needle = $('.filterbox', self.rootElement).val();
				$('.filtered-text', self.rootElement).html(!needle ? ' ' : ' (filtered to ' + iTotal + ') ');
				return '';
			};
		} else
			$('.jtox-controls', self.rootElement).remove();

		// READYY! Go and prepare THE table.
		self.table = jT.tables.putTable(self, $('table', self.rootElement)[0], 'substance', opts);
	};

	SubstanceKit.prototype.queryEntries = function (from, size) {
		if (from < 0) from = 0;
		if (!size || size < 0) size = this.pageSize;

		var qStart = Math.floor(from / size),
			qUri = jT.addParameter(this.substanceUri, "page=" + qStart + "&pagesize=" + size),
			self = this;

		jT.ambit.call(this, qUri, function (result, jhr) {
			if (!!result && jhr.status == 200) {
				self.pageSize = size;
				self.pageStart = from;

				for (var i = 0, rl = result.substance.length; i < rl; ++i)
					result.substance[i].index = i + from + 1;

				self.substance = result.substance;

				if (result.substance.length < self.pageSize) // we've reached the end!!
					self.entriesCount = from + result.substance.length;

				// time to call the supplied function, if any.
				jT.fireCallback(self.settings.onLoaded, self, result);
				if (!self.settings.noInterface) {
					$(self.table).dataTable().fnClearTable();
					$(self.table).dataTable().fnAddData(result.substance);

					self.updateControls(from, result.substance.length);
				}
			} else
				jT.fireCallback(self.settings.onLoaded, self, result);
		});
	};

	SubstanceKit.prototype.querySubstance = function (uri) {
		this.substanceUri = jT.ambit.grabPaging(this, uri);
		this.settings.baseUrl = jT.formBaseUrl(uri);
		this.queryEntries(this.pageStart);
	};

	SubstanceKit.prototype.query = function (uri) {
		this.querySubstance(uri);
	};

	// some "inheritance" :-)
	SubstanceKit.prototype.nextPage = jT.tables.nextPage;
	SubstanceKit.prototype.prevPage = jT.tables.prevPage;
	SubstanceKit.prototype.updateControls = jT.tables.updateControls;

	SubstanceKit.defaults = { // all settings, specific for the kit, with their defaults. These got merged with general (jToxKit) ones.
		showControls: true, // show navigation controls or not
		selectionHandler: null, // if given - this will be the name of the handler, which will be invoked by jToxQuery when the attached selection box has changed...
		embedComposition: null, // embed composition listing as details for each substance - it valid only if onDetails is not given.
		noInterface: false, // run in interface-less mode - only data retrieval and callback calling.
		onDetails: null, // called when a details row is about to be openned. If null - no details handler is attached at all.
		onLoaded: null, // called when the set of substances (for this page) is loaded.
		language: {
			loadingRecords: "No substances found.",
			zeroRecords: "No substances found.",
			emptyTable: "No substances available.",
			info: "Showing _TOTAL_ substance(s) (_START_ to _END_)"
		},

		pageStart: 0,
		pageSize: 10,
		/* substanceUri */
		columns: {
			substance: {
				'Id': {
					title: 'Id',
					data: 'URI',
					defaultContent: "-",
					width: "60px",
					render: function (data, type, full) {
						return (type != 'display') ? full.index : ' - ' + full.index + ' - ';
					}
				},
				'Substance Name': {
					title: "Substance Name",
					data: "name",
					render: function (data, type, full) {
						if (data == null || data == 'null') data = '-';
						return (type != 'display') ? data : jT.ui.linkedData('' + data + '', "Click to view study details", data)
					}
				},
				'Substance UUID': {
					title: "Substance UUID",
					data: "i5uuid",
					render: function (data, type, full) {
						if (data == null || data == 'null') return '';
						return (type != 'display') ? data : jT.ui.shortenedData('' + data + '', "Press to copy the UUID in the clipboard", data)
					}
				},
				'Substance Type': {
					title: "Substance Type",
					data: "substanceType",
					width: "15%",
					defaultContent: '-'
				},
				'Public name': {
					title: "Public name",
					data: "publicname",
					defaultContent: '-'
				},
				'Reference substance UUID': {
					title: "Reference substance UUID",
					data: "referenceSubstance",
					render: function (data, type, full) {
						if (data.i5uuid == null || data.i5uuid == 'null') return '';
						return (type != 'display') ? data.i5uuid : jT.ui.shortenedData('' + data.i5uuid + '', "Press to copy the UUID in the clipboard", data.i5uuid);
					}
				},
				'Owner': {
					title: "Owner",
					data: "ownerName",
					defaultContent: '-'
				},
				'Info': {
					title: "Info",
					data: "externalIdentifiers",
					render: function (data, type, full) {
						return jT.ambit.formatExtIdentifiers(data, type, full);
					}
				}
			}
		}
	}

	jT.ui.Substance = SubstanceKit;

})(asSys, jQuery, jToxKit);


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module unless amdModuleId is set
    define([], function () {
      return (factory());
    });
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    factory();
  }
}(this, function () {

$translateCookieStorageFactory.$inject = ['$injector'];
angular.module('pascalprecht.translate')

/**
 * @ngdoc object
 * @name pascalprecht.translate.$translateCookieStorage
 * @requires $cookieStore
 *
 * @description
 * Abstraction layer for cookieStore. This service is used when telling angular-translate
 * to use cookieStore as storage.
 *
 */
  .factory('$translateCookieStorage', $translateCookieStorageFactory);

function $translateCookieStorageFactory($injector) {

  'use strict';

  // Since AngularJS 1.4, $cookieStore is deprecated
  var delegate;
  if (angular.version.major === 1 && angular.version.minor >= 4) {
    var $cookies = $injector.get('$cookies');
    delegate = {
      get : function (key) {
        return $cookies.get(key);
      },
      put : function (key, value) {
        $cookies.put(key, value);
      }
    };
  } else {
    var $cookieStore = $injector.get('$cookieStore');
    delegate = {
      get : function (key) {
        return $cookieStore.get(key);
      },
      put : function (key, value) {
        $cookieStore.put(key, value);
      }
    };
  }

  var $translateCookieStorage = {

    /**
     * @ngdoc function
     * @name pascalprecht.translate.$translateCookieStorage#get
     * @methodOf pascalprecht.translate.$translateCookieStorage
     *
     * @description
     * Returns an item from cookieStorage by given name.
     *
     * @param {string} name Item name
     * @return {string} Value of item name
     */
    get : function (name) {
      return delegate.get(name);
    },

    /**
     * @ngdoc function
     * @name pascalprecht.translate.$translateCookieStorage#set
     * @methodOf pascalprecht.translate.$translateCookieStorage
     *
     * @description
     * Sets an item in cookieStorage by given name.
     *
     * @deprecated use #put
     *
     * @param {string} name Item name
     * @param {string} value Item value
     */
    set : function (name, value) {
      delegate.put(name, value);
    },

    /**
     * @ngdoc function
     * @name pascalprecht.translate.$translateCookieStorage#put
     * @methodOf pascalprecht.translate.$translateCookieStorage
     *
     * @description
     * Sets an item in cookieStorage by given name.
     *
     * @param {string} name Item name
     * @param {string} value Item value
     */
    put : function (name, value) {
      delegate.put(name, value);
    }
  };

  return $translateCookieStorage;
}

$translateCookieStorageFactory.displayName = '$translateCookieStorage';
return 'pascalprecht.translate';

}));


text:
The `Bonus` contract is a simple smart contract for distributing some bonus in the form of
ethereum to an owner specified group. One can create a `Bonus` contract and send some ether
to this contract. The person who creates this contract becomes the owner of this contract,
he/she can then register people who will receive the distributed bonus. After a certain point
of time, which is specified during the creation of contract, people can claim their bonus.

The following is an example of using `Bonus` contract in `truffle` suite:

## Preparation
Prerequisites of running this project:
```bash
npm install
alias truffle=$(pwd)/node_modules/truffle/build/cli.bundled.js
truffle init
truffle compile
```

## Change deployed contract
Change the `migrations/2_deploy_contracts.js` file to, suppose we have 100 total tokens and
people can claim their bonus 5 minutes after the creation:
```
var Bonus = artifacts.require('./Bonus.sol')

module.exports = function(deployer) {
    deployer(Bonus, 100, 300)
};
```

## Deploy a Bonus contract
We use the test local blockchain by `testrpc`. In one console, run the `testrpc` by
```bash
testrpc
```

## Interact with the contract
In another console, we use `truffle` console to interact with the test blockchain.
```bash
truffle console
> var bonus
> Bonus.deployed().then(function(inst){bonus = inst; console.log(inst.address)});

> account1 = web3.eth.accounts[0]

> account2 = web3.eth.accounts[1]

> account3 = web3.eth.accounts[2]

// check the owner's balance
> web3.eth.getBalance(account1)

// check the bonus contract's balance
> web3.eth.getBalance(bonus.address)

// send some ether from the owner of this contract (account1 by default)
> web3.eth.sendTransaction({from:acc1, to:bonus.address, value: web3.toWei(1, 'ether')})

// register account2 to receive bonus, e.g. 10% of the share
> bonus.register(account2, 10)

// Check account2's entitled bonus amount in ether
> bonus.getMemberBonus(account2)

// Account2 claim bonus
> bonus.claim({from: account2})

// Check Account2's balance
> web3.eth.getBalance(account2)
// You should see 0.1 ether being added to account2's balance
```


text:
local function compare(first_value, compare_method, second_value)
  if compare_method == "=" then
    return first_value == second_value
  elseif compare_method == "<=" then
    return first_value <= second_value
  elseif compare_method == "<" then
    return first_value < second_value
  elseif compare_method == ">=" then
    return first_value >= second_value
  elseif compare_method == ">" then
    return first_value > second_value
  elseif compare_method == "≠" then
    return first_value ~= second_value
  end
  error("Not a valid compare method: " .. compare_method)
end

return {
  compare = {
    description = "Compare two numbers",
    parameters = { "number", "compare-method", "number" },
    result = "boolean",
    parse = function(params, logic)
      local first = params[1]
      local compare_method = params[2]
      local second = params[3]
      return function(entity, current)
        local first_value = logic.resolve(first, entity, current)
        local second_value = logic.resolve(second, entity, current)
        return compare(first_value, compare_method, second_value)
      end
    end
  },
  boolean_to_number = {
    description = "Convert a boolean to a number. 1 == true and 0 == false",
    parameters = { "boolean" },
    result = "number",
    parse = function(params, logic)
      local value = params[1]
      return function(entity, current)
        local bool = logic.resolve(value, entity, current)
        return bool and 1 or 0
      end
    end
  },
  ["if"] = {
    description = "Perform a command if condition is true",
    parameters = { "boolean", "command" },
    result = "command",
    parse = function(params, logic)
      local param_condition = params[1]
      local param_command = params[2]
      return function(entity, current)
        local condition = logic.resolve(param_condition, entity, current)
        if condition then
          return logic.resolve(param_command, entity, current)
        end
      end
    end
  }
}


text:
<?php

use Illuminate\Database\Seeder;
use TCG\Voyager\Traits\Seedable;

class BreadTemplatesDatabaseUnseeder extends Seeder
{
    use Seedable;

    protected $seedersPath = __DIR__.'/';

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->seed('BreadTemplatesTableUnseeder');
        $this->seed('BreadTemplatesMenuTableUnseeder');
        $this->seed('BreadTemplatesPermissionsTableUnseeder');
        $this->seed('BreadTemplatesDataRowsTableUnseeder');
    }
}


text:
class JsonObjectCleaner < Struct.new :json_object

  def clean_date?
    return true unless has_dates
    date_header = (json_object.keys & date_keys)[0]
    is_parsable_date(json_object[date_header])
  end

  def clean_booleans?
    return true unless has_booleans
    result = true
    these_boolean_headers = json_object.keys & boolean_keys
    these_boolean_headers.each do |b|
      if !is_parsable_boolean(json_object[b])
        result = false
      end
    end
    return result
  end

  def has_dates
    (json_object.keys & date_keys).present?
  end

  def has_booleans
    (json_object.keys & boolean_keys).present?
  end

  def date_keys
    [:event_date, :date_taken, :assessment_date]
  end

  def boolean_keys
    [:asbence, :tardy, :has_exact_time]
  end

  def transform_object
    json_object[:local_id] = json_object[:local_id].to_s
    if has_dates
      date_header = (json_object.keys & date_keys)[0]
      json_object[date_header] = parse_date(json_object[date_header])
    end
    if has_booleans
      these_boolean_headers = json_object.keys & boolean_keys
      these_boolean_headers.each do |b|
        json_object[b] = parse_boolean(json_object[b])
      end
    end
    return json_object
  end

  def is_parsable_boolean(value)
    [true, false, '1', '0', 1, 0, 'true', 'false'].include? value
  end

  def is_parsable_date(value)
    require 'date'
    DateTime.strptime(value.to_s,'%s')
  rescue ArgumentError
    false
  end

  def parse_boolean(value)
    case value
    when "1", 1
      true
    when "0", 0
      false
    else
      nil
    end
  end

  def parse_date(event_date)
    require 'date'
    DateTime.strptime(event_date.to_s,'%s')
  rescue ArgumentError
    nil
  end

end


text:
package au.com.sixtree.mule.modules.xero;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Random;

import org.mule.api.MuleEvent;
import org.mule.construct.Flow;
import org.mule.tck.junit4.AbstractMuleContextTestCase;
import org.mule.tck.junit4.FunctionalTestCase;

public class XeroConnectorTestUtil extends FunctionalTestCase{

	private static String configResourceFile = "xero-connector-config.xml";

    public static String getConfigResourceFile() {
		return configResourceFile;
	}

	protected Flow lookupFlowConstruct(String name)
    {

        Flow result = (Flow)AbstractMuleContextTestCase.muleContext.getRegistry().lookupFlowConstruct(name);
        return result;
    }

    public MuleEvent setupGenericGetObjectTest(String testConstructName) throws Exception
    {
    	Flow flow = lookupFlowConstruct(testConstructName);
    	MuleEvent event = getTestEvent(null);
        MuleEvent responseEvent = flow.process(event);

        return responseEvent;
    }

    public MuleEvent setupGenericGetObjectByIdTest(String testConstructName, String id) throws Exception
    {
    	Flow flow = lookupFlowConstruct(testConstructName);
    	MuleEvent event = getTestEvent(id);
        MuleEvent responseEvent = flow.process(event);

        return responseEvent;
    }

    public MuleEvent setupGenericCreateObjectTest(String testConstructName, String payload) throws Exception
    {
    	Flow flow = lookupFlowConstruct(testConstructName);
    	MuleEvent event = getTestEvent(payload);
        MuleEvent responseEvent = flow.process(event);

        return responseEvent;
    }

    public MuleEvent setupGenericUpdateObjectTest(String testConstructName, String payload) throws Exception
    {
    	Flow flow = lookupFlowConstruct(testConstructName);
    	MuleEvent event = getTestEvent(payload);
        MuleEvent responseEvent = flow.process(event);

        return responseEvent;
    }

    public String readFile(String path) throws IOException {
    	FileInputStream stream = new FileInputStream(new File(path));
    	try {
    		FileChannel fc = stream.getChannel();
    		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    		/* Instead of using default, pass in a decoder. */
    		return Charset.defaultCharset().decode(bb).toString();
    	}
    	finally {
    		stream.close();
    	}
    }

    public String generateRandomString(){
    	long currentTime = System.currentTimeMillis();
    	Random randGenerator = new Random(currentTime);
    	int randomNumberInt = randGenerator.nextInt(99999999) + 10000000;
    	String randomNumberString = Integer.toString(randomNumberInt);

    	return randomNumberString;
    }

	@Override
	protected String getConfigResources() {
		return configResourceFile;
	}

}


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

<title>Code Igniter User Guide</title>

<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />
<meta name='author' content='Rick Ellis' />
<meta name='description' content='Code Igniter User Guide' />

Code Igniter User Guide Version 1.5.1

Table of Contents Page

Code Igniter Home  ›
User Guide Home  ›
Database Library  ›
Query Helpers

<form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="www.codeigniter.com/user_guide/" />Search User Guide  <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" /> <input type="submit" class="submit" name="sa" value="Go" /></form>

Query Helper Functions

$this->db->insert_id()

The insert ID number when performing database inserts.

$this->db->affected_rows()

Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).

Note:  In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the
correct number of affected rows.  By default this hack is enabled but it can be turned off in the database driver file.

$this->db->count_all();

Permits you to determine the number of rows in a particular table.  Submit the table name in the first parameter. Example:

echo $this->db->count_all('<var>my_table</var>');

// Produces an integer, like 25

$this->db->platform()

Outputs the database platform you are running (MySQL, MS SQL, Postgre, etc...):

echo $this->db->platform();

$this->db->version()

Outputs the database version you are running:

echo $this->db->version();

$this->db->last_query();

Returns the last query that was run (the query string, not the result).  Example:

$str = $this->db->last_query();

// Produces:  SELECT * FROM sometable....

The following two functions help simplify the process of writing database INSERTs and UPDATEs.

$this->db->insert_string();

This function simplifies the process of writing database inserts. It returns a correctly formatted SQL insert string. Example:

$data = array('name' => $name, 'email' => $email, 'url' => $url);

$str = $this->db->insert_string('table_name', $data);

The first parameter is the table name, the second is an associative array with the data to be inserted.  The above example produces:

INSERT INTO table_name (name, email, url) VALUES ('Rick', 'rick@your-site.com', 'www.your-site.com')

Note: Values are automatically escaped, producing safer queries.

$this->db->update_string();

This function simplifies the process of writing database updates. It returns a correctly formatted SQL update string. Example:

$data = array('name' => $name, 'email' => $email, 'url' => $url);

$where = "author_id = 1 AND status = 'active'";

$str = $this->db->update_string('table_name', $data, $where);

The first parameter is the table name, the second is an associative array with the data to be inserted, and the third parameter is the "where" clause. The above example produces:

 UPDATE exp_weblog SET name = 'Rick', email = 'rick@your-site.com', url = 'www.your-site.com' WHERE author_id = 1 AND status = 'active'

Note: Values are automatically escaped, producing safer queries.

Previous Topic:  Query Results
   ·
Top of Page   ·
User Guide Home   ·
Next Topic:  Active Record Pattern

Code Igniter  ·  Copyright © 2006  ·  pMachine, Inc.


text:
package org.geepawhill.server;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class LiveServer implements SimpleServer
{
	private final CloseableHttpClient client;

	public LiveServer(CloseableHttpClient client)
	{
		this.client = client;
	}

	public LiveServer()
	{
		this(HttpClients.createDefault());
	}

	@Override
	public SimpleResponse execute(HttpUriRequest request) throws Exception
	{
		return new SimpleResponse(client.execute(request));
	}
}


text:
#ifndef SSD_CACHE_H_
#define SSD_CACHE_H_

#include <atomic>
#include <fcntl.h>
#include <functional>
#include <iostream>
#include <unistd.h>
#include <unordered_map>
#include <vector>

#include "leveldb/status.h"
#include "port/port.h"
#include "util/hash.h"
#include "util/mutexlock.h"

namespace leveldb {

static const int kSegmentOffsetBits = 18; // For 256K segments
static const int kSegmentNumBits = 64 - kSegmentOffsetBits;
static const int kSegmentSize = 1 << kSegmentOffsetBits;
static const int kSegmentOffsetMask = kSegmentSize-1;

#define SEGMENT_NUM(x) (x >> kSegmentOffsetBits)
#define SEGMENT_OFF(x) (x & kSegmentOffsetMask)
#define ADDRESS(segment, off) ((segment << kSegmentOffsetBits) | off)

struct Segment {
  uint32_t num;
  uint32_t size;
  uint32_t curr_offset;
  uint32_t garbage_bytes;

  Segment(uint32_t n, uint32_t sz): num(n), size(sz) { curr_offset = 0; garbage_bytes = 0; }

  double Unused() const {
    double total_unused = garbage_bytes + (size - curr_offset);
    return static_cast<double>(total_unused) / static_cast<double>(size);
  }

  uint32_t BytesAvailable() const { return size - curr_offset; }

  void MarkGarbage(uint64_t nbytes) { garbage_bytes += nbytes; }

  uint64_t StartOffset() const { return num * size; }
};

class SegmentManager {
 public:

 private:
  uint32_t segment_size;
  std::vector<Segment> segments_;
  int i;

 public:
  SegmentManager(size_t sz);

  inline Segment* NextSegment() { return &segments_[i++]; }

  inline Segment* GetSegment(int seg_num) { return &segments_[seg_num]; }
};

struct IndexEntry {
  uint64_t off;
  uint32_t len; // total length of entry on-disk (include key size)
  uint32_t key_len;
  //char* key_; // pointer to heap-allocated key
  uint32_t hash;

  IndexEntry* prev;
  IndexEntry* next;
  IndexEntry* next_hash;

  char key_[1];   // Beginning of key

  Slice key() const { return Slice{key_, key_len}; }
};

class HandleTable {
 public:
  HandleTable() : length_(0), elems_(0), list_(NULL) { Resize(); }
  ~HandleTable() {
      for (uint32_t i = 0; i < length_; i++) {
          IndexEntry* h = list_[i];
          while (h != NULL) {
              IndexEntry* next = h->next_hash;
              free(h);
              h = next;
          }
      }
      delete[] list_;
  }

  IndexEntry* Lookup(const Slice& key, uint32_t hash) {
    return *FindPointer(key, hash);
  }

  IndexEntry* Insert(IndexEntry* h) {
    IndexEntry** ptr = FindPointer(h->key(), h->hash);
    IndexEntry* old = *ptr;
    h->next_hash = (old == NULL ? NULL : old->next_hash);
    *ptr = h;
    if (old == NULL) {
      ++elems_;
      if (elems_ > length_) {
        // Since each cache entry is fairly large, we aim for a small
        // average linked list length (<= 1).
        Resize();
      }
    }
    return old;
  }

  IndexEntry* Remove(const Slice& key, uint32_t hash) {
    IndexEntry** ptr = FindPointer(key, hash);
    IndexEntry* result = *ptr;
    if (result != NULL) {
      *ptr = result->next_hash;
      --elems_;
    }
    return result;
  }

  uint32_t Size() const { return elems_; }

 private:
  // The table consists of an array of buckets where each bucket is
  // a linked list of cache entries that hash into the bucket.
  uint32_t length_;
  uint32_t elems_;
  IndexEntry** list_;

  // Return a pointer to slot that points to a cache entry that
  // matches key/hash.  If there is no such cache entry, return a
  // pointer to the trailing slot in the corresponding linked list.
  IndexEntry** FindPointer(const Slice& key, uint32_t hash) {
    IndexEntry** ptr = &list_[hash & (length_ - 1)];
    while (*ptr != NULL &&
           ((*ptr)->hash != hash || key != (*ptr)->key())) {
      ptr = &(*ptr)->next_hash;
    }
    return ptr;
  }

  void Resize() {
    uint32_t new_length = 4;
    while (new_length < elems_) {
      new_length *= 2;
    }
    IndexEntry** new_list = new IndexEntry*[new_length];
    memset(new_list, 0, sizeof(new_list[0]) * new_length);
    uint32_t count = 0;
    for (uint32_t i = 0; i < length_; i++) {
      IndexEntry* h = list_[i];
      while (h != NULL) {
        IndexEntry* next = h->next_hash;
        uint32_t hash = h->hash;
        IndexEntry** ptr = &new_list[hash & (new_length - 1)];
        h->next_hash = *ptr;
        *ptr = h;
        h = next;
        count++;
      }
    }
    assert(elems_ == count);
    delete[] list_;
    list_ = new_list;
    length_ = new_length;
  }
};

class SsdCache {

 private:
  static inline uint32_t HashSlice(const Slice& key) {
    return Hash(key.data(), key.size(), 0);
  }

  static inline bool KeyEquals(const Slice& k1, const Slice& k2) {
    return k1 == k2;
  }

  // The name of the file used by this cache
  std::string cache_fname_;

  // The file descriptor of the cache file if the cache has been opened
  int fd_;
  port::Mutex mutex_;

  // The class that manages the segments in the file
  SegmentManager segment_manager_;
  Segment* active_segment_;

  // Write Buffer
  char buf_[kSegmentSize];

  // Read buffer
  char rbuf_[kSegmentSize];

  // The maximum size of the cache (in bytes)
  uint64_t capacity_;
  uint64_t curr_size_;

  // The in-memory index that maps keys to offset into the file
  /*
  std::unordered_map<
    Slice,
    IndexEntry*,
    std::function<decltype(HashSlice)>,
    std::function<decltype(KeyEquals)>> index_;
  */

  HandleTable table_;

  // LRU
  IndexEntry dummy_;

 public:
  explicit SsdCache(std::string cache_dir, size_t capacity);

  ~SsdCache();

  bool Insert(const Slice& key, void* value, size_t size);

  void Lookup(const Slice& key, void* arg, void (*saver)(void*, const Slice& key, const Slice& val));

  void Erase(const Slice& key);

  //inline bool ContainsKey(const Slice& key) const { return index_.find(key) != index_.end(); }
  inline bool ContainsKey(const Slice& key) { return table_.Lookup(key, HashSlice(key)) != nullptr; }

  //inline uint64_t NumKeys() const { return index_.size(); }
  inline uint64_t NumKeys() const { return table_.Size(); }

  Status Open() {
    fd_ = open(cache_fname_.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR );
    if (fd_ < 0) {
      // error
      std::cout << "Error opening file: " << strerror(errno) << std::endl;
      return Status::IOError(cache_fname_, strerror(errno));
    }
    return Status::OK();
  }

 private:
  // Persist current active segment and start using a new one
  void RollSegment();

  // Append the parameters to the current active segment
  uint64_t AppendToSegment(const Slice& key, void* value, size_t sz);

  // Ensure there is sufficient room in the index for the given kv pair
  void MakeRoomForInsert(const Slice& key, size_t sz);

  // Remove the key (and it's value) from the index and cleanup resources
  void Remove(IndexEntry* e);

  void LRU_Append(IndexEntry* e);

  void LRU_Remove(IndexEntry* e);
};

} // namespace

#endif


text:
@media projection, screen { .ui-tabs-hide { display:none; } }
@media print { .ui-tabs-nav { display: none; } }

.flora .ui-tabs-nav,
.flora.ui-tabs-nav {
  padding-left:10px;
  float:left;
  width:98%;
  border-bottom:1px solid #FFF;
  margin:0;
}
.flora .ui-tabs-nav li,
.flora.ui-tabs-nav li {
  list-style:none;
  float:left;
 }
.flora .ui-tabs-nav a,
.flora.ui-tabs-nav a {
  background:url(i/tabs.gif) no-repeat left 4px;
  display:block;
  height:27px;
  padding:0 0 0 4px;
  text-decoration:none!important;
  margin:1px 5px -2px 0;
  font:9pt Verdana;
  outline:none;
}
.flora .ui-tabs-nav span,
.flora.ui-tabs-nav span {
  background:url(i/tabs.gif) no-repeat right 4px;
  display:block;
  height:27px;
  line-height:29px;
  padding:0px 13px 0 10px;
  margin-right:-3px;
  color:#FFF;
}
.flora .ui-tabs-nav .ui-tabs-selected a,
.flora.ui-tabs-nav .ui-tabs-selected a {
  background-position:left -23px;
}
.flora .ui-tabs-nav .ui-tabs-selected a span,
.flora.ui-tabs-nav .ui-tabs-selected a span {
  background-position:right -23px;
  margin-bottom:0;
  cursor:default;
  }
.flora .ui-tabs-nav .ui-tabs-disabled a,
.flora .ui-tabs-nav .ui-tabs-disabled a span,
.flora.ui-tabs-nav .ui-tabs-disabled a,
.flora.ui-tabs-nav .ui-tabs-disabled a span {
  color:#000;
  opacity:0.4;
  filter:alpha(opacity=40);
  cursor:default;
}
.flora .ui-tabs-container,
.flora.ui-tabs-container {
  background:#FFF;
  border:1px solid #519E2D;
  clear:left;
  padding:10px 10px 8px 10px;
  *padding-top:3px;
  *margin-top:-24px;
}


text:
var restClient = require('node-rest-client').Client,
	restcli = new restClient(),
	underscore = require('underscore');

exports.injectSetting = function ( req, res, view, locals ) {
	// don't we need some sort of caching here? - Mark

	restcli.get("http://localhost:5000/api/v1/settings/", function (data, response) {
		module.exports.data = underscore.extend(locals, JSON.parse(data));
		console.log(module.exports.data);
		res.render(view, module.exports.data);
	});
};


text:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

/**
 * default
 */
Route::get('/', 'Admin\DashboardController@index')->name('admin.dashboard');

/**
 * Auth routes
 */
Route::group(['namespace' => 'Auth'], function () {

    // Authentication Routes...
    Route::get('login', 'LoginController@showLoginForm')->name('login');
    Route::post('login', 'LoginController@login');
    Route::get('logout', 'LoginController@logout')->name('logout');

    // Registration Routes...
    if (config('auth.users.registration')) {
        Route::get('register', 'RegisterController@showRegistrationForm')->name('register');
        Route::post('register', 'RegisterController@register');
    }

    // Password Reset Routes...
    Route::get('password/reset', 'ForgotPasswordController@showLinkRequestForm')->name('password.request');
    Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    Route::get('password/reset/{token}', 'ResetPasswordController@showResetForm')->name('password.reset');
    Route::post('password/reset', 'ResetPasswordController@reset');

    // Confirmation Routes...
    if (config('auth.users.confirm_email')) {
        Route::get('confirm/{user_by_code}', 'ConfirmController@confirm')->name('confirm');
        Route::get('confirm/resend/{user_by_email}', 'ConfirmController@sendEmail')->name('confirm.send');
    }
});

/**
 * Backend routes
 */
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {

    //Users
    Route::get('users', 'UserController@index')->name('users');
    Route::get('users/{user}', 'UserController@show')->name('users.show');
    Route::get('users/{user}/edit', 'UserController@edit')->name('users.edit');
    Route::put('users/{user}', 'UserController@update')->name('users.update');
    Route::delete('users/{user}', 'UserController@destroy')->name('users.destroy');
    Route::get('permissions', 'PermissionController@index')->name('permissions');
    Route::get('permissions/{user}/repeat', 'PermissionController@repeat')->name('permissions.repeat');
});

Route::group(['prefix' => 'admin', 'as' => 'cadastro.', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {

    Route::resource('pessoa', 'PessoasController');
    Route::resource('produto', 'ProdutosController');

    Route::post('ajax/categoria/destroy', 'ProdutosController@categoriaDestroy')->name('produto.categoria.destroy');

});

Route::group(['prefix' => 'admin', 'as' => 'operacional.', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {

    Route::resource('venda', 'VendasController');
    Route::get('ajax/produto/attributes', 'VendasController@produtoAttributes')->name('venda.produto.attributes');

    Route::resource('movimento', 'MovimentosController');

    Route::resource('compra', 'ComprasController');
    Route::get('ajax/compra/produto/preco', 'ComprasController@produtoPreco')->name('compra.produto.preco');

    Route::resource('estoque', 'EstoqueProdutosController');

});

Route::group(['prefix' => 'admin', 'as' => 'administrativo.', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {

    Route::get('relacao_vendas', 'AdminController@relacaoVendas')->name('relacao_vendas');
    Route::get('ajax/table-relacao_vendas', 'AdminController@getRelacaoVendasDataTable')->name('ajax.table-relacao-vendas');
    Route::get('relacao_produtos', 'AdminController@relacaoProdutos')->name('relacao_produtos');
    Route::get('ajax/table-relacao_produtos', 'AdminController@getRelacaoProdutosDataTable')->name('ajax.table-relacao-produtos');
    Route::get('balanco', 'AdminController@balanco')->name('balanco');

});

Route::group(['prefix' => 'admin', 'as' => 'financeiro.', 'namespace' => 'Admin', 'middleware' => 'auth'], function () {

    Route::resource('centros_custo', 'FinanceiroCentrosController');
    Route::resource('categorias', 'FinanceiroCategoriasController');
    Route::get('ajax/table-categorias', 'FinanceiroCategoriasController@getDataTable')->name('ajax.table-categorias');
    Route::get('resumo_centros_custo', 'FinanceiroCentrosController@resumo')->name('resumo_centros_custo');
    Route::resource('recebimentos', 'RecebimentosController');
    Route::get('ajax/table-recebimentos', 'RecebimentosController@getDataTable')->name('ajax.table-recebimentos');
    Route::resource('pagamentos', 'PagamentosController');
    Route::get('ajax/table-pagamentos', 'PagamentosController@getDataTable')->name('ajax.table-pagamentos');
    Route::resource('caixa', 'CaixaController');
    Route::resource('fiado', 'FiadoPessoasController');
    Route::get('ajax/table-fiado-vendas', 'FiadoPessoasController@getVendasDataTable')->name('ajax.table-fiado-vendas');
    Route::get('ajax/table-fiado-recebimentos', 'FiadoPessoasController@getRecebimentosDataTable')->name('ajax.table-fiado-recebimentos');
    Route::get('ajax/table-fiado-recebimentos/destroy/{id}', 'FiadoPessoasController@recebimentoDestroy')->name('ajax.table-fiado-recebimentos.destroy');
    Route::resource('fechamento', 'FechamentoController');

    Route::get('ajax/table-fechamento-dinheiro', 'RecebimentosController@getFechamentoDinheiro')->name('ajax.table-fechamento-dinheiro');
    Route::get('ajax/table-fechamento-cartao', 'RecebimentosController@getFechamentoCartao')->name('ajax.table-fechamento-cartao');
    Route::get('ajax/table-fechamento-pagamentos', 'PagamentosController@getFechamentoPagamentos')->name('ajax.table-fechamento-pagamentos');

});

Route::group(['prefix' => 'admin', 'as' => 'configuracao.', 'namespace' => 'Admin', 'middleware' => 'admin'], function () {

    Route::resource('configuracao', 'ConfigController');

});


text:
import angular from "angular";
import _ from "lodash";
import {initialiseData} from "../../common";
import template from "./tag-edit.html";
import {CORE_API} from "../../common/services/core-api-utils";

/**
 * @name waltz-keyword-edit
 *
 * @description
 * This component ...
 */

const bindings = {
    onCancel: "<",
    onSave: "<",
    keywords: "<",
    entityKind: "<"
};

const initialState = {};

function controller(serviceBroker) {
    const vm = this;

    vm.$onInit = () => initialiseData(vm, initialState);

    vm.$onChanges = (c) => {
        vm.working = angular.copy(vm.keywords);
    };

    vm.save = () => {
        const values = _.map(vm.working, "name");
        serviceBroker
            .loadViewData(
                CORE_API.TagStore.findTagsByEntityKind,
                [vm.entityKind], {force : true})
            .then(r => {
                const diff = _.difference(values, _.map(r.data, d => d.name));
                const message = _.isEmpty(diff)
                    ? "Updated Tags" : `New Tag [${diff}] created`;
                vm.onSave(values, message);
            });

    };

    vm.onKeyDown = (event) => {
        if (event.ctrlKey && event.keyCode === 13) {
            // ctrl + enter
            vm.save();
            vm.onCancel();
        }
    };

    vm.loadExistingTags = (query) => {
        const filterTags = (availableTags) => {
            return _.filter(availableTags,
                tag => tag.name.toLowerCase().indexOf(query.toLowerCase()) !== -1);
        };

        return serviceBroker
            .loadViewData(
                CORE_API.TagStore.findTagsByEntityKind,
                [vm.entityKind])
            .then(r => filterTags(r.data));
    };
}

controller.$inject = [ "ServiceBroker" ];

const component = {
    template,
    bindings,
    controller
};

export default component;


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.UseObjectInitializer
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
    <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseObjectInitializer), [Shared]>
    Friend Class VisualBasicUseObjectInitializerCodeFixProvider
        Inherits AbstractUseObjectInitializerCodeFixProvider(Of
            SyntaxKind,
            ExpressionSyntax,
            StatementSyntax,
            ObjectCreationExpressionSyntax,
            MemberAccessExpressionSyntax,
            AssignmentStatementSyntax,
            VariableDeclaratorSyntax)

        <ImportingConstructor>
        <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
        Public Sub New()
        End Sub

        Protected Overrides Function GetNewStatement(
                statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax,
                matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As StatementSyntax
            Dim newStatement = statement.ReplaceNode(
                objectCreation,
                GetNewObjectCreation(objectCreation, matches))

            Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance()
            totalTrivia.AddRange(statement.GetLeadingTrivia())
            totalTrivia.Add(SyntaxFactory.ElasticMarker)

            For Each match In matches
                For Each trivia In match.Statement.GetLeadingTrivia()
                    If trivia.Kind = SyntaxKind.CommentTrivia Then
                        totalTrivia.Add(trivia)
                        totalTrivia.Add(SyntaxFactory.ElasticMarker)
                    End If
                Next
            Next

            Return newStatement.WithLeadingTrivia(totalTrivia)
        End Function

        Private Function GetNewObjectCreation(
                objectCreation As ObjectCreationExpressionSyntax,
                matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As ObjectCreationExpressionSyntax

            Return UseInitializerHelpers.GetNewObjectCreation(
                objectCreation,
                SyntaxFactory.ObjectMemberInitializer(
                    CreateFieldInitializers(matches)))
        End Function

        Private Function CreateFieldInitializers(
                matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As SeparatedSyntaxList(Of FieldInitializerSyntax)
            Dim nodesAndTokens = New List(Of SyntaxNodeOrToken)

            For i = 0 To matches.Length - 1
                Dim match = matches(i)

                Dim rightValue = match.Initializer
                If i < matches.Length - 1 Then
                    rightValue = rightValue.WithoutTrailingTrivia()
                End If

                Dim initializer = SyntaxFactory.NamedFieldInitializer(
                    keyKeyword:=Nothing,
                    dotToken:=match.MemberAccessExpression.OperatorToken,
                    name:=SyntaxFactory.IdentifierName(match.MemberName),
                    equalsToken:=match.Statement.OperatorToken,
                    expression:=rightValue).WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker)

                nodesAndTokens.Add(initializer)
                If i < matches.Length - 1 Then
                    Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken).
                                              WithTrailingTrivia(match.Initializer.GetTrailingTrivia())
                    nodesAndTokens.Add(comma)
                End If
            Next

            Return SyntaxFactory.SeparatedList(Of FieldInitializerSyntax)(nodesAndTokens)
        End Function
    End Class
End Namespace


text:
'use strict';

const path = require('path');
const {cyan, green, red} = require('../common/colors');
const {log, logLocalDev} = require('../common/logging');

const expectedCaches = ['google', 'bing'];
const cachesJsonPath = '../global-configs/caches.json';

/**
 * Entry point for amp caches-jason.
 * @return {Promise<void>}
 */
async function cachesJson() {
  const filename = path.basename(cachesJsonPath);
  let jsonContent;
  try {
    jsonContent = require(cachesJsonPath);
  } catch (e) {
    log(red('ERROR:'), 'Could not parse', cyan(filename));
    process.exitCode = 1;
    return;
  }
  const foundCaches = [];
  for (const foundCache of jsonContent.caches) {
    foundCaches.push(foundCache.id);
  }
  for (const cache of expectedCaches) {
    if (foundCaches.includes(cache)) {
      logLocalDev(green('✔'), 'Found', cyan(cache), 'in', cyan(filename));
    } else {
      log(red('✖'), 'Missing', cyan(cache), 'in', cyan(filename));
      process.exitCode = 1;
    }
  }
}

module.exports = {
  cachesJson,
};

cachesJson.description = 'Check that caches.json contains all expected caches';