text:
function run(generator, res) {
    const ret = generator.next(res);
    console.log(ret)
    if (ret.done) return;
    ret.value.then(function (res) {
        run(generator, res);
    });
}

let count = 1;
function tick(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('tick %s after %s ms', count++, time);
            resolve();
        }, time);
    });
}
function* main() {
    console.log('start run...');
    yield tick(500);
    yield tick(1000);
    yield tick(2000);
}
run(main());

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Backbone.js with IndexedDB and Dexie.js</title>
	<link href="style/css/bootstrap.min.css" rel="stylesheet">
	<link href="style/main.css" rel="stylesheet">

		<image style="float:right;width: 50px;height:50px;" src="github-10-xxl.png"></image>

Backbone.js with IndexedDB and Dexie.js

This demo application displays the use of Backbone.js with IndexedDB and Dexie.js to build a fully client-side application.

Feel free to edit the data on this page and then refresh your browser to see it stick!

Learn More:

indexedDB

Dexie.js

Backbone.sync


text:
# Non-Enumerable Read-Only Accessor

> [Define][@stdlib/utils/define-property] a non-enumerable **read-only** accessor.

## Usage

```javascript
var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
```

#### setNonEnumerableReadOnlyAccessor( obj, prop, getter )

[Defines][@stdlib/utils/define-property] a non-enumerable **read-only** accessor.

```javascript
function getter() {
    return 'bar';
}

var obj = {};

setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );

obj.foo = 'boop';
// throws <Error>
```

## Notes

-   Non-enumerable read-only accessors are **non-configurable**.

## Examples

```javascript
var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );

function Foo( name ) {
    if ( !(this instanceof Foo) ) {
        return new Foo( name );
    }
    setNonEnumerableReadOnlyAccessor( this, 'name', getName );
    return this;

    function getName() {
        return name;
    }
}

var foo = new Foo( 'beep' );

try {
    foo.name = 'boop';
} catch ( err ) {
    console.error( err.message );
}
```

* * *

## See Also

-   [`@stdlib/utils/define-nonenumerable-property`][@stdlib/utils/define-nonenumerable-property]: define a non-enumerable property.
-   [`@stdlib/utils/define-nonenumerable-read-only-property`][@stdlib/utils/define-nonenumerable-read-only-property]: define a non-enumerable read-only property.
-   [`@stdlib/utils/define-nonenumerable-read-write-accessor`][@stdlib/utils/define-nonenumerable-read-write-accessor]: define a non-enumerable read-write accessor.
-   [`@stdlib/utils/define-nonenumerable-write-only-accessor`][@stdlib/utils/define-nonenumerable-write-only-accessor]: define a non-enumerable write-only accessor.
-   [`@stdlib/utils/define-read-only-accessor`][@stdlib/utils/define-read-only-accessor]: define a read-only accessor.

[@stdlib/utils/define-property]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-property

[@stdlib/utils/define-nonenumerable-property]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-nonenumerable-property

[@stdlib/utils/define-nonenumerable-read-only-property]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-nonenumerable-read-only-property

[@stdlib/utils/define-nonenumerable-read-write-accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-nonenumerable-read-write-accessor

[@stdlib/utils/define-nonenumerable-write-only-accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-nonenumerable-write-only-accessor

[@stdlib/utils/define-read-only-accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/utils/define-read-only-accessor


text:
var isogroup;
$(function() {
    isogroup = new Isogroup('.resources-container');

    var filterIso = function(list) {
        isogroup.filter(list);
        ga('send', 'event', 'Resource Action', 'Filter resources', list);
    }

    filter = new Filter('.file-type-group', file_types, filterIso);

    $.each(file_types, function(i, type) {
        var count = isogroup.$el.find('.' + type).length;
        $('.file-type-group .' + type + ' .count').html("(" + count + ")");
    });

    $('.layout').click(function() {
        var layout = $(this).data('layout');
        $('.layout').not('[data-layout=' + layout + ']').removeClass('active');
        $(this).addClass('active');

        if (layout == 'list') {
            isogroup.$el.find('.icon-140').removeClass('icon-140').addClass('.icon-32');
        } else {
            isogroup.$el.find('.icon-32').removeClass('icon-32').addClass('.icon-140');
        }

        $('body').removeClass('cards list').addClass(layout);
        isogroup.$el.isotope();
    });

    $('.delete').click(function(event) {
        event.preventDefault();
        var el = $(this);
        var csrf = $('[name="csrfmiddlewaretoken"]').val();
        console.log(csrf);
        var url = el.attr('href');
        bootbox.dialog({
            message: "Are you sure you want to remove this file?",
            className: "remove-modal",
            onEscape: function () {},
            buttons: {
                remove: {
                    label: "Remove",
                    className: "btn btn-primary btn-remove",
                    callback: function() {
                        $.post(url, {'csrfmiddlewaretoken': csrf}, function(data) {
                            if(data.success) {
                                isogroup.$el.isotope('remove', el.closest('.item')).isotope('reLayout');
                            } else {
                                bootbox.alert("We couldn't deleted the selected file. Reason: " + data.error);
                            }
                        });
                    }
                },
                cancel: {
                    label: "Cancel",
                    className: "btn btn-danger btn-remove"
                }
            }
        });
    });

    // Start with grid

    $('body').addClass('cards');

});


text:
package com.acadiasoft.im.simm.model.param;

import com.acadiasoft.im.simm.model.imtree.identifiers.WeightingClass;

import java.math.BigDecimal;

public interface SimmFxSensitivityCorrelation {

  public BigDecimal getSensitivityCorrelation(WeightingClass r, WeightingClass s, String calculationCurrency);

}


text:
import React from 'react';
import classnames from 'classnames';

import {CSS_CLASSES, DEVICE_TYPE} from './constant';

export type TwelveColumn = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
export type FourColumn = 1 | 2 | 3 | 4;
export type EightColumn = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
export type Alignment = 'bottom' | 'middle' | 'top';

export interface CellProps<T> extends React.HTMLProps<T> {
  align?: Alignment;
  className?: string;
  columns?: TwelveColumn;
  desktopColumns?: TwelveColumn;
  order?: TwelveColumn;
  phoneColumns?: FourColumn;
  tabletColumns?: EightColumn;
  tag?: string;
}

const Cell: <T extends {} = HTMLDivElement>(
  props: CellProps<T>
) => React.ReactElement<any> = ({
  align,
  children,
  className = '',
  columns,
  desktopColumns,
  order,
  phoneColumns,
  tabletColumns,
  tag: Tag = 'div',
  ...otherProps
}) => {
  const classes = classnames(CSS_CLASSES.CELL, className, {
    [`${CSS_CLASSES.CELL_ALIGN}-${align}`]: !!align,
    [`${CSS_CLASSES.CELL_ORDER}-${order}`]: !!order,
    [`${CSS_CLASSES.CELL_SPAN}-${columns}`]: !!columns,
    [`${CSS_CLASSES.CELL_SPAN}-${desktopColumns}-${DEVICE_TYPE.DESKTOP}`]: !!desktopColumns,
    [`${CSS_CLASSES.CELL_SPAN}-${phoneColumns}-${DEVICE_TYPE.PHONE}`]: !!phoneColumns,
    [`${CSS_CLASSES.CELL_SPAN}-${tabletColumns}-${DEVICE_TYPE.TABLET}`]: !!tabletColumns,
  });

  return (
    // https://github.com/Microsoft/TypeScript/issues/28892
    // @ts-ignore
    <Tag className={classes} {...otherProps}>
      {children}
    </Tag>
  );
};

export default Cell;


text:
import React from 'react';

import { Meta, Story } from '@storybook/react/dist/client/preview/types-6-0';

import { Anchor } from '../components/Anchor/Anchor';
import { IAnchorComponentProps } from '../components/Anchor/model';

import GlobalStyle from '../components/Styled/GlobalStyles';

export default ({
	component: Anchor,
	title: 'Example/Anchor'
} as any) as Meta;

const Template: Story<IAnchorComponentProps> = (args) => {
	return (
		<>
			<GlobalStyle />
			<Anchor {...args} onClick={(e: React.MouseEvent<HTMLElement>) => alert('Being redirected...')} />
		</>
	);
};

export const Normal = Template.bind({});
Normal.args = {
	children: 'VIEW CAMPAIGN',
	href: 'https://www.moosend.com'
} as IAnchorComponentProps;

export const Disabled = Template.bind({});
Disabled.args = {
	children: 'VIEW CAMPAIGN',
	disabled: true,
	href: 'https://www.moosend.com'
} as IAnchorComponentProps;


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die;

if ($ADMIN->fulltree) {
    require_once("$CFG->libdir/resourcelib.php");

    $displayoptions = resourcelib_get_displayoptions(array(RESOURCELIB_DISPLAY_OPEN, RESOURCELIB_DISPLAY_POPUP));
    $defaultdisplayoptions = array(RESOURCELIB_DISPLAY_OPEN);

    //--- general settings -----------------------------------------------------------------------------------
    $settings->add(new admin_setting_configcheckbox('page/requiremodintro',
        get_string('requiremodintro', 'admin'), get_string('configrequiremodintro', 'admin'), 1));
    $settings->add(new admin_setting_configmultiselect('page/displayoptions',
        get_string('displayoptions', 'page'), get_string('configdisplayoptions', 'page'),
        $defaultdisplayoptions, $displayoptions));

    //--- modedit defaults -----------------------------------------------------------------------------------
    $settings->add(new admin_setting_heading('pagemodeditdefaults', get_string('modeditdefaults', 'admin'), get_string('condifmodeditdefaults', 'admin')));

    $settings->add(new admin_setting_configcheckbox('page/printintro',
        get_string('printintro', 'page'), get_string('printintroexplain', 'page'), 0));
    $settings->add(new admin_setting_configselect('page/display',
        get_string('displayselect', 'page'), get_string('displayselectexplain', 'page'), RESOURCELIB_DISPLAY_OPEN, $displayoptions));
    $settings->add(new admin_setting_configtext('page/popupwidth',
        get_string('popupwidth', 'page'), get_string('popupwidthexplain', 'page'), 620, PARAM_INT, 7));
    $settings->add(new admin_setting_configtext('page/popupheight',
        get_string('popupheight', 'page'), get_string('popupheightexplain', 'page'), 450, PARAM_INT, 7));
}


text:
package org.camunda.feel.interpreter.impl

import org.scalatest.{FlatSpec, Matchers}
import org.camunda.feel.syntaxtree._

/**
  * @author Philipp Ossler
  */
class InterpreterStringExpressionTest
    extends FlatSpec
    with Matchers
    with FeelIntegrationTest {

  "A string" should "concatenates to another String" in {

    eval(""" "a" + "b" """) should be(ValString("ab"))
  }

  it should "compare with '='" in {

    eval(""" "a" = "a" """) should be(ValBoolean(true))
    eval(""" "a" = "b" """) should be(ValBoolean(false))
  }

  it should "compare with '!='" in {

    eval(""" "a" != "a" """) should be(ValBoolean(false))
    eval(""" "a" != "b" """) should be(ValBoolean(true))
  }

  it should "compare with '<'" in {

    eval(""" "a" < "b" """) should be(ValBoolean(true))
    eval(""" "b" < "a" """) should be(ValBoolean(false))
  }

  it should "compare with '<='" in {

    eval(""" "a" <= "a" """) should be(ValBoolean(true))
    eval(""" "b" <= "a" """) should be(ValBoolean(false))
  }

  it should "compare with '>'" in {

    eval(""" "b" > "a" """) should be(ValBoolean(true))
    eval(""" "a" > "b" """) should be(ValBoolean(false))
  }

  it should "compare with '>='" in {

    eval(""" "b" >= "b" """) should be(ValBoolean(true))
    eval(""" "a" >= "b" """) should be(ValBoolean(false))
  }

  it should "compare with null" in {

    eval(""" "a" = null """) should be(ValBoolean(false))
    eval(""" null = "a" """) should be(ValBoolean(false))
    eval(""" "a" != null """) should be(ValBoolean(true))
  }

}


text:
      Thêm

          <ng-template let-khachHang="rowData" pTemplate="body">

            <button class="btn btn-primary btn-circle" (click)="remove(khachHang._id)"></button>
          </ng-template>


text:
package com.blastedstudios.freeboot.util.ui;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.blastedstudios.gdxworld.util.Log;

public class UIHelper {
	public static Color getColor(Skin skin, String... names){
		for(String name : names)
			try{
				return skin.getColor(name);
			}catch(GdxRuntimeException e){}
		handleError("Color", names);
		return null;
	}

	public static BitmapFont getFont(Skin skin, String... names){
		for(String name : names)
			try{
				return skin.getFont(name);
			}catch(GdxRuntimeException e){}
		handleError("Font", names);
		return null;
	}

	public static Sprite getSprite(Skin skin, String... names){
		for(String name : names)
			try{
				return skin.getSprite(name);
			}catch(GdxRuntimeException e){}
		handleError("Sprite", names);
		return null;
	}

	public static NinePatch getPatch(Skin skin, String... names){
		for(String name : names)
			try{
				return skin.getPatch(name);
			}catch(GdxRuntimeException e){}
		handleError("Patch", names);
		return null;
	}

	private static void handleError(String origin, String... names){
		StringBuffer buf = new StringBuffer("No match for name(s) ");
		for(String name : names)
			buf.append(name + ",");
		Log.debug("UIHelper.get" + origin, buf.toString());
	}
}


text:
package chapter_11.activation;

import chapter_11.warehouse.Warehouse;

import java.io.IOException;
import java.rmi.MarshalledObject;
import java.rmi.RemoteException;
import java.rmi.activation.Activatable;
import java.rmi.activation.ActivationID;
import java.util.Map;

/**
 * This class is the implementation for the remote Warehouse interface.
 * @author Jerry-0824
 * @version 1.0.0 2017-01-03 20:22
 */
public class WarehouseImpl extends Activatable implements Warehouse{
    private Map<String, Double> prices;

    public WarehouseImpl(ActivationID id, MarshalledObject<Map<String, Double>> param) throws RemoteException, ClassNotFoundException, IOException {
        super(id, 0);
        prices = param.get();
        System.out.println("Warehouse implementation constructed.");
    }

    public double getPrice(String description) throws RemoteException {
        Double price = prices.get(description);

        return price == null ? 0 : price;
    }
}


text:
export interface TranformableData {
  [key: string]: string | number;
}

export const transformToNivoFormat = (
  data: TranformableData[],
  xKeyName: string,
  yKeyName: string,
): TranformableData[] => {
  data.forEach((item: TranformableData, index: number) => {
    item.x = item[xKeyName];
    item.y = item[yKeyName];
    delete item[xKeyName];
    delete item[yKeyName];
    data[index] = item;
  });
  return data;
};


text:
package org.jboss.pnc.rest.restmodel.causeway;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
 * Date: 8/25/16
 * Time: 2:48 PM
 *
 */
@Deprecated
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@AllArgsConstructor
public class BuildImportResultRest {
    /**
     * id of pnc build record
     */
    private Integer buildRecordId;

    /**
     * build id assigned by brew
     */
    private Integer brewBuildId;
    /**
     * link to brew
     */
    private String brewBuildUrl;

    private BuildImportStatus status;
    /**
     * global errors
     */
    private String errorMessage;

    /**
     * list of errors for artifact imports
     */
    private List<ArtifactImportError> errors;

}


text:
/**
 * Created by apple on 2017/10/3.
 */
import Show from './Show.vue';
export default Show;


text:
// .NAME OffsetsManager - Helper class due to PIMPL excess
// .SECTION Description
// This class is deisgned to work within vtkXMLWriter. It store a position
// in a file (unsigned long) and associate a offset in the file. This is
// useful when writing TimeStep XML file when you want to forward the
// same offset from the AppendData section on every entry in let say
// \<Points\> definition
// Example:
// \verbatim
// <Points>
//   <DataArray type="Float32" TimeStep="0" format="appended" offset="268" />
//   <DataArray type="Float32" TimeStep="1" format="appended" offset="268" />
//   ...
// </Points>
// \endverbatim
// Therefore data is only stored once in the XML file. At read time the
// offset value is stored to determine whenever we need to read data
// (ie when offset different from previously stored offset)

// .SECTION See Also
// vtkXMLWriter
// .SECTION Warning
// Do not include this file in a header file, it will break PIMPL convention

#ifndef vtkOffsetsManager_DoNotInclude
#error "do not include unless you know what you are doing"
#endif

#ifndef __vtkOffsetsManagerArray_h
#define __vtkOffsetsManagerArray_h

#include "vtkIOCoreExport.h" // For export macro
#include "vtkSystemIncludes.h"
#include <vtkstd/vector>
#include <assert.h>

//----------------------------------------------------------------------------
class OffsetsManager
{
public:
  // A type used for data sizes and offsets for stream i/o.  Using
  // vtkIdType should satisfy most users.  This could be streamoff if
  // it is deemed portable.  It could also be split into OffsetType
  // (streamoff) and PositionType (streampos).
  typedef vtkIdType OffsetType;

  // Construct with default (unsigned long)-1  MTime
  OffsetsManager()
    {
      this->LastMTime = static_cast<unsigned long>(-1); //almost invalid state
    }
  ~OffsetsManager()
    {
    }
  void Allocate(int numTimeStep)
    {
    assert( numTimeStep > 0);
    this->Positions.resize(numTimeStep);
    this->RangeMinPositions.resize(numTimeStep);
    this->RangeMaxPositions.resize(numTimeStep);
    this->OffsetValues.resize(numTimeStep);
    }
  OffsetType &GetPosition(unsigned int t)
    {
    assert( t < this->Positions.size());
    return this->Positions[t];
    }
  OffsetType &GetRangeMinPosition(unsigned int t)
    {
    assert( t < this->RangeMinPositions.size());
    return this->RangeMinPositions[t];
    }
  OffsetType &GetRangeMaxPosition(unsigned int t)
    {
    assert( t < this->RangeMaxPositions.size());
    return this->RangeMaxPositions[t];
    }
  OffsetType &GetOffsetValue(unsigned int t)
    {
    assert( t < this->OffsetValues.size());
    return this->OffsetValues[t];
    }
  unsigned long &GetLastMTime()
    {
    return this->LastMTime;
    }
private:
  unsigned long LastMTime; // Previously written dataarray mtime
  // at some point these vectors could become a vector of map <string,ul>
  // where the string is the name of the offset, but that would be pretty fat
  // and slow, but if another couple offsets are added then we should
  // consider doing it
  // Position in the stream to write the offset
  vtkstd::vector<OffsetType> Positions;
  vtkstd::vector<OffsetType> RangeMinPositions; // Where is this
  vtkstd::vector<OffsetType> RangeMaxPositions; // Whee is this

  vtkstd::vector<OffsetType> OffsetValues;    // Value of offset
};

//----------------------------------------------------------------------------
class OffsetsManagerGroup
{
public:
  // This is kind of a hack since we need to consider both the case of Points
  // with only one array over time and PointData with possibly multiple array
  // over time therefore we need to use a OffsetsManagerGroup for
  // representing offset from Points but OffsetsManagerArray for
  // PointData. In both case the toplevel structure is a container of
  // Pieces...
  OffsetsManager &GetPiece(unsigned int index)
    {
    assert( index < this->Internals.size());
    OffsetsManager &e = this->Internals[index];
    return e;
    }
  // GetElement should be used when manipulating a OffsetsManagerArray
  OffsetsManager &GetElement(unsigned int index)
    {
    // commenting the following out, this is an heisenbug which only appears
    // on gcc when exporting GLIBCPP_NEW=1. If you try to print the value or
    // run through gdb it desepears //assert( index <
    // this->Internals.size());
    OffsetsManager &e = this->Internals[index];
    return e;
    }
  unsigned int GetNumberOfElements()
    {
    return static_cast<unsigned int>(this->Internals.size());
    }
  void Allocate(int numElements)
    {
    assert(numElements >= 0); //allow 0 for empty FieldData
    this->Internals.resize(numElements);
    }
  void Allocate(int numElements, int numTimeSteps)
    {
    assert(numElements > 0);
    assert(numTimeSteps > 0);
    this->Internals.resize(numElements);
    for(int i=0; i<numElements; i++)
      {
      this->Internals[i].Allocate(numTimeSteps);
      }
    }
private:
  vtkstd::vector<OffsetsManager> Internals;
};

//----------------------------------------------------------------------------
class OffsetsManagerArray
{
public:
  OffsetsManagerGroup &GetPiece(unsigned int index)
    {
    assert( index < this->Internals.size());
    return this->Internals[index];
    }
  void Allocate(int numPieces)
    {
    assert(numPieces > 0);
    // Force re-initialization of values.
    this->Internals.resize(0);
    this->Internals.resize(numPieces);
    }
  void Allocate(int numPieces, int numElements, int numTimeSteps)
    {
    assert(numPieces > 0);
    assert(numElements > 0);
    assert(numTimeSteps > 0);

    // Force re-initialization of values.
    this->Internals.resize(0);
    this->Internals.resize(numPieces);
    for(int i=0; i<numPieces; i++)
      {
      this->Internals[i].Allocate(numElements, numTimeSteps);
      }
    }
private:
  vtkstd::vector<OffsetsManagerGroup> Internals;
};

#endif


text:
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.

var crypto = require('crypto');
var querystring = require('querystring');

var errors = require('../errors');

///--- Globals

var BadDigestError = errors.BadDigestError;
var InvalidContentError = errors.InvalidContentError;

///--- API

/**
 * Returns a plugin that will parse the HTTP request body IFF the
 * contentType is application/x-www-form-urlencoded.
 *
 * If req.params already contains a given key, that key is skipped and an
 * error is logged.
 *
 * @return {Function} restify handler.
 * @throws {TypeError} on bad input
 */
function urlEncodedBodyParser(options) {
  if (options && typeof (options) !== 'object')
    throw new TypeError('options (Object) required');
  if (!options)
    options = {};

  return function parseUrlEncodedBody(req, res, next) {
    if (req.contentType !== 'application/x-www-form-urlencoded' ||
        (req.contentLength === 0 && !req.chunked))
      return next();

    var hash;
    if (req.header('content-md5'))
      hash = crypto.createHash('md5');

    req.body = '';
    req.setEncoding('utf8');
    req.on('data', function (chunk) {
      req.body += chunk;
      if (hash)
        hash.update(chunk);
    });
    req.on('error', function (err) {
      return next(err);
    });
    req.on('end', function () {
      if (!req.body)
        return next();

      if (hash && req.header('content-md5') !== hash.digest('base64'))
        return next(new BadDigestError('Content-MD5 did not match'));

      try {
        var params = querystring.parse(req.body);
        if (options.mapParams !== false) {
          Object.keys(params).forEach(function (k) {
            if (req.params[k] && !options.overrideParams) {
              req.log.warn('%s is a URL parameter, but was in the body', k);
              return;
            }
            req.params[k] = params[k];
          });
        } else {
          req._body = req.body;
          req.body = params;
        }
      } catch (e) {
        return next(new InvalidContentError(e.message));
      }

      req.log.trace('req.params now: %j', req.params);
      return next();
    });

    return false;
  };
}

module.exports = urlEncodedBodyParser;


text:
package com.android.scenegraph;

import java.lang.Math;
import java.util.ArrayList;

import android.renderscript.Float3;
import android.renderscript.Float4;
import android.renderscript.Matrix4f;
import android.renderscript.RenderScriptGL;
import android.util.Log;

/**
 * @hide
 */
public abstract class LightBase extends SceneGraphBase {
    static final int RS_LIGHT_POINT = 0;
    static final int RS_LIGHT_DIRECTIONAL = 1;

    ScriptField_Light_s mField;
    ScriptField_Light_s.Item mFieldData;
    Transform mTransform;
    Float4 mColor;
    float mIntensity;
    public LightBase() {
        mColor = new Float4(0.0f, 0.0f, 0.0f, 0.0f);
        mIntensity = 1.0f;
    }

    public void setTransform(Transform t) {
        mTransform = t;
        updateRSData();
    }

    public void setColor(float r, float g, float b) {
        mColor.x = r;
        mColor.y = g;
        mColor.z = b;
        updateRSData();
    }

    public void setColor(Float3 c) {
        setColor(c.x, c.y, c.z);
    }

    public void setIntensity(float i) {
        mIntensity = i;
        updateRSData();
    }

    public void setName(String n) {
        super.setName(n);
        updateRSData();
    }

    protected void updateRSData() {
        if (mField == null) {
            return;
        }
        RenderScriptGL rs = SceneManager.getRS();
        mFieldData.transformMatrix = mTransform.getRSData().getAllocation();
        mFieldData.name = getNameAlloc(rs);
        mFieldData.color = mColor;
        mFieldData.intensity = mIntensity;

        initLocalData();

        mField.set(mFieldData, 0, true);
    }

    abstract void initLocalData();

    ScriptField_Light_s getRSData() {
        if (mField != null) {
            return mField;
        }

        RenderScriptGL rs = SceneManager.getRS();
        if (rs == null) {
            return null;
        }
        if (mField == null) {
            mField = new ScriptField_Light_s(rs, 1);
            mFieldData = new ScriptField_Light_s.Item();
        }

        updateRSData();

        return mField;
    }
}


text:
package com.datos.vfs.operations.vcs;

import java.util.Calendar;

/**
 *
 * @since 0.1
 */
public class VcsLogEntry
{
    /**
     */
    private final String author;

    /**
     * Revision.
     */
    private final long revision;

    /**
     * Message.
     */
    private final String message;

    /**
     * Date.
     */
    private final Calendar date;

    /**
     * Path.
     */
    private final String path;

    /**
     *
     * @param author The author.
     * @param revision The revision.
     * @param message The message.
     * @param date The date.
     * @param path The path.
     */
    public VcsLogEntry(final String author, final long revision,
            final String message, final Calendar date, final String path)
    {
        this.author = author;
        this.revision = revision;
        this.message = message;
        this.date = date;
        this.path = path;
    }

    /**
     *
     * @return The author.
     */
    public String getAuthor()
    {
        return author;
    }

    /**
     *
     * @return The revision.
     */
    public long getRevision()
    {
        return revision;
    }

    /**
     *
     * @return The message.
     */
    public String getMessage()
    {
        return message;
    }

    /**
     *
     * @return The date.
     */
    public Calendar getDate()
    {
        return date;
    }

    /**
     *
     * @return The path.
     */
    public String getPath()
    {
        return path;
    }
}


text:
namespace base{
struct PlatformFileInfo;
class TaskRunner;
}
namespace file_util {
struct FileInfo;
}

namespace net {

class FileStream;

// A request job that handles reading file URLs
class NET_EXPORT URLRequestFileJob : public URLRequestJob {
 public:
  URLRequestFileJob(URLRequest* request,
                    NetworkDelegate* network_delegate,
                    const base::FilePath& file_path,
                    const scoped_refptr<base::TaskRunner>& file_task_runner);

  // URLRequestJob:
  virtual void Start() OVERRIDE;
  virtual void Kill() OVERRIDE;
  virtual bool ReadRawData(IOBuffer* buf,
                           int buf_size,
                           int* bytes_read) OVERRIDE;
  virtual bool IsRedirectResponse(GURL* location,
                                  int* http_status_code) OVERRIDE;
  virtual Filter* SetupFilter() const OVERRIDE;
  virtual bool GetMimeType(std::string* mime_type) const OVERRIDE;
  virtual void SetExtraRequestHeaders(
      const HttpRequestHeaders& headers) OVERRIDE;

 protected:
  virtual ~URLRequestFileJob();

  // The OS-specific full path name of the file
  base::FilePath file_path_;

 private:
  // Meta information about the file. It's used as a member in the
  // URLRequestFileJob and also passed between threads because disk access is
  // necessary to obtain it.
  struct FileMetaInfo {
    FileMetaInfo();

    // Size of the file.
    int64 file_size;
    // Mime type associated with the file.
    std::string mime_type;
    // Result returned from GetMimeTypeFromFile(), i.e. flag showing whether
    // obtaining of the mime type was successful.
    bool mime_type_result;
    // Flag showing whether the file exists.
    bool file_exists;
    // Flag showing whether the file name actually refers to a directory.
    bool is_directory;
  };

  // Fetches file info on a background thread.
  static void FetchMetaInfo(const base::FilePath& file_path,
                            FileMetaInfo* meta_info);

  // Callback after fetching file info on a background thread.
  void DidFetchMetaInfo(const FileMetaInfo* meta_info);

  // Callback after opening file on a background thread.
  void DidOpen(int result);

  // Callback after seeking to the beginning of |byte_range_| in the file
  // on a background thread.
  void DidSeek(int64 result);

  // Callback after data is asynchronously read from the file.
  void DidRead(int result);

  scoped_ptr<FileStream> stream_;
  FileMetaInfo meta_info_;
  const scoped_refptr<base::TaskRunner> file_task_runner_;

  HttpByteRange byte_range_;
  int64 remaining_bytes_;

  base::WeakPtrFactory<URLRequestFileJob> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(URLRequestFileJob);
};

}  // namespace net

#endif  // NET_URL_REQUEST_URL_REQUEST_FILE_JOB_H_


text:
// Copyright (C) 2008  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_KCENTROId_ABSTRACT_
#ifdef DLIB_KCENTROId_ABSTRACT_

#include "../algs.h"
#include "../serialize.h"
#include "kernel_abstract.h"

namespace dlib
{

    template <
        typename kernel_type
        >
    class kcentroid
    {
        /*!
            REQUIREMENTS ON kernel_type
                is a kernel function object as defined in dlib/svm/kernel_abstract.h

            INITIAL VALUE
                - dictionary_size() == 0
                - samples_trained() == 0

            WHAT THIS OBJECT REPRESENTS
                This object represents a weighted sum of sample points in a kernel induced
                feature space.  It can be used to kernelize any algorithm that requires only
                the ability to perform vector addition, subtraction, scalar multiplication,
                and inner products.

                An example use of this object is as an online algorithm for recursively estimating
                the centroid of a sequence of training points.  This object then allows you to
                compute the distance between the centroid and any test points.  So you can use
                this object to predict how similar a test point is to the data this object has
                been trained on (larger distances from the centroid indicate dissimilarity/anomalous
                points).

                Also note that the algorithm internally keeps a set of "dictionary vectors"
                that are used to represent the centroid.  You can force the algorithm to use
                no more than a set number of vectors by setting the 3rd constructor argument
                to whatever you want.

                This object uses the sparsification technique described in the paper The
                Kernel Recursive Least Squares Algorithm by Yaakov Engel.  This technique
                allows us to keep the number of dictionary vectors down to a minimum.  In fact,
                the object has a user selectable tolerance parameter that controls the trade off
                between accuracy and number of stored dictionary vectors.
        !*/

    public:
        typedef typename kernel_type::scalar_type scalar_type;
        typedef typename kernel_type::sample_type sample_type;
        typedef typename kernel_type::mem_manager_type mem_manager_type;

        kcentroid (
        );
        /*!
            ensures
                - this object is properly initialized
                - #tolerance() == 0.001
                - #get_kernel() == kernel_type() (i.e. whatever the kernel's default value is)
                - #max_dictionary_size() == 1000000
                - #remove_oldest_first() == false
        !*/

        explicit kcentroid (
            const kernel_type& kernel_,
            scalar_type tolerance_ = 0.001,
            unsigned long max_dictionary_size_ = 1000000,
            bool remove_oldest_first_ = false
        );
        /*!
            requires
                - tolerance > 0
                - max_dictionary_size_ > 1
            ensures
                - this object is properly initialized
                - #tolerance() == tolerance_
                - #get_kernel() == kernel_
                - #max_dictionary_size() == max_dictionary_size_
                - #remove_oldest_first() == remove_oldest_first_
        !*/

        const kernel_type& get_kernel (
        ) const;
        /*!
            ensures
                - returns a const reference to the kernel used by this object
        !*/

        unsigned long max_dictionary_size(
        ) const;
        /*!
            ensures
                - returns the maximum number of dictionary vectors this object will
                  use at a time.  That is, dictionary_size() will never be greater
                  than max_dictionary_size().
        !*/

        bool remove_oldest_first (
        ) const;
        /*!
            ensures
                - When the maximum dictionary size is reached this object sometimes
                  needs to discard dictionary vectors when new samples are added via
                  one of the train functions.  When this happens this object chooses
                  the dictionary vector to discard based on the setting of the
                  remove_oldest_first() parameter.
                - if (remove_oldest_first() == true) then
                    - This object discards the oldest dictionary vectors when necessary.
                      This is an appropriate mode when using this object in an online
                      setting and the input training samples come from a slowly
                      varying distribution.
                - else (remove_oldest_first() == false) then
                    - This object discards the most linearly dependent dictionary vectors
                      when necessary.  This it the default behavior and should be used
                      in most cases.
        !*/

        unsigned long dictionary_size (
        ) const;
        /*!
            ensures
                - returns the number of basis vectors in the dictionary.  These are
                  the basis vectors used by this object to represent a point in kernel
                  feature space.
        !*/

        scalar_type samples_trained (
        ) const;
        /*!
            ensures
                - returns the number of samples this object has been trained on so far
        !*/

        scalar_type tolerance(
        ) const;
        /*!
            ensures
                - returns the tolerance to use for the approximately linearly dependent
                  test used for sparsification (see the KRLS paper for details).  This is
                  a number which governs how accurately this object will approximate the
                  centroid it is learning.  Smaller values generally result in a more
                  accurate estimate while also resulting in a bigger set of vectors in
                  the dictionary.  Bigger tolerances values result in a less accurate
                  estimate but also in less dictionary vectors.  (Note that in any case,
                  the max_dictionary_size() limits the number of dictionary vectors no
                  matter the setting of the tolerance)
                - The exact meaning of the tolerance parameter is the following:
                  Imagine that we have an empirical_kernel_map that contains all
                  the current dictionary vectors.  Then the tolerance is the minimum
                  projection error (as given by empirical_kernel_map::project()) required
                  to cause us to include a new vector in the dictionary.  So each time
                  you call train() the kcentroid basically just computes the projection
                  error for that new sample and if it is larger than the tolerance
                  then that new sample becomes part of the dictionary.
        !*/

        void clear_dictionary (
        );
        /*!
            ensures
                - clears out all learned data (e.g. #dictionary_size() == 0)
                - #samples_seen() == 0
        !*/

        scalar_type operator() (
            const kcentroid& x
        ) const;
        /*!
            requires
                - x.get_kernel() == get_kernel()
            ensures
                - returns the distance in kernel feature space between this centroid and the
                  centroid represented by x.
        !*/

        scalar_type operator() (
            const sample_type& x
        ) const;
        /*!
            ensures
                - returns the distance in kernel feature space between the sample x and the
                  current estimate of the centroid of the training samples given
                  to this object so far.
        !*/

        scalar_type inner_product (
            const sample_type& x
        ) const;
        /*!
            ensures
                - returns the inner product of the given x point and the current
                  estimate of the centroid of the training samples given to this object
                  so far.
        !*/

        scalar_type inner_product (
            const kcentroid& x
        ) const;
        /*!
            requires
                - x.get_kernel() == get_kernel()
            ensures
                - returns the inner product between x and this centroid object.
        !*/

        scalar_type squared_norm (
        ) const;
        /*!
            ensures
                - returns the squared norm of the centroid vector represented by this
                  object.  I.e. returns this->inner_product(*this)
        !*/

        void train (
            const sample_type& x
        );
        /*!
            ensures
                - adds the sample x into the current estimate of the centroid
                - also note that calling this function is equivalent to calling
                  train(x, samples_trained()/(samples_trained()+1.0, 1.0/(samples_trained()+1.0).
                  That is, this function finds the normal unweighted centroid of all training points.
        !*/

        void train (
            const sample_type& x,
            scalar_type cscale,
            scalar_type xscale
        );
        /*!
            ensures
                - adds the sample x into the current estimate of the centroid but
                  uses a user given scale.  That is, this function performs:
                    - new_centroid = cscale*old_centroid + xscale*x
                - This function allows you to weight different samples however
                  you want.
        !*/

        void scale_by (
            scalar_type cscale
        );
        /*!
            ensures
                - multiplies the current centroid vector by the given scale value.
                  This function is equivalent to calling train(some_x_value, cscale, 0).
                  So it performs:
                    - new_centroid == cscale*old_centroid
        !*/

        scalar_type test_and_train (
            const sample_type& x
        );
        /*!
            ensures
                - calls train(x)
                - returns (*this)(x)
                - The reason this function exists is because train() and operator()
                  both compute some of the same things.  So this function is more efficient
                  than calling both individually.
        !*/

        scalar_type test_and_train (
            const sample_type& x,
            scalar_type cscale,
            scalar_type xscale
        );
        /*!
            ensures
                - calls train(x,cscale,xscale)
                - returns (*this)(x)
                - The reason this function exists is because train() and operator()
                  both compute some of the same things.  So this function is more efficient
                  than calling both individually.
        !*/

        void swap (
            kcentroid& item
        );
        /*!
            ensures
                - swaps *this with item
        !*/

        distance_function<kernel_type> get_distance_function (
        ) const;
        /*!
            ensures
                - returns a distance function F that represents the point learned
                  by this object so far.  I.e. it is the case that:
                    - for all x: F(x) == (*this)(x)
        !*/

    };

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

    template <
        typename kernel_type
        >
    void swap(
        kcentroid<kernel_type>& a,
        kcentroid<kernel_type>& b
    ) { a.swap(b); }
    /*!
        provides a global swap function
    !*/

    template <
        typename kernel_type
        >
    void serialize (
        const kcentroid<kernel_type>& item,
        std::ostream& out
    );
    /*!
        provides serialization support for kcentroid objects
    !*/

    template <
        typename kernel_type
        >
    void deserialize (
        kcentroid<kernel_type>& item,
        std::istream& in
    );
    /*!
        provides serialization support for kcentroid objects
    !*/

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

}

#endif // DLIB_KCENTROId_ABSTRACT_


text:
id: 396
title: "Windows Live Domains"
date: 2013-06-20T16:56:06-03:00
author: Rodrigo Eiras
permalink: /2013/06/20/windows-live-domains/
categories:
  - Geral
tags:
  - domains
  - live.com
  - windows live
---

  Para quem esta procurando uma solução semelhante ao Google Apps que não é mais gratuito, uma saída é usar esse serviço da Microsoft que é gratuito até 50 contas. O “Windows Live Domains” é bem simples de configurar, basta ter um domínio, criar uma conta de administração e começar a trabalhar no Windows Live Admin Center. Para quem tiver interesse em conhecer:

#### http://domains.live.com


text:
/**
 * @author Sergey Burlak
 */
package javax.swing.plaf.metal;

import java.awt.Component;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.SwingTestCase;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;

public class MetalTreeUITest extends SwingTestCase {
    private MetalTreeUI ui;

    private JTree tree;

    private DefaultMutableTreeNode root;

    private DefaultMutableTreeNode node1;

    private DefaultMutableTreeNode node2;

    private DefaultMutableTreeNode node3;

    private DefaultMutableTreeNode node11;

    private DefaultMutableTreeNode node21;

    private DefaultMutableTreeNode node22;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        try {
            UIManager.setLookAndFeel(new MetalLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        root = new DefaultMutableTreeNode("root");
        node1 = new DefaultMutableTreeNode("node1");
        node2 = new DefaultMutableTreeNode("node2");
        node3 = new DefaultMutableTreeNode("node3");
        node11 = new DefaultMutableTreeNode("node11");
        node21 = new DefaultMutableTreeNode("node21");
        node22 = new DefaultMutableTreeNode("node22");
        root.add(node1);
        node1.add(node11);
        node11.add(new DefaultMutableTreeNode("node111"));
        root.add(node1);
        node2.add(node21);
        node2.add(node22);
        root.add(node2);
        root.add(node3);
        tree = new JTree(root);
        ui = new MetalTreeUI();
        tree.setUI(ui);
    }

    @Override
    protected void tearDown() throws Exception {
        ui = null;
        tree = null;
        root = null;
        node1 = null;
        node2 = null;
        node3 = null;
        node11 = null;
        node21 = null;
        node22 = null;
        super.tearDown();
    }

    public void testPaint() {
        Graphics g = createTestGraphics();
        g.setClip(0, 0, 10, 10);
        ui.paint(g, tree);
    }

    public void testUninstallUI() {
        ui.uninstallUI(tree);
        assertNotNull(ui.getExpandedIcon());
        assertNotNull(ui.getCollapsedIcon());
    }

    public void testInstallUI() {
        ui.uninstallUI(tree);
        ui.installUI(tree);
        assertNotNull(ui.getExpandedIcon());
        assertNotNull(ui.getCollapsedIcon());
    }

    public void testCreateUI() {
        assertNotSame(MetalTreeUI.createUI(tree), MetalTreeUI.createUI(tree));
    }

    public void testGetHorizontalLegBuffer() {
        assertEquals(4, ui.getHorizontalLegBuffer());
    }

    public void testIsLocationInExpandControl() throws Exception {
        tree.setShowsRootHandles(false);
        tree.expandPath(tree.getPathForRow(1));
        assertFalse(ui.isLocationInExpandControl(0, 0, -26, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, -25, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, -1, 25));
        assertFalse(ui.isLocationInExpandControl(0, 0, 0, 25));
        assertFalse(ui.isLocationInExpandControl(1, 0, -26, 25));
        assertTrue(ui.isLocationInExpandControl(1, 0, -25, 25));
        assertTrue(ui.isLocationInExpandControl(1, 0, -1, 25));
        assertFalse(ui.isLocationInExpandControl(1, 0, 0, 25));
        assertFalse(ui.isLocationInExpandControl(2, 0, -26, 25));
        assertTrue(ui.isLocationInExpandControl(2, 0, -25, 25));
        assertTrue(ui.isLocationInExpandControl(2, 0, -1, 25));
        assertFalse(ui.isLocationInExpandControl(2, 0, 0, 25));
        assertFalse(ui.isLocationInExpandControl(3, 0, -26, 25));
        assertTrue(ui.isLocationInExpandControl(3, 0, -25, 25));
        assertTrue(ui.isLocationInExpandControl(3, 0, -1, 25));
        assertFalse(ui.isLocationInExpandControl(3, 0, 0, 25));
        assertFalse(ui.isLocationInExpandControl(0, 1, -6, 25));
        assertTrue(ui.isLocationInExpandControl(0, 1, -5, 25));
        assertTrue(ui.isLocationInExpandControl(0, 1, 19, 25));
        assertFalse(ui.isLocationInExpandControl(0, 1, 20, 25));
        assertFalse(ui.isLocationInExpandControl(1, 1, -6, 20));
        assertTrue(ui.isLocationInExpandControl(1, 1, -5, 20));
        assertTrue(ui.isLocationInExpandControl(1, 1, 19, 20));
        assertFalse(ui.isLocationInExpandControl(1, 1, 20, 20));
        assertFalse(ui.isLocationInExpandControl(2, 1, -6, 20));
        assertTrue(ui.isLocationInExpandControl(2, 1, -5, 20));
        assertTrue(ui.isLocationInExpandControl(2, 1, 19, 20));
        assertFalse(ui.isLocationInExpandControl(2, 1, 20, 20));
        assertFalse(ui.isLocationInExpandControl(0, 2, 14, -20));
        assertTrue(ui.isLocationInExpandControl(0, 2, 15, -20));
        assertTrue(ui.isLocationInExpandControl(0, 2, 39, -20));
        assertFalse(ui.isLocationInExpandControl(0, 2, 40, -20));
        assertFalse(ui.isLocationInExpandControl(1, 2, 14, -20));
        assertTrue(ui.isLocationInExpandControl(1, 2, 15, -20));
        assertTrue(ui.isLocationInExpandControl(1, 2, 39, -20));
        assertFalse(ui.isLocationInExpandControl(1, 2, 40, -20));
        assertFalse(ui.isLocationInExpandControl(2, 2, 14, -20));
        assertTrue(ui.isLocationInExpandControl(2, 2, 15, -20));
        assertTrue(ui.isLocationInExpandControl(2, 2, 39, -20));
        assertFalse(ui.isLocationInExpandControl(2, 2, 40, -20));
        tree.setShowsRootHandles(true);
        assertFalse(ui.isLocationInExpandControl(0, 0, -6, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, -5, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, 19, 25));
        assertFalse(ui.isLocationInExpandControl(0, 0, 20, 25));
        tree.setShowsRootHandles(false);
        ui.setExpandedIcon(new Icon() {
            public void paintIcon(Component c, Graphics g, int x, int y) {
            }

            public int getIconWidth() {
                return 0;
            }

            public int getIconHeight() {
                return 100;
            }
        });
        assertFalse(ui.isLocationInExpandControl(0, 0, -17, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, -16, 25));
        assertTrue(ui.isLocationInExpandControl(0, 0, -10, 25));
        assertFalse(ui.isLocationInExpandControl(0, 0, -9, 25));
    }
}


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

<document>

 <properties>
  <title>Apache James Server 3 - Mailet Container Configuration</title>
 </properties>

Consult mailetcontainer-template.xml in SVN to get some examples and hints.

Changes between 3.0-M2 and 3.0-beta3:

No more mailetpackage specification in mailetcontainer.xml

Exactly one standard package, hard-coded in source code

Standard package applied to mailet classnames without package prefix

All custom mailets must be specified with full package prefix

Package prefixed custom mailet names will be searched across the entire applicable class path

Composite matchers

This configuration block is defined by the mailserver tag.  All administrators
      need to adjust the mailserver block upon installation.

context.postmaster

The body of this element is the address that the server
            will consider its postmaster address.  This address will be listed as the sender address
            of all error messages that originate from James.  Also, all messages addressed to
            postmaster@<servername>, where <servername> is one of the domain names whose
            mail is being handled by James, will be redirected to this email address.
            Set this to the appropriate email address for error reports
            If this is set to a non-local email address, the mail server
            will still function, but will generate a warning on startup.

spooler.threads

Number of simultaneous threads used to spool the mails.

    <subsection name="The Mailet Tag">

Consider the following simple mailet tag:

      <mailet match="RemoteAddrNotInNetwork=127.0.0.1" class="ToProcessor">

      <processor>spam</processor>

      </mailet>

The mailet tag has two required attributes, match and class.

The match attribute is set to the value of the specific Matcher class to be instantiated with a an
      optional argument.  If present, the argument is separated from the Matcher class name by an '='.  Semantic
      interpretation of the argument is left to the particular mailet.

The class attribute is set to the value of the Mailet class that is to be instantiated.

Finally, the children of the mailet tag define the configuration that is passed to the Mailet.  The
      tags used in this section should have no attributes or children.  The names and bodies of the elements will be passed to
      the mailet as (name, value) pairs.

So in the example above, a Matcher instance of RemoteAddrNotInNetwork would be instantiated, and the value "127.0.0.1"
      would be passed to the matcher.  The Mailet of the pair will be an instance of ToProcessor, and it will be passed the (name, value)
      pair of ("processor", "spam").

Apache James Server includes a number of pre-packaged Mailets and Matchers.  A list of provided Mailets may be found
      here.  A list of provided Matchers may be found here.

    </subsection>

</document>


text:
#include "OgreGL3PlusRenderSystem.h"
#include "OgreRoot.h"

#include "OgreTextureManager.h"

#include "OgreGL3PlusHardwareBufferManager.h"
#include "OgreGL3PlusHardwarePixelBuffer.h"
#include "OgreGL3PlusTextureBuffer.h"
#include "OgreGL3PlusPixelFormat.h"
#include "OgreGL3PlusFBORenderTexture.h"
#include "OgreGL3PlusStateCacheManager.h"

#include "OgreGLSLMonolithicProgram.h"
#include "OgreGLSLProgramManager.h"
#include "OgreGLSLSeparableProgram.h"

#include "OgreGL3PlusTexture.h"

namespace Ogre {

    GL3PlusTextureBuffer::GL3PlusTextureBuffer(GL3PlusTexture* parent,
                                               GLint face, GLint level, uint32 width, uint32 height,
                                               uint32 depth)
        : GLHardwarePixelBufferCommon(width, height, depth, parent->getFormat(), (Usage)parent->getUsage()),
          mTarget(parent->getGL3PlusTextureTarget()), mTextureID(parent->getGLID()), mLevel(level)
    {
        mRenderSystem = static_cast<GL3PlusRenderSystem*>(Root::getSingleton().getRenderSystem());
        // Get face identifier
        mFaceTarget = mTarget;
        if (mTarget == GL_TEXTURE_CUBE_MAP)
            mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;

        // Get format
        mGLInternalFormat = GL3PlusPixelUtil::getGLInternalFormat(mFormat, parent->isHardwareGammaEnabled());

        // Log a message
        //        std::stringstream str;
        //        str << "GL3PlusHardwarePixelBuffer constructed for texture: " << mTextureID
        //            << " bytes: " << mSizeInBytes
        //            << " face: " << mFace << " level: " << mLevel
        //            << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth
        //            << " format: " << PixelUtil::getFormatName(mFormat)
        //            << "(internal 0x" << std::hex << value << ")";
        //        LogManager::getSingleton().logMessage(LML_NORMAL, str.str());

        // Set up a pixel box
        mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat);

        if (mWidth==0 || mHeight==0 || mDepth==0)
            // We are invalid, do not allocate a buffer
            return;

        // Is this a render target?
        if (mUsage & TU_RENDERTARGET)
        {
            // Create render target for each slice
            mSliceTRT.reserve(mDepth);
            for(uint32 zoffset=0; zoffset<mDepth; ++zoffset)
            {
                String name;
                name = "rtt/" + StringConverter::toString((size_t)this) + "/" + parent->getName();
                GLSurfaceDesc surface;
                surface.buffer = this;
                surface.zoffset = zoffset;
                RenderTexture* trt = GL3PlusRTTManager::getSingleton().createRenderTexture(
                    name, surface, parent->isHardwareGammaEnabled(), parent->getFSAA());
                mSliceTRT.push_back(trt);
                Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[zoffset]);
            }
        }
    }

    GL3PlusTextureBuffer::~GL3PlusTextureBuffer()
    {
    }

    void GL3PlusTextureBuffer::upload(const PixelBox &data, const Box &dest)
    {
        mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID );

        // PBOs have no advantage with this usage pattern
        // see: https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object
#ifdef USE_PBO
        // Calculate size for all mip levels of the texture.
        size_t dataSize = data.getConsecutiveSize();
        GL3PlusHardwareBuffer buffer(GL_PIXEL_UNPACK_BUFFER, dataSize, mUsage);
        buffer.writeData(0, dataSize, data.data, false);

        PixelBox tmp(data.getWidth(), data.getHeight(), data.getHeight(), data.format);
        tmp.data = buffer.lockImpl(0, dataSize, HardwareBuffer::HBL_DISCARD);
        PixelUtil::bulkPixelConversion(data, tmp);
        buffer.unlockImpl(dataSize);

        // std::stringstream str;
        // str << "GL3PlusHardwarePixelBuffer::upload: " << mTextureID
        // << " pixel buffer: " << buffer.getGLBufferId()
        // << " bytes: " << mSizeInBytes
        // << " dest depth: " << dest.getDepth()
        // << " dest front: " << dest.front
        // << " datasize: " << dataSize
        // << " face: " << mFace << " level: " << mLevel
        // << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth
        // << " format: " << PixelUtil::getFormatName(mFormat);
        // LogManager::getSingleton().logMessage(LML_NORMAL, str.str());

        void* pdata = NULL;
#else
        void* pdata = data.getTopLeftFrontPixelPtr();
#endif

        if (PixelUtil::isCompressed(data.format))
        {
            if (data.format != mFormat || !data.isConsecutive())
                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                            "Compressed images must be consecutive and in the designated source format",
                            "GL3PlusTextureBuffer::upload");

            GLenum format = GL3PlusPixelUtil::getGLInternalFormat(mFormat);
            // Data must be consecutive and at beginning of buffer as
            // PixelStorei not allowed for compressed formats.
            switch(mTarget)
            {
            case GL_TEXTURE_1D:
                // Some systems (e.g. old Apple) don't like compressed
                // subimage calls so prefer non-sub versions.
                OGRE_CHECK_GL_ERROR(glCompressedTexSubImage1D(
                    GL_TEXTURE_1D, mLevel,
                    dest.left,
                    dest.getWidth(),
                    format, data.getConsecutiveSize(),
                    pdata));
                break;
            case GL_TEXTURE_2D:
            case GL_TEXTURE_CUBE_MAP:
            case GL_TEXTURE_RECTANGLE:
                OGRE_CHECK_GL_ERROR(glCompressedTexSubImage2D(
                    mFaceTarget, mLevel,
                    dest.left, dest.top,
                    dest.getWidth(), dest.getHeight(),
                    format, data.getConsecutiveSize(),
                    pdata));
                break;
            case GL_TEXTURE_3D:
            case GL_TEXTURE_2D_ARRAY:
                OGRE_CHECK_GL_ERROR(glCompressedTexSubImage3D(
                    mTarget, mLevel,
                    dest.left, dest.top, dest.front,
                    dest.getWidth(), dest.getHeight(), dest.getDepth(),
                    format, data.getConsecutiveSize(),
                    pdata));
                break;
            }

        }
        else
        {
#ifndef USE_PBO
            if (data.getWidth() != data.rowPitch)
                OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch));
            if (data.getHeight() * data.getWidth() != data.slicePitch)
                OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth())));
#endif
            if ((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
                // Standard alignment of 4 is not right.
                OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
            }

            GLenum type = GL3PlusPixelUtil::getGLOriginDataType(data.format);

            if (PixelUtil::isDepth(data.format))
            {
                switch (GL3PlusPixelUtil::getGLInternalFormat(data.format))
                {
                    case GL_DEPTH_COMPONENT16:
                        type = GL_UNSIGNED_SHORT;
                        break;

                    default:
                    case GL_DEPTH_COMPONENT24:
                    case GL_DEPTH_COMPONENT32:
                        type = GL_UNSIGNED_INT;
                        break;

                    case GL_DEPTH_COMPONENT32F:
                        type = GL_FLOAT;
                        break;
                }
            }

            switch(mTarget)
            {
            case GL_TEXTURE_1D:
                OGRE_CHECK_GL_ERROR(glTexSubImage1D(
                    GL_TEXTURE_1D, mLevel,
                    dest.left,
                    dest.getWidth(),
                    GL3PlusPixelUtil::getGLOriginFormat(data.format),
                    type,
                    pdata));
                break;
            case GL_TEXTURE_2D:
            case GL_TEXTURE_CUBE_MAP:
            case GL_TEXTURE_RECTANGLE:
                OGRE_CHECK_GL_ERROR(glTexSubImage2D(
                    mFaceTarget, mLevel,
                    dest.left, dest.top,
                    dest.getWidth(), dest.getHeight(),
                    GL3PlusPixelUtil::getGLOriginFormat(data.format),
                    type,
                    pdata));
                break;
            case GL_TEXTURE_3D:
            case GL_TEXTURE_2D_ARRAY:
                OGRE_CHECK_GL_ERROR(glTexSubImage3D(
                    mTarget, mLevel,
                    dest.left, dest.top, dest.front,
                    dest.getWidth(), dest.getHeight(), dest.getDepth(),
                    GL3PlusPixelUtil::getGLOriginFormat(data.format),
                    type,
                    pdata));
                break;
            }
        }

        // TU_AUTOMIPMAP is only enabled when there are no custom mips
        // so we do not have to care about overwriting
        if ((mUsage & TU_AUTOMIPMAP) && (mLevel == 0))
        {
            OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget));
        }

        // Restore defaults.
        OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
        OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0));
        OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 4));
    }

    void GL3PlusTextureBuffer::download(const PixelBox &data)
    {
        if (data.getSize() != getSize())
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "only download of entire buffer is supported by GL",
                        "GL3PlusTextureBuffer::download");

        // Download data to PBO
        GL3PlusHardwareBuffer buffer(GL_PIXEL_PACK_BUFFER, data.getConsecutiveSize(), HBU_GPU_TO_CPU);

        //        std::stringstream str;
        //        str << "GL3PlusHardwarePixelBuffer::download: " << mTextureID
        //        << " pixel buffer: " << mBufferId
        //        << " bytes: " << mSizeInBytes
        //        << " face: " << mFace << " level: " << mLevel
        //        << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth
        //        << " format: " << PixelUtil::getFormatName(mFormat);
        //        LogManager::getSingleton().logMessage(LML_NORMAL, str.str());

        mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID);

        if (PixelUtil::isCompressed(data.format))
        {
            if (data.format != mFormat || !data.isConsecutive())
                OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                            "Compressed images must be consecutive, in the source format",
                            "GL3PlusTextureBuffer::download");
            // Data must be consecutive and at beginning of buffer as PixelStorei not allowed
            // for compressed formate
            OGRE_CHECK_GL_ERROR(glGetCompressedTexImage(mFaceTarget, mLevel, 0));
        }
        else
        {
            if ((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
                // Standard alignment of 4 is not right
                OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 1));
            }
            // We can only get the entire texture
            OGRE_CHECK_GL_ERROR(glGetTexImage(mFaceTarget, mLevel,
                                              GL3PlusPixelUtil::getGLOriginFormat(data.format),
                                              GL3PlusPixelUtil::getGLOriginDataType(data.format),
                                              0));

            // Restore defaults
            OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 4));
        }

        // Copy to destination buffer
        if(data.isConsecutive())
            buffer.readData(0, data.getConsecutiveSize(), data.getTopLeftFrontPixelPtr());
        else
        {
            size_t srcOffset = 0, elemSizeInBytes = PixelUtil::getNumElemBytes(data.format);
            for(size_t z = 0; z < mDepth; ++z)
                for(size_t y = 0; y < mHeight; ++y)
                {
                    buffer.readData(srcOffset, mWidth * elemSizeInBytes,
                        (uint8*)data.getTopLeftFrontPixelPtr() + (z * data.slicePitch + y * data.rowPitch) * elemSizeInBytes);
                    srcOffset += mWidth * elemSizeInBytes;
                }
        }
    }

    void GL3PlusTextureBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset)
    {
        // Delegate the framebuffer binding to a more specific function
        // This call retains the original implementation using GL_FRAMEBUFFER (aka GL_DRAW_FRAMEBUFFER)
        _bindToFramebuffer(attachment, zoffset, GL_DRAW_FRAMEBUFFER);
    }

    void GL3PlusTextureBuffer::copyFromFramebuffer(uint32 zoffset)
    {
        mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID);
        switch(mTarget)
        {
        case GL_TEXTURE_1D:
            OGRE_CHECK_GL_ERROR(glCopyTexSubImage1D(mFaceTarget, mLevel, 0, 0, 0, mWidth));
            break;
        case GL_TEXTURE_2D:
        case GL_TEXTURE_CUBE_MAP:
        case GL_TEXTURE_RECTANGLE:
            OGRE_CHECK_GL_ERROR(glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight));
            break;
        case GL_TEXTURE_3D:
        case GL_TEXTURE_2D_ARRAY:
            OGRE_CHECK_GL_ERROR(glCopyTexSubImage3D(mFaceTarget, mLevel, 0, 0, zoffset, 0, 0, mWidth, mHeight));
            break;
        }
    }

    void GL3PlusTextureBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox)
    {
        GL3PlusTextureBuffer *srct = static_cast<GL3PlusTextureBuffer *>(src.get());
        // Check for FBO support first
        if (GLRTTManager::getSingleton().checkFormat(mFormat))
        {
            blitFromTexture(srct, srcBox, dstBox);
        }
        else
        {
            GLHardwarePixelBufferCommon::blit(src, srcBox, dstBox);
        }
    }

    void GL3PlusTextureBuffer::blitFromTexture(GL3PlusTextureBuffer *src, const Box &srcBox, const Box &dstBox)
    {
        //        std::cerr << "GL3PlusTextureBuffer::blitFromTexture " <<
        //        src->mTextureID << ":" << srcBox.left << "," << srcBox.top << "," << srcBox.right << "," << srcBox.bottom << " " <<
        //        mTextureID << ":" << dstBox.left << "," << dstBox.top << "," << dstBox.right << "," << dstBox.bottom << std::endl;
        GLenum filtering = GL_LINEAR;

        // Set filtering modes depending on the dimensions and source
        if (srcBox.getSize()==dstBox.getSize())
        {
            // Dimensions match -- use nearest filtering (fastest and pixel correct)
            filtering = GL_NEAREST;
        }

        // Store old binding so it can be restored later
        GLint oldfb;
        OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb));

        // Set up temporary FBOs
        GLuint tempFBO[2] = { 0, 0 };
        OGRE_CHECK_GL_ERROR(glGenFramebuffers(2, tempFBO));
        mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, tempFBO[0] );
        mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_READ_FRAMEBUFFER, tempFBO[1] );

        bool isDepth = PixelUtil::isDepth(mFormat);

        // Process each destination slice
        for(uint32 slice = dstBox.front; slice < dstBox.back; ++slice)
        {
            // Bind directly
            bindToFramebuffer(isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, slice);

            OGRE_CHECK_GL_ERROR(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER));

            GLbitfield mask = 0;

            // Bind the appropriate source texture to the read framebuffer
            src->_bindToFramebuffer(isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, slice,
                                    GL_READ_FRAMEBUFFER);
            if (isDepth)
            {
                // Depth framebuffer sources can only be blit with nearest filtering
                filtering = GL_NEAREST;
                mask |= GL_DEPTH_BUFFER_BIT;
            }
            else
            {
                OGRE_CHECK_GL_ERROR(glReadBuffer(GL_COLOR_ATTACHMENT0));
                mask |= GL_COLOR_BUFFER_BIT;
            }

            OGRE_CHECK_GL_ERROR(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER));

            // Perform blit from the source texture bound to read framebuffer to
            // this texture bound to draw framebuffer using the pixel coorinates.
            // Sampling ouside the source box is implicitly handled using GL_CLAMP_TO_EDGE.
            OGRE_CHECK_GL_ERROR(glBlitFramebuffer(srcBox.left, srcBox.top, srcBox.right, srcBox.bottom,
                                                  dstBox.left, dstBox.top, dstBox.right, dstBox.bottom,
                                                  mask, filtering));
        }

        // Generate mipmaps
        if (mUsage & TU_AUTOMIPMAP)
        {
            mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID );
            OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget));
        }

        OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(
            GL_DRAW_FRAMEBUFFER, isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0));

        // Reset read buffer/framebuffer
        OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE));
        mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_READ_FRAMEBUFFER, 0 );

        // Restore old framebuffer
        mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, oldfb);

        mRenderSystem->_getStateCacheManager()->deleteGLFrameBuffer(GL_FRAMEBUFFER, tempFBO[0]);
        mRenderSystem->_getStateCacheManager()->deleteGLFrameBuffer(GL_FRAMEBUFFER, tempFBO[1]);
    }

    void GL3PlusTextureBuffer::_bindToFramebuffer(GLenum attachment, uint32 zoffset, GLenum which)
    {
        assert(zoffset < mDepth);
        assert(which == GL_READ_FRAMEBUFFER || which == GL_DRAW_FRAMEBUFFER || which == GL_FRAMEBUFFER);

        mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID );
        switch(mTarget)
        {
        case GL_TEXTURE_1D:
        case GL_TEXTURE_2D:
        case GL_TEXTURE_RECTANGLE:
            OGRE_CHECK_GL_ERROR(glFramebufferTexture(which, attachment,
                                                     mTextureID, mLevel));
            break;
        case GL_TEXTURE_CUBE_MAP:
            OGRE_CHECK_GL_ERROR(glFramebufferTexture2D(which, GL_COLOR_ATTACHMENT0,
                                                       mFaceTarget, mTextureID, mLevel));
            break;
        case GL_TEXTURE_3D:
        case GL_TEXTURE_2D_ARRAY:
            OGRE_CHECK_GL_ERROR(glFramebufferTexture3D(which, attachment,
                                                       mFaceTarget, mTextureID, mLevel, zoffset));
            break;
        }
    }

    // blitFromMemory doing hardware bilinear scaling
    void GL3PlusTextureBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox)
    {
        if (!mBuffer.contains(dstBox))
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Destination box out of range");

        // Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case
        // the source dimensions match the destination ones, in which case no scaling is needed
        if (src.getSize() == dstBox.getSize())
        {
            _blitFromMemory(src, dstBox);
            return;
        }

        TextureType type = (src.getDepth() != 1) ? TEX_TYPE_3D : TEX_TYPE_2D;

        // no mipmaps. blitFromTexture does not use them
        TexturePtr tex = TextureManager::getSingleton().createManual(
            "GLBlitFromMemoryTMP", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, type,
            src.getWidth(), src.getHeight(), src.getDepth(), 0, src.format);

        // Upload data to 0,0,0 in temporary texture
        Box tempTarget(src.getSize());
        tex->getBuffer()->blitFromMemory(src, tempTarget);

        // Blit from texture
        blit(tex->getBuffer(), tempTarget, dstBox);

        // Delete temp texture
        TextureManager::getSingleton().remove(tex);
    }
    void GL3PlusTextureBuffer::_blitFromMemory(const PixelBox &src, const Box& dst)
    {
        PixelBox converted;

        if (GL3PlusPixelUtil::getGLInternalFormat(src.format) == 0)
        {
            // Extents match, but format is not accepted as valid
            // source format for GL. Do conversion in temporary buffer.
            allocateBuffer();
            converted = mBuffer.getSubVolume(src);
            PixelUtil::bulkPixelConversion(src, converted);
        }
        else
        {
            // No conversion needed.
            converted = src;
        }

        upload(converted, dst);
        freeBuffer();
    }

    void GL3PlusTextureBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst)
    {
        if (!mBuffer.contains(srcBox))
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "source box out of range",
                        "GL3PlusHardwarePixelBuffer::blitToMemory");
        }

        if (srcBox.getOrigin() == Vector3i(0, 0 ,0) &&
            srcBox.getSize() == getSize() &&
            dst.getSize() == getSize() &&
            GL3PlusPixelUtil::getGLInternalFormat(dst.format) != 0)
        {
            // The direct case: the user wants the entire texture in a format supported by GL
            // so we don't need an intermediate buffer
            download(dst);
        }
        else
        {
            // Use buffer for intermediate copy
            allocateBuffer();
            // Download entire buffer
            download(mBuffer);
            if(srcBox.getSize() != dst.getSize())
            {
                // We need scaling
                Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR);
            }
            else
            {
                // Just copy the bit that we need
                PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst);
            }
            freeBuffer();
        }
    }
}


text:
import logging

def setup_logging(config):
    fmt_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    logging.basicConfig(format=fmt_string)
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    formatter = logging.Formatter(fmt_string)
    if config.log_file_err:
        try:
            from logging import handlers
            handler_cls = handlers.WatchedFileHandler
        except:
            handler_cls = logging.FileHandler
        handler = handler_cls(config.log_file_err)
        handler.setFormatter(formatter)
        handler.setLevel(logging.WARN)
        root_logger.addHandler(handler)

    if config.log_file_access:
        try:
            from logging import handlers
            handler_cls = handlers.WatchedFileHandler
        except:
            handler_cls = logging.FileHandler
        handler = handler_cls(config.log_file_access)
        handler.setFormatter(formatter)
        handler.setLevel(logging.INFO)
        logging.getLogger('access').addHandler(handler)


text:
module RayCaster.Transformations where

import           RayCaster.Camera
import           RayCaster.DataTypes
import           RayCaster.Quaternion
import           RayCaster.Shapes
import           RayCaster.Vector

-- Transformations
rotateCamera :: Vector -> Vector -> Double -> Camera -> Camera
rotateCamera point axis angle (Camera fov center lookingAt) =
  let newCenter = point `add` rotate axis angle (center `sub` point)
  in Camera fov newCenter lookingAt

rotateObj :: Vector -> Vector -> Double -> Object -> Object
rotateObj point axis angle (Object shape material) =
  let rotatedShape =
        translateShape
          point
          (rotateShape axis angle (translateShape (neg point) shape))
  in Object rotatedShape material

rotateShape :: Vector -> Double -> Shape -> Shape
rotateShape axis angle (Sphere center radius) =
  Sphere (rotate axis angle center) radius
rotateShape axis angle (Plane center normal) =
  Plane (rotate axis angle center) normal

translateObj :: Vector -> Object -> Object
translateObj translationVector (Object shape material) =
  Object (translateShape translationVector shape) material

translateShape :: Vector -> Shape -> Shape
translateShape translationVector (Sphere center radius) =
  Sphere (center `add` translationVector) radius
translateShape translationVector (Plane center normal) =
  Plane (center `add` translationVector) normal

translateCamera :: Vector -> Camera -> Camera
translateCamera translationVector (Camera fov center lookAt) =
  Camera fov (center `add` translationVector) lookAt

scaleObj :: Object -> Double -> Object
scaleObj (Object shape material) factor =
  Object (scaleShape factor shape) material

scaleShape :: Double -> Shape -> Shape
scaleShape factor (Sphere center radius) = Sphere center (factor * radius)
scaleShape factor shape                  = shape


text:
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
using System.Text;
using System.ComponentModel;
using Velyo.Web.Security.Resources;

namespace Velyo.Web.Security.Store
{
    /// <summary>
    /// Generic class for a perssitable object.
    /// Encapsulates the logic to load/save data from/to the filesystem.
    /// To speed up the acces, caching is used.
    /// </summary>
    /// <typeparam name="T">class or struct with all the data-fields that must be persisted</typeparam>
    /// <summary>
    /// Generic class for a perssitable object.
    /// Encapsulates the logic to load/save data from/to the filesystem.
    /// To speed up the acces, caching is used.
    /// </summary>
    /// <typeparam name="T">class or struct with all the data-fields that must be persisted</typeparam>
    public class XmlStore<T> : IDisposable where T : class, new()
    {
        private static readonly object FileChangedEvent = new object();
        private static readonly object ValueChangedEvent = new object();

        private T _value;

        [NonSerialized]
        private readonly string _file;

        [NonSerialized]
        private readonly XmlSerializer _serializer;

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlStore<T>"/> class.
        /// </summary>
        /// <param name="file">Name of the file.</param>
        public XmlStore(string file) : this()
        {
            _file = file;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlStore<T>"/> class.
        /// </summary>
        protected internal XmlStore()
        {
            _serializer = new XmlSerializer(typeof(T));
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="XmlStore<T>"/> is reclaimed by garbage collection.
        /// </summary>
        ~XmlStore()
        {
            Dispose(false);
        }

        /// <summary>
        /// Occurs when [file changed].
        /// </summary>
        public event EventHandler FileChanged
        {
            add
            {
                Events.AddHandler(FileChangedEvent, value);
            }
            remove
            {
                Events.RemoveHandler(FileChangedEvent, value);
            }
        }

        /// <summary>
        /// Occurs when [value changed].
        /// </summary>
        public event EventHandler ValueChanged
        {
            add
            {
                Events.AddHandler(ValueChangedEvent, value);
            }
            remove
            {
                Events.RemoveHandler(ValueChangedEvent, value);
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [auto create].
        /// </summary>
        /// <value><c>true</c> if [auto create]; otherwise, <c>false</c>.</value>
        public bool AutoCreate { get; set; } = true;

        /// <summary>
        /// Gets or sets a value indicating whether [auto load].
        /// </summary>
        /// <value><c>true</c> if [auto load]; otherwise, <c>false</c>.</value>
        public bool AutoLoad { get; set; } = true;

        /// <summary>
        /// Gets or sets a value indicating whether [direct write].
        /// </summary>
        /// <value><c>true</c> if [direct write]; otherwise, <c>false</c>.</value>
        public bool DirectWrite { get; set; }

        /// <summary>
        /// Gets the events.
        /// </summary>
        /// <value>The events.</value>
        protected EventHandlerList Events { get; } = new EventHandlerList();

        /// <summary>
        /// Gets a value indicating whether this instance is empty.
        /// </summary>
        /// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value>
        public bool IsEmpty
        {
            get
            {
                lock (SyncRoot)
                {
                    return (_value == null || (_value is ICollection && ((ICollection)_value).Count == 0));
                }

            }
        }

        /// <summary>
        /// Gets or sets the sync root.
        /// </summary>
        /// <value>The sync root.</value>
        public virtual object SyncRoot { get; } = new object();

        /// <summary>
        /// Gets or sets the data.
        /// </summary>
        /// <value>The data.</value>
        public virtual T Value
        {
            get
            {
                if (IsEmpty)
                {
                    lock (SyncRoot)
                    {
                        if (IsEmpty)
                        {
                            if (AutoLoad) Load();
                            if (_value == null && AutoCreate) _value = new T();
                        }

                    }
                }
                return _value;
            }
            set
            {
                if (_value != value)
                {
                    lock (SyncRoot)
                    {
                        if (_value != value)
                        {
                            _value = value;
                            OnValueChanged(EventArgs.Empty);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (Events != null)
                {
                    Events.Dispose();
                }
                _value = null;
            }
        }

        /// <summary>
        /// Deletes the data from the cache and file system
        /// </summary>
        /// <returns></returns>
        public virtual bool Delete()
        {
            if (File.Exists(_file))
            {
                using (var scope = new FileLockScope(_file))
                {
                    // loop just in case of any file locks while deleting
                    for (int i = 1; i < 4; i++)
                    {
                        try
                        {
                            File.Delete(_file);
                            return true;
                        }
                        catch
                        {
                            Thread.Sleep(50 * i);
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Loads the data from the file system. For deserialization an XmlSeralizer is used.
        /// </summary>
        public virtual void Load()
        {
            try
            {
                using (var scope = new FileLockScope(_file))
                {
                    if (File.Exists(_file))
                    {
                        using (FileStream reader = File.Open(_file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            _value = (T)_serializer.Deserialize(reader);
                        }
                    }
                    AddFileNotifier();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(Messages.LoadFailed, _file), ex);
            }
        }

        /// <summary>
        /// Persists the data back to the file system
        /// </summary>
        public virtual void Save()
        {
            try
            {
                if (!IsEmpty)
                {
                    lock (SyncRoot)
                    {
                        if (!IsEmpty)
                        {
                            string file = DirectWrite ? _file : Path.GetTempFileName();

                            using (new FileLockScope(file))
                            {
                                FileMode mode = File.Exists(file) ? FileMode.Truncate : FileMode.OpenOrCreate;
                                using (FileStream stream = File.Open(file, mode, FileAccess.Write, FileShare.ReadWrite))
                                {
                                    _serializer.Serialize(stream, _value);
                                }

                                if (!DirectWrite)
                                {
                                    File.Copy(file, _file, true);
                                    File.Delete(file);
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(Messages.SaveFailed, _file), ex);
            }
        }

        /// <summary>
        /// Raises the <see cref="E:FileChanged"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void OnFileChanged(EventArgs e)
        {
            (Events?[FileChangedEvent] as EventHandler)?.Invoke(this, e);
        }

        /// <summary>
        /// Raises the <see cref="E:ValueChanged"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void OnValueChanged(EventArgs e)
        {
            (Events?[ValueChangedEvent] as EventHandler)?.Invoke(this, e);
        }

        #region File change notifier

        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        private void AddFileNotifier()
        {
            HttpRuntime.Cache.Insert(
                _file,
                new object(),
                new CacheDependency(_file),
                Cache.NoAbsoluteExpiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.High,
                new CacheItemRemovedCallback(NotifyFileChanged));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="reason"></param>
        private void NotifyFileChanged(string key, object value, CacheItemRemovedReason reason)
        {
            Value = default(T);
            OnFileChanged(EventArgs.Empty);
        }
        #endregion

        class FileLockScope : IDisposable
        {
            private Mutex _lock;

            /// <summary>
            /// Initializes a new instance of the <see cref="XmlStore<T>.FileLockScope"/> class.
            /// </summary>
            /// <param name="fileName">Name of the file.</param>
            public FileLockScope(string fileName)
            {
                string hash = CalculateMD5Hash(fileName);
                _lock = new Mutex(false, hash);
                _lock.WaitOne();
            }

            /// <summary>
            /// Releases unmanaged resources and performs other cleanup operations before the
            /// <see cref="XmlStore<T>.FileLockScope"/> is reclaimed by garbage collection.
            /// </summary>
            ~FileLockScope()
            {
                Dispose(false);
            }

            /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }

            /// <summary>
            /// Releases unmanaged and - optionally - managed resources
            /// </summary>
            /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
            protected virtual void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (_lock != null)
                    {
                        _lock.ReleaseMutex();
                        _lock = null;
                    }
                }
            }

            /// <summary>
            /// Creates a MD5 hash from a string. Used for creating a unique name for the mutex's for each file that is accessed by the store objects. (putting the
            /// actual file name as a mutex name was resulting in a DirectoryNotFound error, which I believe was because of some special rules the
            /// Mutex name must follow, but aren't well documented.
            /// </summary>
            /// <param name="strInput">Unhashed string</param>
            /// <returns>Hashed string</returns>
            private static string CalculateMD5Hash(string strInput)
            {
                var md5 = System.Security.Cryptography.MD5.Create();
                byte[] inputBytes = Encoding.ASCII.GetBytes(strInput);
                byte[] hash = md5.ComputeHash(inputBytes);

                var sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
    }
}


text:
"""Package to deal with handling meta-data about Project Gutenberg works."""

from gutenberg.query.api import get_metadata  # noqa
from gutenberg.query.api import get_etexts  # noqa
from gutenberg.query.api import list_supported_metadatas  # noqa

from gutenberg.query.extractors import AuthorExtractor  # noqa
from gutenberg.query.extractors import TitleExtractor  # noqa


text:
'use strict';

var deepMap = require('../../utils/collection/deepMap');

function factory (type, config, load, typed) {
  var matrix = load(require('../../type/matrix/function/matrix'));
  var complexMultiply = typed.find(load(require('./multiplyScalar')), ['Complex,Complex']);
  var complexExp      = typed.find(load(require('./exp')), ['Complex']);

  /**
   * Calculate the cubic root of a value.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.cbrt(x)
   *
   * Examples:
   *
   *    math.cbrt(27);                  // returns 3
   *    math.cube(3);                   // returns 27
   *    math.cbrt(-64);                 // returns -4
   *    math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
   *    math.cbrt([27, 64, 125]);       // returns [3, 4, 5]
   *
   *    var x = math.complex('8i');
   *    math.cbrt(x);                   // returns Complex 1.7320508075689 + i
   *    math.cbrt(x, true);             // returns Matrix [
   *                                    //    1.7320508075689 + i
   *                                    //   -1.7320508075689 + i
   *                                    //   -2i
   *                                    // ]
   *
   * See also:
   *
   *    square, sqrt, cube
   *
   * @param {number | BigNumber | Complex | Unit | Array | Matrix} x
   *            Value for which to calculate the cubic root.
   * @param {boolean} [allRoots]  Optional, false by default. Only applicable
   *            when `x` is a number or complex number. If true, all complex
   *            roots are returned, if false (default) the principal root is
   *            returned.
   * @return {number | BigNumber | Complex | Unit | Array | Matrix}
   *            Returns the cubic root of `x`
   */
  var cbrt = typed('cbrt', {
    'number': _cbrtNumber,
    // note: signature 'number, boolean' is also supported,
    //       created by typed as it knows how to convert number to Complex

    'Complex': _cbrtComplex,

    'Complex, boolean': _cbrtComplex,

    'BigNumber': _cbrtBigNumber,

    'Unit': _cbrtUnit,

    'Array | Matrix': function (x) {
      // deep map collection, skip zeros since cbrt(0) = 0
      return deepMap(x, cbrt, true);
    }
  });

  /**
   * Calculate cbrt for a number
   *
   * Code from es6-shim.js:
   *   https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
   *
   * @param {number} x
   * @returns {number | Complex} Returns the cubic root of x
   * @private
   */
  function _cbrtNumber(x) {
    if (x === 0) {
      return x;
    }

    var negate = x < 0;
    var result;
    if (negate) {
      x = -x;
    }

    if (isFinite(x)) {
      result = Math.exp(Math.log(x) / 3);
      // from http://en.wikipedia.org/wiki/Cube_root#Numerical_methods
      result = (x / (result * result) + (2 * result)) / 3;
    } else {
      result = x;
    }

    return negate ? -result : result;
  }

  /**
   * Calculate the cubic root for a complex number
   * @param {Complex} x
   * @param {boolean} [allRoots]   If true, the function will return an array
   *                               with all three roots. If false or undefined,
   *                               the principal root is returned.
   * @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
   * @private
   */
  function _cbrtComplex(x, allRoots) {
    // https://www.wikiwand.com/en/Cube_root#/Complex_numbers
    var polar = x.toPolar();

    // principal root:
    var principal = complexMultiply(
        new type.Complex(_cbrtNumber(polar.r), 0),
        complexExp(new type.Complex(0, polar.phi / 3))
    );

    if (allRoots) {
      var all = [
          principal,
          complexMultiply(
            new type.Complex(_cbrtNumber(polar.r), 0),
            complexExp(new type.Complex(0, polar.phi / 3 + Math.PI * 2 / 3))
          ),
          complexMultiply(
            new type.Complex(_cbrtNumber(polar.r), 0),
            complexExp(new type.Complex(0, polar.phi / 3 - Math.PI * 2 / 3))
          )
      ];

      return (config.matrix === 'array') ? all : matrix(all);
    }
    else {
      return principal;
    }
  }

  /**
   * Calculate the cubic root for a BigNumber
   * @param {BigNumber} x
   * @returns {BigNumber} Returns the cubic root of x
   * @private
   */
  function _cbrtBigNumber(x) {
    if (x.isZero()) {
      return x;
    }

    var negate = x.isNegative();
    var result;
    if (negate) {
      x = x.neg();
    }

    if (!x.isFinite()) {
      result = Infinity;
    } else {
      // from http://en.wikipedia.org/wiki/Cube_root#Numerical_methods
      result = x.ln().div(3).exp();
      result = x.div(result.times(result)).plus(result.times(2)).div(3);
    }

    return negate ? result.neg() : result;
  }

  /**
   * Calculate the cubic root for a Unit
   * @param {Unit} x
   * @return {Unit} Returns the cubic root of x
   * @private
   */
  function _cbrtUnit(x) {
    var negate = x.value < 0;
    if (negate) {
      x.value = -x.value;
    }

    var result = x.pow(1/3);

    if (negate) {
      result.value = -result.value;
    }

    return result;
  }

  cbrt.toTex = '\\sqrt[3]{${args[0]}}';

  return cbrt;
}

exports.name = 'cbrt';
exports.factory = factory;