text:
<!DOCTYPE html>
<!--
Copyright 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/math/range.html">
<link rel="import" href="/tracing/base/unit.html">
<link rel="import" href="/tracing/value/diagnostics/diagnostic_map.html">
<link rel="import" href="/tracing/value/diagnostics/generic_set.html">
<link rel="import" href="/tracing/value/histogram.html">
<link rel="import" href="/tracing/value/histogram_set.html">

<script>
'use strict';
tr.b.unittest.testSuite(function() {
  // TODO(#3812) Test groupHistogramsRecursively.

  test('assertType', function() {
    const hs = new tr.v.HistogramSet();
    assert.throws(() => hs.importLegacyDict({type: ''}),
        Error, 'Unrecognized shared diagnostic type ');
  });

  test('ignoreTagMap', function() {
    const hs = new tr.v.HistogramSet();
    hs.importLegacyDict({type: 'TagMap'});
  });

  test('importDicts', function() {
    const n = new tr.v.Histogram('foo', tr.b.Unit.byName.unitlessNumber);
    const histograms = new tr.v.HistogramSet([n]);
    const histograms2 = new tr.v.HistogramSet();
    histograms2.importDicts(histograms.asDicts());
    assert.isDefined(histograms2.getHistogramNamed('foo'));
  });

  test('importDictsWithSampleDiagnostic', function() {
    const n = new tr.v.Histogram('foo', tr.b.Unit.byName.count);
    n.addSample(10, {bar: new tr.v.d.GenericSet(['baz'])});

    const histograms = new tr.v.HistogramSet([n]);
    const histograms2 = new tr.v.HistogramSet();
    histograms2.importDicts(histograms.asDicts());
    assert.isDefined(histograms2.getHistogramNamed('foo'));
    const v = histograms2.getHistogramNamed('foo');
    assert.lengthOf(v.getBinForValue(10).diagnosticMaps, 1);
    const dm = v.getBinForValue(10).diagnosticMaps[0];
    assert.strictEqual(dm.size, 1);
    assert.instanceOf(dm.get('bar'), tr.v.d.GenericSet);
    assert.strictEqual(tr.b.getOnlyElement(dm.get('bar')), 'baz');
  });

  test('sourceHistogramsWithSampleDiagnostic', function() {
    const unit = tr.b.Unit.byName.unitlessNumber;
    const aHist = new tr.v.Histogram('a', unit);
    aHist.addSample(1);

    const bHist = new tr.v.Histogram('b', tr.b.Unit.byName.unitlessNumber);
    const related = new tr.v.d.RelatedNameMap();
    related.set('0', aHist.name);
    bHist.diagnostics.set('related', related);
    bHist.addSample(1);

    const histograms = new tr.v.HistogramSet([aHist, bHist]);
    assert.strictEqual(tr.b.getOnlyElement(histograms.sourceHistograms), bHist);
  });

  test('sourceHistogramsWithNameMap', function() {
    const unit = tr.b.Unit.byName.unitlessNumber;
    const histograms = new tr.v.HistogramSet();
    histograms.createHistogram('A', unit, []);
    const bHist = histograms.createHistogram('B', unit, [], {diagnostics: {
      related: tr.v.d.RelatedNameMap.fromEntries([['a', 'A']]),
    }});
    assert.strictEqual(tr.b.getOnlyElement(histograms.sourceHistograms), bHist);
  });

  test('sharedDiagnostic', function() {
    // Make a single Histogram, add a shared Diagnostic.
    const aHist = new tr.v.Histogram('aHist', tr.b.Unit.byName.count);
    const histograms = new tr.v.HistogramSet([aHist]);
    const diagnostic = new tr.v.d.GenericSet(['shared']);
    histograms.addSharedDiagnosticToAllHistograms('generic', diagnostic);

    // Serializing a single Histogram with a single shared diagnostic should
    // produce 2 dicts.
    const dicts = histograms.asDicts();
    assert.lengthOf(dicts, 2);
    assert.deepEqual(diagnostic.asDict(), dicts[0]);

    // The serialized Histogram should refer to the shared diagnostic by its
    // guid.
    assert.strictEqual(dicts[1].diagnostics.generic, diagnostic.guid);

    // Deserialize the dicts.
    const histograms2 = new tr.v.HistogramSet();
    histograms2.importDicts(dicts);
    assert.lengthOf(histograms2, 1);
    const aHist2 = histograms2.getHistogramNamed(aHist.name);

    assert.instanceOf(aHist2.diagnostics.get('generic'), tr.v.d.GenericSet);
    assert.strictEqual(tr.b.getOnlyElement(diagnostic),
        tr.b.getOnlyElement(aHist2.diagnostics.get('generic')));
  });

  test('getHistogramNamed_noHistogramFound', function() {
    const aHist = new tr.v.Histogram('aHist', tr.b.Unit.byName.count);
    const histograms = new tr.v.HistogramSet([aHist]);

    assert.isUndefined(histograms.getHistogramNamed('bHist'));
  });

  test('getHistogramNamed_oneHistogramFound', function() {
    const aHist = new tr.v.Histogram('aHist', tr.b.Unit.byName.count);
    const histograms = new tr.v.HistogramSet([aHist]);

    assert.strictEqual(histograms.getHistogramNamed('aHist'), aHist);
  });

  test('getHistogramNamed_multipleHistogramsFound', function() {
    const aHist1 = new tr.v.Histogram('aHist', tr.b.Unit.byName.count);
    const aHist2 = new tr.v.Histogram('aHist', tr.b.Unit.byName.count);
    const histograms = new tr.v.HistogramSet([aHist1, aHist2]);

    assert.throws(() => histograms.getHistogramNamed('aHist'),
        Error, 'Unexpectedly found multiple histograms named "aHist"');
  });

  test('deduplicateDiagnostics', function() {
    const genericA = new tr.v.d.GenericSet(['A']);
    const genericB = new tr.v.d.GenericSet(['B']);
    const dateA = new tr.v.d.DateRange(42);
    const dateB = new tr.v.d.DateRange(57);

    const aHist = new tr.v.Histogram('a', tr.b.Unit.byName.count);
    const generic0 = genericA.clone();
    generic0.addDiagnostic(genericB);
    aHist.diagnostics.set('generic', generic0);
    const date0 = dateA.clone();
    date0.addDiagnostic(dateB);
    aHist.diagnostics.set('date', date0);

    const bHist = new tr.v.Histogram('b', tr.b.Unit.byName.count);
    const generic1 = genericA.clone();
    generic1.addDiagnostic(genericB);
    bHist.diagnostics.set('generic', generic1);
    const date1 = dateA.clone();
    date1.addDiagnostic(dateB);
    bHist.diagnostics.set('date', date1);

    const cHist = new tr.v.Histogram('c', tr.b.Unit.byName.count);
    cHist.diagnostics.set('generic', generic1);

    const histograms = new tr.v.HistogramSet([aHist, bHist, cHist]);
    assert.notStrictEqual(
        aHist.diagnostics.get('generic'), bHist.diagnostics.get('generic'));
    assert.strictEqual(
        bHist.diagnostics.get('generic'), cHist.diagnostics.get('generic'));
    assert.isTrue(
        aHist.diagnostics.get('generic').equals(
            bHist.diagnostics.get('generic')));
    assert.notStrictEqual(
        aHist.diagnostics.get('date'), bHist.diagnostics.get('date'));
    assert.isTrue(
        aHist.diagnostics.get('date').equals(bHist.diagnostics.get('date')));

    histograms.deduplicateDiagnostics();

    assert.strictEqual(
        aHist.diagnostics.get('generic'), bHist.diagnostics.get('generic'));
    assert.strictEqual(
        bHist.diagnostics.get('generic'), cHist.diagnostics.get('generic'));
    assert.strictEqual(
        aHist.diagnostics.get('date'), bHist.diagnostics.get('date'));

    const histogramDicts = histograms.asDicts();

    // All diagnostics should have been serialized as DiagnosticRefs.
    for (const dict of histogramDicts) {
      if (!('type' in dict)) {
        for (const diagnosticDict of Object.values(dict.diagnostics)) {
          assert.strictEqual(typeof(diagnosticDict), 'string');
        }
      }
    }

    const histograms2 = new tr.v.HistogramSet();
    histograms2.importDicts(histogramDicts);
    const aHist2 = histograms2.getHistogramNamed('a');
    const bHist2 = histograms2.getHistogramNamed('b');

    assert.strictEqual(
        aHist2.diagnostics.get('generic'), bHist2.diagnostics.get('generic'));
    assert.strictEqual(
        aHist2.diagnostics.get('date'), bHist2.diagnostics.get('date'));
  });

  test('buildGroupingsFromTags', function() {
    const histograms = new tr.v.HistogramSet();
    const aHist = histograms.createHistogram('', tr.b.Unit.byName.count, [], {
      diagnostics: new Map([
        [tr.v.d.RESERVED_NAMES.STORY_TAGS, new tr.v.d.GenericSet(['a'])],
      ]),
    });
    const bHist = histograms.createHistogram('', tr.b.Unit.byName.count, [], {
      diagnostics: new Map([
        [tr.v.d.RESERVED_NAMES.STORY_TAGS, new tr.v.d.GenericSet(['b'])],
      ]),
    });
    const groupings = histograms.buildGroupingsFromTags([
      tr.v.d.RESERVED_NAMES.STORY_TAGS]);
    assert.lengthOf(groupings, 2);
    assert.strictEqual(groupings[0].callback(aHist), 'a');
    assert.strictEqual(groupings[0].callback(bHist), '~a');
    assert.strictEqual(groupings[1].callback(aHist), '~b');
    assert.strictEqual(groupings[1].callback(bHist), 'b');
  });
});
</script>


text:
JavaScript Library to read dataset content (e.g., Open Data), infer data types, give a data quality indicator and parse content.

In details, it analysis the json (specified paths) to infer the data type. In addition, when request (via code) the library converts the json data based on the inferred type.

Recognised basic types:
 - Text;
 - Number;
 - Date;
 - Object;
 - Null.

Recognised types:
 - Geographic coordinates;
 - JSON;
 - GEOJSON.

It also provides a module to be used in nodejs.

## Documentation

See wiki pages [here](https://github.com/donpir/JSDataChecker/wiki).

## License

The library has released with the LGPL license [link here](http://www.gnu.org/licenses/lgpl.html).

Briefly with this license:

 - Freedom to modify and distribute modified copies of DataChecker, distributing the source code and releasing it with the same LGPL license;
 - You can dynamically (not statically) link DataChecker library in a proprietary software, keeping the JS files as they are.

## Publications

Please, refer to this paper for details on the library and its use case:

- _D. Pirozzi, V. Scarano_, **_Support citizens in Visualizing Open Data_**, 20th International Conference on Information Visualisation, Lisbon (Portugal), 19-22 July 2016 ([Citation](http://ieeexplore.ieee.org/abstract/document/7557938/))

redpajama_set_name: RedPajamaGithub


text:
var Hilo = require('../core/Hilo');
var Class = require('../core/Class');
var Container = require('./Container');
var CanvasRenderer = require('../renderer/CanvasRenderer');
var DOMRenderer = require('../renderer/DOMRenderer');
var WebGLRenderer = require('../renderer/WebGLRenderer');

/**
 * Hilo
 * Copyright 2015 alibaba.com
 * Licensed under the MIT License
 */

/**
 * 示例:
 *

 * var stage = new Hilo.Stage({
 *     renderType:'canvas',
 *     container: containerElement,
 *     width: 320,
 *     height: 480
 * });
 *

 * @class 舞台是可视对象树的根,可视对象只有添加到舞台或其子对象后才会被渲染出来。创建一个hilo应用一般都是从创建一个stage开始的。
 * @augments Container
 * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。主要有:
 *

 *
container:String|HTMLElement - 指定舞台在页面中的父容器元素。它是一个dom容器或id。若不传入此参数且canvas未被加入到dom树,则需要在舞台创建后手动把舞台画布加入到dom树中,否则舞台不会被渲染。可选。

 *
renderType:String - 指定渲染方式,canvas|dom|webgl,默认canvas。可选。

 *
canvas:String|HTMLCanvasElement|HTMLElement - 指定舞台所对应的画布元素。它是一个canvas或普通的div,也可以传入元素的id。若为canvas,则使用canvas来渲染所有对象,否则使用dom+css来渲染。可选。

 *
width:Number
 - 指定舞台的宽度。默认为canvas的宽度。可选。
 *
height:Number
 - 指定舞台的高度。默认为canvas的高度。可选。
 *
paused:Boolean
 - 指定舞台是否停止渲染。默认为false。可选。
 *

 * @module hilo/view/Stage
 * @requires hilo/core/Hilo
 * @requires hilo/core/Class
 * @requires hilo/view/Container
 * @requires hilo/renderer/CanvasRenderer
 * @requires hilo/renderer/DOMRenderer
 * @requires hilo/renderer/WebGLRenderer
 * @property {HTMLCanvasElement|HTMLElement} canvas 舞台所对应的画布。它可以是一个canvas或一个普通的div。只读属性。
 * @property {Renderer} renderer 舞台渲染器。只读属性。
 * @property {Boolean} paused 指示舞台是否暂停刷新渲染。
 * @property {Object} viewport 舞台内容在页面中的渲染区域。包含的属性有:left、top、width、height。只读属性。
 */
var Stage = Class.create(/** @lends Stage.prototype */{
    Extends: Container,
    constructor: function(properties){
        properties = properties || {};
        this.id = this.id || properties.id || Hilo.getUid('Stage');
        Stage.superclass.constructor.call(this, properties);

        this._initRenderer(properties);

        //init size
        var width = this.width, height = this.height,
            viewport = this.updateViewport();
        if(!properties.width) width = (viewport && viewport.width) || 320;
        if(!properties.height) height = (viewport && viewport.height) || 480;
        this.resize(width, height, true);
    },

    canvas: null,
    renderer: null,
    paused: false,
    viewport: null,

    /**
     * @private
     */
    _initRenderer: function(properties){
        var canvas = properties.canvas;
        var container = properties.container;
        var renderType = properties.renderType||'canvas';

        if(typeof canvas === 'string') canvas = Hilo.getElement(canvas);
        if(typeof container === 'string') container = Hilo.getElement(container);

        if(!canvas){
            var canvasTagName = renderType === 'dom'?'div':'canvas';
            canvas = Hilo.createElement(canvasTagName, {
                style: {
                    position: 'absolute'
                }
            });
        }
        else if(!canvas.getContext){
            renderType = 'dom';
        }

        this.canvas = canvas;
        if(container) container.appendChild(canvas);

        var props = {canvas:canvas, stage:this};
        switch(renderType){
            case 'dom':
                this.renderer = new DOMRenderer(props);
                break;
            case 'webgl':
                if(WebGLRenderer.isSupport()){
                    this.renderer = new WebGLRenderer(props);
                }
                else{
                    this.renderer = new CanvasRenderer(props);
                }
                break;
            case 'canvas':
            default:
                this.renderer = new CanvasRenderer(props);
                break;
        }
    },

    /**
     * 添加舞台画布到DOM容器中。注意:此方法覆盖了View.addTo方法。
     * @param {HTMLElement} domElement 一个dom元素。
     * @returns {Stage} 舞台本身,可用于链式调用。
     */
    addTo: function(domElement){
        var canvas = this.canvas;
        if(canvas.parentNode !== domElement){
            domElement.appendChild(canvas);
        }
        return this;
    },

    /**
     * 调用tick会触发舞台的更新和渲染。开发者一般无需使用此方法。
     * @param {Number} delta 调度器当前调度与上次调度tick之间的时间差。
     */
    tick: function(delta){
        if(!this.paused){
            this._render(this.renderer, delta);
        }
    },

    /**
     * 开启/关闭舞台的DOM事件响应。要让舞台上的可视对象响应用户交互,必须先使用此方法开启舞台的相应事件的响应。
     * @param {String|Array} type 要开启/关闭的事件名称或数组。
     * @param {Boolean} enabled 指定开启还是关闭。如果不传此参数,则默认为开启。
     * @returns {Stage} 舞台本身。链式调用支持。
     */
    enableDOMEvent: function(type, enabled){
        var me = this,
            canvas = me.canvas,
            types = typeof type === 'string' ? [type] : type,
            enabled = enabled !== false,
            handler = me._domListener || (me._domListener = function(e){me._onDOMEvent(e)});

        for(var i = 0; i < types.length; i++){
            var type = types[i];

            if(enabled){
                canvas.addEventListener(type, handler, false);
            }else{
                canvas.removeEventListener(type, handler);
            }
        }

        return me;
    },

    /**
     * DOM事件处理函数。此方法会把事件调度到事件的坐标点所对应的可视对象。
     * @private
     */
    _onDOMEvent: function(e){
        var type = e.type, event = e, isTouch = type.indexOf('touch') == 0;

        //calculate stageX/stageY
        var posObj = e;
        if(isTouch){
            var touches = e.touches, changedTouches = e.changedTouches;
            posObj = (touches && touches.length) ? touches[0] :
                     (changedTouches && changedTouches.length) ? changedTouches[0] : null;
        }

        var x = posObj.pageX || posObj.clientX, y = posObj.pageY || posObj.clientY,
            viewport = this.viewport || this.updateViewport();

        event.stageX = x = (x - viewport.left) / this.scaleX;
        event.stageY = y = (y - viewport.top) / this.scaleY;

        //鼠标事件需要阻止冒泡方法
        event.stopPropagation = function(){
            this._stopPropagationed = true;
        };

        var obj = this.getViewAtPoint(x, y, true, false, true)||this,
            canvas = this.canvas, target = this._eventTarget;

        //fire mouseout/touchout event for last event target
        var leave = type === 'mouseout';
        //当obj和target不同 且obj不是target的子元素时才触发out事件
        if(target && (target != obj && (!target.contains || !target.contains(obj))|| leave)){
            var out = (type === 'touchmove') ? 'touchout' :
                      (type === 'mousemove' || leave || !obj) ? 'mouseout' : null;
            if(out) {
                var outEvent = Hilo.copy({}, event);
                outEvent.type = out;
                outEvent.eventTarget = target;
                target._fireMouseEvent(outEvent);
            }
            event.lastEventTarget = target;
            this._eventTarget = null;
        }

        //fire event for current view
        if(obj && obj.pointerEnabled && type !== 'mouseout'){
            event.eventTarget = this._eventTarget = obj;
            obj._fireMouseEvent(event);
        }

        //set cursor for current view
        if(!isTouch){
            var cursor = (obj && obj.pointerEnabled && obj.useHandCursor) ? 'pointer' : '';
            canvas.style.cursor = cursor;
        }

        //fix android: `touchmove` fires only once
        if(Hilo.browser.android && type === 'touchmove'){
            e.preventDefault();
        }
    },

    /**
     * 更新舞台在页面中的可视区域,即渲染区域。当舞台canvas的样式border、margin、padding等属性更改后,需要调用此方法更新舞台渲染区域。
     * @returns {Object} 舞台的可视区域。即viewport属性。
     */
    updateViewport: function(){
        var canvas = this.canvas, viewport = null;
        if(canvas.parentNode){
            viewport = this.viewport = Hilo.getElementRect(canvas);
        }
        return viewport;
    },

    /**
     * 改变舞台的大小。
     * @param {Number} width 指定舞台新的宽度。
     * @param {Number} height 指定舞台新的高度。
     * @param {Boolean} forceResize 指定是否强制改变舞台大小,即不管舞台大小是否相同,仍然强制执行改变动作,可确保舞台、画布以及视窗之间的尺寸同步。
     */
    resize: function(width, height, forceResize){
        if(forceResize || this.width !== width || this.height !== height){
            this.width = width;
            this.height = height;
            this.renderer.resize(width, height);
            this.updateViewport();
        }
    }

});

module.exports = Stage;


text:
namespace chromeos {

BrightnessBubble::BrightnessBubble()
    : SettingLevelBubble(
          ResourceBundle::GetSharedInstance().GetBitmapNamed(
              IDR_BRIGHTNESS_BUBBLE_ICON),
          ResourceBundle::GetSharedInstance().GetBitmapNamed(
              IDR_BRIGHTNESS_BUBBLE_ICON),
          ResourceBundle::GetSharedInstance().GetBitmapNamed(
              IDR_BRIGHTNESS_BUBBLE_ICON)) {
}

// static
BrightnessBubble* BrightnessBubble::GetInstance() {
  return Singleton<BrightnessBubble>::get();
}

}  // namespace chromeos


text:
package org.openkilda.floodlight.service.kafka;

import static org.openkilda.floodlight.service.zookeeper.ZooKeeperService.ZK_COMPONENT_NAME;

import org.openkilda.bluegreen.LifecycleEvent;
import org.openkilda.bluegreen.Signal;
import org.openkilda.floodlight.service.zookeeper.ZooKeeperEventObserver;
import org.openkilda.floodlight.service.zookeeper.ZooKeeperService;
import org.openkilda.messaging.AbstractMessage;
import org.openkilda.messaging.Message;
import org.openkilda.messaging.info.ChunkedInfoMessage;
import org.openkilda.messaging.info.InfoData;
import org.openkilda.messaging.info.InfoMessage;
import org.openkilda.messaging.info.event.IslInfoData;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;

public class KafkaProducerService implements IKafkaProducerService, ZooKeeperEventObserver {

    private static final Logger logger = LoggerFactory.getLogger(KafkaProducerService.class);
    private static final Logger discoLogger = LoggerFactory.getLogger(
            String.format("%s.DISCO", KafkaProducerService.class.getName()));

    private int failedSendMessageCounter;
    private Producer<String, String> producer;
    private final ObjectMapper jsonObjectMapper = new ObjectMapper();

    private ZooKeeperService zkService;
    private final AtomicBoolean active = new AtomicBoolean(false);

    @Override
    public void setup(FloodlightModuleContext moduleContext) {
        producer = moduleContext.getServiceImpl(KafkaUtilityService.class).makeProducer();
        zkService = moduleContext.getServiceImpl(ZooKeeperService.class);
        zkService.subscribe(this);
    }

    @Override
    public void sendMessageAndTrack(String topic, Message message) {
        produce(encode(topic, message), new SendStatusCallback(this, topic, message));
    }

    @Override
    public void sendMessageAndTrack(String topic, String key, Message message) {
        produce(encode(topic, key, message), new SendStatusCallback(this, topic, message));
    }

    @Override
    public void sendMessageAndTrack(String topic, String key, AbstractMessage message) {
        produce(encode(topic, key, message), new SendStatusCallback(this, topic,
                message.getMessageContext().getCorrelationId()));
    }

    @Override
    public void sendChunkedMessageAndTrack(String topic, String key, Collection<? extends InfoData> data) {
        for (Message message : ChunkedInfoMessage.createChunkedList(data, key)) {
            sendMessageAndTrack(topic, key, message);
        }
    }

    @Override
    public void sendMessageAndTrackWithZk(String topic, Message message) {
        if (active.get()) {
            produce(encode(topic, message), new SendStatusCallback(this, topic, message));
        } else {
            logger.debug("ZooKeeper signal is not START");
        }
    }

    @Override
    public void sendMessageAndTrackWithZk(String topic, String key, Message message) {
        if (active.get()) {
            produce(encode(topic, key, message), new SendStatusCallback(this, topic, message));
        } else {
            logger.debug("ZooKeeper signal is not START");
        }
    }

    @Override
    public void handleLifecycleEvent(LifecycleEvent event) {
        logger.info("Component {} with id {} got lifecycle event {}", ZK_COMPONENT_NAME, zkService.getRegion(), event);
        if (Signal.START.equals(event.getSignal())) {
            if (active.get()) {
                logger.info("Component is already in active state, skipping START signal");
                return;
            }
            active.set(true);
            this.zkService.processLifecycleEvent(event);
        } else if (Signal.SHUTDOWN.equals(event.getSignal())) {
            if (!active.get()) {
                logger.info("Component is already in inactive state, skipping SHUTDOWN signal");
                return;
            }
            active.set(false);
            this.zkService.processLifecycleEvent(event);
        } else {
            logger.error("Unsupported signal received: {}", event.getSignal());
        }
    }

    /**
     * Push message into kafka-broker and do not control operation result.
     *
     * <p>Caller can check operation result by himself using returned {@link SendStatusCallback} object.
     */
    public SendStatus sendMessage(String topic, Message message) {
        SendStatus sendStatus = produce(encode(topic, message), null);
        return sendStatus;
    }

    protected SendStatus produce(ProducerRecord<String, String> record, Callback callback) {
        logger.debug("Send kafka message: {} <== key:{} value:{}", record.topic(), record.key(), record.value());
        return new SendStatus(producer.send(record, callback));
    }

    private ProducerRecord<String, String> encode(String topic, Message payload) {
        return encode(topic, null, payload);
    }

    private ProducerRecord<String, String> encode(String topic, String key, Object payload) {
        return new ProducerRecord<>(topic, key, encodeValue(payload));
    }

    private String encodeValue(Object message) {
        String encoded;
        try {
            encoded = jsonObjectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(String.format("Can not serialize message: %s", e.toString()), e);
        }

        return encoded;
    }

    /**
     * get failed sent messages count since last run.
     */
    public int getFailedSendMessageCounter() {
        return failedSendMessageCounter;
    }

    private static class SendStatusCallback implements Callback {
        private final KafkaProducerService service;
        private final String topic;
        private final String correlationId;
        private final Message message;

        SendStatusCallback(KafkaProducerService service, String topic, String correlationId) {
            this.service = service;
            this.topic = topic;
            this.correlationId = correlationId;
            this.message = null;
        }

        SendStatusCallback(KafkaProducerService service, String topic, Message message) {
            this.service = service;
            this.topic = topic;
            this.correlationId = message.getCorrelationId();
            this.message = message;
        }

        @Override
        public void onCompletion(RecordMetadata metadata, Exception exception) {
            String error = exception == null ? null : exception.toString();
            logger.debug("{}: {}, {}", this.getClass().getCanonicalName(), metadata, error);

            if (exception == null) {
                service.failedSendMessageCounter = 0;
                if (message instanceof InfoMessage) {
                    InfoData infoData = ((InfoMessage) message).getData();
                    if (infoData instanceof IslInfoData) {
                        IslInfoData isl = (IslInfoData) infoData;
                        discoLogger.debug("Isl discovery response was successfully sent: {}", isl.getPacketId());
                    }
                }
                return;
            }
            service.failedSendMessageCounter++;
            logger.error(
                    "Fail to send message(correlationId=\"{}\") in kafka topic={}: {}",
                    correlationId, topic, exception);
        }
    }
}


text:
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnSensorDepthGenerator.h"
#include <XnOpenNI.h>
#include <XnOS.h>
#include <XnPsVersion.h>
#include <XnCommon.h>
#include <math.h>

//---------------------------------------------------------------------------
// XnSensorDepthGenerator class
//---------------------------------------------------------------------------

XnSensorDepthGenerator::XnSensorDepthGenerator(xn::Context& context, xn::Device& sensor, XnDeviceBase* pSensor, const XnChar* strStreamName) :
	XnSensorMapGenerator(context, sensor, pSensor, strStreamName),
	m_hRWPropCallback(NULL)
{
}

XnSensorDepthGenerator::~XnSensorDepthGenerator()
{
	if (m_hRWPropCallback != NULL)
	{
		UnregisterFromProps(m_hRWPropCallback);
	}
}

XnStatus XnSensorDepthGenerator::Init()
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = XnSensorMapGenerator::Init();
	XN_IS_STATUS_OK(nRetVal);

	const XnChar* aProps[] =
	{
		XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE,
		XN_STREAM_PROPERTY_ZERO_PLANE_PIXEL_SIZE,
		NULL
	};

	m_hRWPropCallback;
	nRetVal = RegisterToProps(RealWorldTranslationPropChanged, this, m_hRWPropCallback, aProps);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = UpdateRealWorldTranslationData();
	if (nRetVal != XN_STATUS_OK)
	{
		UnregisterFromProps(m_hRWPropCallback);
		m_hRWPropCallback = NULL;
		return (nRetVal);
	}

	return (XN_STATUS_OK);
}

XnBool XnSensorDepthGenerator::IsCapabilitySupported(const XnChar* strCapabilityName)
{
	return (strcmp(strCapabilityName, XN_CAPABILITY_USER_POSITION) == 0 ||
		strcmp(strCapabilityName, XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) == 0 ||
		strcmp(strCapabilityName, XN_CAPABILITY_FRAME_SYNC) == 0 ||
		XnSensorMapGenerator::IsCapabilitySupported(strCapabilityName));
}

XnDepthPixel* XnSensorDepthGenerator::GetDepthMap()
{
	return (XnDepthPixel*)m_pStreamData->pData;
}

XnDepthPixel XnSensorDepthGenerator::GetDeviceMaxDepth()
{
	XnUInt64 nValue;
	m_pSensor->GetProperty(m_strModule, XN_STREAM_PROPERTY_DEVICE_MAX_DEPTH, &nValue);
	return (XnDepthPixel)nValue;
}

void XnSensorDepthGenerator::GetFieldOfView(XnFieldOfView& FOV)
{
	FOV = m_FOV;
}

XnStatus XnSensorDepthGenerator::RegisterToFieldOfViewChange(XnModuleStateChangedHandler handler, void* pCookie, XnCallbackHandle& hCallback)
{
	return m_fovChangedEvent.Register(handler, pCookie, hCallback);
}

void XnSensorDepthGenerator::UnregisterFromFieldOfViewChange(XnCallbackHandle hCallback)
{
	m_fovChangedEvent.Unregister(hCallback);
}

XnStatus XnSensorDepthGenerator::UpdateRealWorldTranslationData()
{
	XnStatus nRetVal = XN_STATUS_OK;

	XnUInt64 nZPD;
	nRetVal = GetIntProperty(XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE, nZPD);
	XN_IS_STATUS_OK(nRetVal);

	XnDouble fZPPS;
	nRetVal = GetRealProperty(XN_STREAM_PROPERTY_ZERO_PLANE_PIXEL_SIZE, fZPPS);
	XN_IS_STATUS_OK(nRetVal);

	m_FOV.fHFOV = 2*atan(fZPPS*XN_SXGA_X_RES/2/nZPD);
	m_FOV.fVFOV = 2*atan(fZPPS*XN_VGA_Y_RES*2/2/nZPD);

	nRetVal = m_fovChangedEvent.Raise();
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}

void XnSensorDepthGenerator::RealWorldTranslationPropChanged(void* pCookie)
{
	XnSensorDepthGenerator* pThis = (XnSensorDepthGenerator*)pCookie;
	pThis->UpdateRealWorldTranslationData();
}

XnUInt32 XnSensorDepthGenerator::GetSupportedUserPositionsCount()
{
	return 4;
}

XnStatus XnSensorDepthGenerator::SetUserPosition(XnUInt32 nIndex, const XnBoundingBox3D& Position)
{
	// set (we only support Z boxing for now)
	XnDepthAGCBin bin;
	bin.nBin = (XnUInt16)nIndex;
	bin.nMin = (XnUInt16)Position.LeftBottomNear.Z;
	bin.nMax = (XnUInt16)Position.RightTopFar.Z;
	return m_pSensor->SetProperty(m_strModule, XN_STREAM_PROPERTY_AGC_BIN, XN_PACK_GENERAL_BUFFER(bin));
}

XnStatus XnSensorDepthGenerator::GetUserPosition(XnUInt32 nIndex, XnBoundingBox3D& Position)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// get
	XnDepthAGCBin bin;
	bin.nBin = (XnUInt16)nIndex;
	nRetVal =  m_pSensor->GetProperty(m_strModule, XN_STREAM_PROPERTY_AGC_BIN, XN_PACK_GENERAL_BUFFER(bin));
	XN_IS_STATUS_OK(nRetVal);

	XnMapOutputMode MapOutputMode;
	nRetVal = GetMapOutputMode(MapOutputMode);
	XN_IS_STATUS_OK(nRetVal);

	// we only support Z position for now
	Position.LeftBottomNear.Z = bin.nMin;
	Position.RightTopFar.Z = bin.nMax;
	Position.LeftBottomNear.X = 0;
	Position.RightTopFar.X = (XnFloat)(MapOutputMode.nXRes - 1);
	Position.LeftBottomNear.Y = 0;
	Position.RightTopFar.Y = (XnFloat)(MapOutputMode.nYRes - 1);

	return (XN_STATUS_OK);
}

XnStatus XnSensorDepthGenerator::RegisterToUserPositionChange(XnModuleStateChangedHandler handler, void* pCookie, XnCallbackHandle& hCallback)
{
	const XnChar* aProps[] =
	{
		XN_STREAM_PROPERTY_AGC_BIN,
		NULL
	};

	return RegisterToProps(handler, pCookie, hCallback, aProps);
}

void XnSensorDepthGenerator::UnregisterFromUserPositionChange(XnCallbackHandle hCallback)
{
	UnregisterFromProps(hCallback);
}

XnBool XnSensorDepthGenerator::IsSensorImageNode(xn::ProductionNode& OtherNode)
{
	xn::NodeInfo info = OtherNode.GetInfo();

	XnVersion Version;
	Version.nMajor = XN_PS_MAJOR_VERSION;
	Version.nMinor = XN_PS_MINOR_VERSION;
	Version.nMaintenance = XN_PS_MAINTENANCE_VERSION;
	Version.nBuild = XN_PS_BUILD_VERSION;

	// check if this view point is image from this DLL
	if (info.GetDescription().Type != XN_NODE_TYPE_IMAGE ||
		strcmp(info.GetDescription().strName, XN_DEVICE_NAME) != 0 ||
		strcmp(info.GetDescription().strVendor, XN_VENDOR_PRIMESENSE) != 0 ||
		xnVersionCompare(&info.GetDescription().Version, &Version) != 0)
	{
		return FALSE;
	}

	// check if it uses the same device
	xn::NodeInfoList needed = info.GetNeededNodes();
	for (xn::NodeInfoList::Iterator it = needed.Begin(); it != needed.End(); ++it)
	{
		if ((*it).GetDescription().Type == XN_NODE_TYPE_DEVICE &&
			strcmp((*it).GetCreationInfo(), m_device.GetInfo().GetCreationInfo()) == 0)
		{
			return TRUE;
		}
	}

	return FALSE;
}

XnBool XnSensorDepthGenerator::IsViewPointSupported(xn::ProductionNode& OtherNode)
{
	return IsSensorImageNode(OtherNode);
}

XnStatus XnSensorDepthGenerator::SetViewPoint(xn::ProductionNode& OtherNode)
{
	if (IsSensorImageNode(OtherNode))
	{
		return SetIntProperty(XN_STREAM_PROPERTY_REGISTRATION, TRUE);
	}
	else
	{
		return XN_STATUS_BAD_PARAM;
	}
}

XnStatus XnSensorDepthGenerator::ResetViewPoint()
{
	return SetIntProperty(XN_STREAM_PROPERTY_REGISTRATION, FALSE);
}

XnBool XnSensorDepthGenerator::IsViewPointAs(xn::ProductionNode& OtherNode)
{
	XnUInt64 nValue = FALSE;
	GetIntProperty(XN_STREAM_PROPERTY_REGISTRATION, nValue);

	return (nValue == TRUE && IsSensorImageNode(OtherNode));
}

XnStatus XnSensorDepthGenerator::RegisterToViewPointChange(XnModuleStateChangedHandler handler, void* pCookie, XnCallbackHandle& hCallback)
{
	const XnChar* aProps[] =
	{
		XN_STREAM_PROPERTY_REGISTRATION,
		NULL
	};

	return RegisterToProps(handler, pCookie, hCallback, aProps);
}

void XnSensorDepthGenerator::UnregisterFromViewPointChange(XnCallbackHandle hCallback)
{
	UnregisterFromProps(hCallback);
}

XnStatus XnSensorDepthGenerator::GetPixelCoordinatesInViewPoint(xn::ProductionNode& other, XnUInt32 x, XnUInt32 y, XnUInt32& altX, XnUInt32& altY)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (!IsSensorImageNode(other))
	{
		return XN_STATUS_BAD_PARAM;
	}

	xn::MapGenerator image(other);
	XnMapOutputMode imageMode;
	nRetVal = image.GetMapOutputMode(imageMode);
	XN_IS_STATUS_OK(nRetVal);

	XnDepthPixel* pDepthMap = GetDepthMap();
	XnMapOutputMode mode;
	GetMapOutputMode(mode);

	if (x >= mode.nXRes || y >= mode.nYRes)
	{
		return XN_STATUS_BAD_PARAM;
	}

	XnPixelRegistration args;
	args.nDepthX = x;
	args.nDepthY = y;
	args.nDepthValue = pDepthMap[mode.nXRes * y + x];
	args.nImageXRes = imageMode.nXRes;
	args.nImageYRes = imageMode.nYRes;

	nRetVal = GetGeneralProperty(XN_STREAM_PROPERTY_PIXEL_REGISTRATION, sizeof(args), &args);
	XN_IS_STATUS_OK(nRetVal);

	altX = args.nImageX;
	altY = args.nImageY;

	return (XN_STATUS_OK);
}

XnBool XnSensorDepthGenerator::CanFrameSyncWith(xn::ProductionNode& OtherNode)
{
	return (IsSensorImageNode(OtherNode));
}

XnStatus XnSensorDepthGenerator::FrameSyncWith(xn::ProductionNode& OtherNode)
{
	if (IsSensorImageNode(OtherNode))
	{
		return m_pSensor->SetProperty(XN_MODULE_NAME_DEVICE, XN_MODULE_PROPERTY_FRAME_SYNC, (XnUInt64)TRUE);
	}
	else
	{
		return XN_STATUS_BAD_PARAM;
	}
}

XnStatus XnSensorDepthGenerator::StopFrameSyncWith(xn::ProductionNode& /*OtherNode*/)
{
	// we assume the other node is the image one (this is the only one we started)
	return m_pSensor->SetProperty(XN_MODULE_NAME_DEVICE, XN_MODULE_PROPERTY_FRAME_SYNC, (XnUInt64)FALSE);
}

XnBool XnSensorDepthGenerator::IsFrameSyncedWith(xn::ProductionNode& OtherNode)
{
	XnUInt64 nValue = FALSE;
	m_pSensor->GetProperty(XN_MODULE_NAME_DEVICE, XN_MODULE_PROPERTY_FRAME_SYNC, &nValue);

	return (nValue == TRUE && IsSensorImageNode(OtherNode));
}

XnStatus XnSensorDepthGenerator::RegisterToFrameSyncChange(XnModuleStateChangedHandler handler, void* pCookie, XnCallbackHandle& hCallback)
{
	const XnChar* aProps[] =
	{
		XN_MODULE_PROPERTY_FRAME_SYNC,
		NULL
	};

	return RegisterToProps(handler, pCookie, hCallback, aProps, XN_MODULE_NAME_DEVICE);
}

void XnSensorDepthGenerator::UnregisterFromFrameSyncChange(XnCallbackHandle hCallback)
{
	UnregisterFromProps(hCallback);
}

void XnSensorDepthGenerator::FilterProperties(XnActualPropertiesHash* pHash)
{
	XnSensorMapGenerator::FilterProperties(pHash);
	pHash->Remove(XN_STREAM_PROPERTY_REGISTRATION);
	pHash->Remove(XN_STREAM_PROPERTY_DEVICE_MAX_DEPTH);
}

//---------------------------------------------------------------------------
// XnExportedSensorDepthGenerator class
//---------------------------------------------------------------------------
XnExportedSensorDepthGenerator::XnExportedSensorDepthGenerator() :
	XnExportedSensorGenerator(XN_NODE_TYPE_DEPTH, XN_STREAM_TYPE_DEPTH)
{}

XnSensorGenerator* XnExportedSensorDepthGenerator::CreateGenerator(xn::Context& context, xn::Device& sensor, XnDeviceBase* pSensor, const XnChar* strStreamName)
{
	return XN_NEW(XnSensorDepthGenerator, context, sensor, pSensor, strStreamName);
}


text:
package com.example.xiongcen.myapplication.circleimg;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.example.xiongcen.myapplication.R;

/**
 * Created by xiongcen on 16/9/28.
 */
public class CircleActivity extends AppCompatActivity {

    private int mPathType = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.circle_activity);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a123);

        final CircleImageViewA imgViewA = (CircleImageViewA) findViewById(R.id.imgViewA);
        imgViewA.setImageBitmap(bitmap);
        imgViewA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPathType++;
                imgViewA.setPathType(mPathType % 5);
            }
        });
        imgViewA.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                startActivity(new Intent(CircleActivity.this, Activity2.class));
                return true;
            }
        });

        CircleImageViewB imgViewB = (CircleImageViewB) findViewById(R.id.imgViewB);
        imgViewB.setImageBitmap(bitmap);
        imgViewB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(CircleActivity.this, Activity3.class));
            }
        });
    }

}


text:
layout: post
title: Bookmarks
thumbnail-path: "img/bookmarks.png"
short-description: Social Bookmarking Application

---

{:.center}
![]({{ site.baseurl }}/img/bookmarks.png)

{:.center}
[Source Code](https://github.com/AnithaPal/Bookmarks)  [Website](https://personal-bookmarks.herokuapp.com)

{:.center}

## Overview
Bookmarks is a social bookmarking site that allows users to create topics and organize bookmarks under it. It also allows to browse bookmarks created by others. Users can also add bookmarks under others topics. Users can add bookmarks created by others to their profile by favoriting it.

{:.center}

## Features

+ Users can create an account, make their topics to organize it.
+ Users can email a bookmark to Bookmarks application to store and organize it.
+ Owner of the bookmarks and topics can only destroy destroy what they created.
+ Users can like and dislike  others bookmarks.
+ Users profile page displays all the topics and bookmarks they created as well as they liked.

{:.center}

## Tools
**Languages, Libraries, and Frameworks:** Ruby on Rails, jQuery, AJAX, Bootstrap, RSpec, Cabybara, Factory Girl

**Databases:** SQLite (Test, Development), PostgreSQL (Production)

**Development Tools, Gems and Methodologies:**

+ Devise for user authentication
+ SendGrid for email confirmation
+ Pundit for authorization
+ carrierwave for uploading url.

{:.center}

[<i class="fa fa-home"></i>]({{ site.baseurl | append: '/' }})


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `ExecuteErrorKind` enum in crate `futures`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, ExecuteErrorKind">

    <title>futures::future::ExecuteErrorKind - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

futures::<wbr>future

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Enum futures::<wbr>future::<wbr>ExecuteErrorKind

                       [−]

               [src]

pub enum ExecuteErrorKind {
    Shutdown,
    NoCapacity,
    // some variants omitted
}

Kinds of errors that can be returned from the Execute::spawn function.

Executors which may not always be able to accept a future may return one of
these errors, indicating why it was unable to spawn a future.

Variants

Shutdown

This executor has shut down and will no longer accept new futures to
spawn.

NoCapacity

This executor has no more capacity to run more futures. Other futures
need to finish before this executor can accept another.

Trait Implementations

impl Debug for ExecuteErrorKind

[src]

fn fmt(&self, __arg_0: &mut Formatter) -> Result

Formats the value using the given formatter.

impl Copy for ExecuteErrorKind

[src]

impl Clone for ExecuteErrorKind

[src]

fn clone(&self) -> ExecuteErrorKind

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)
1.0.0

Performs copy-assignment from source. Read more

impl PartialEq for ExecuteErrorKind

[src]

fn eq(&self, __arg_0: &ExecuteErrorKind) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Rhs) -> bool
1.0.0

This method tests for !=.

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CardsAndSymbols.ConsoleTest
{
    public class Symbol : IComparable<Symbol>, IEquatable<Symbol>
    {
        public Symbol(string name)
        {
            this.Name = name;
        }

        public string Name { get; private set; }

        public static List<Symbol> CreateDefaultSymbolList(int numSymbols)
        {
            var symbols = new List<Symbol>();

            for (int i = 0; i < numSymbols; ++i)
            {
                var symbol = new Symbol(i.ToString());
                symbols.Add(symbol);
            }

            return symbols;
        }

        public override string ToString()
        {
            return this.Name;
        }

        public override int GetHashCode()
        {
            return this.Name != null ? this.Name.GetHashCode() : 0;
        }

        public override bool Equals(object obj)
        {
            var other = obj as Symbol;
            return this.Equals(other);
        }

        public bool Equals(Symbol other)
        {
            return other != null ? this.Name == other.Name : false;
        }

        public int CompareTo(Symbol other)
        {
            if (other == null)
            {
                return 1;
            }

            return string.Compare(this.Name, other.Name);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="6dip">

    <ImageView
        android:id="@+id/chat_item_picture_other"
        android:layout_width="180dip"
        android:layout_height="180dip"
        android:layout_alignParentTop="true"
        android:layout_marginRight="6dip" />

    <TextView
        android:id="@+id/chat_item_date_other"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:ellipsize="marquee"
        android:textSize="12sp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="left"
        android:layout_toRightOf="@+id/chat_item_picture_other" />

    <TextView
        android:id="@+id/chat_item_message_other"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/chat_item_date_other"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:gravity="center_vertical|left"
        android:textSize="16sp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/chat_item_picture_other" />

    <ImageView
        android:id="@+id/chat_item_picture_own"
        android:layout_width="180dip"
        android:layout_height="180dip"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />

    <TextView
        android:id="@+id/chat_item_date_own"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:ellipsize="marquee"
        android:textSize="12sp"
        android:gravity="right"
        android:layout_alignEnd="@+id/chat_item_message_own"
        android:layout_toLeftOf="@+id/chat_item_picture_own" />

    <TextView
        android:id="@+id/chat_item_message_own"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/chat_item_date_own"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_toLeftOf="@id/chat_item_picture_own"
        android:gravity="center_vertical|right"
        android:textSize="16sp" />

</RelativeLayout>


text:
using System;
using System.Web;
using DotNetNuke.Data;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using Telerik.Web.UI.PivotGrid.Core;

#endregion

namespace DotNetNuke.Modules.Admin.Security
{
    public partial class AccessDeniedPage : PortalModuleBase
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string message = null;
            Guid messageGuid;
            var guidText = Request.QueryString["message"];
            if (!string.IsNullOrEmpty(guidText) && Guid.TryParse(guidText, out messageGuid))
            {
                message = HttpUtility.HtmlEncode(DataProvider.Instance().GetRedirectMessage(messageGuid));
            }

            UI.Skins.Skin.AddModuleMessage(this,
                !string.IsNullOrEmpty(message) ? message : Localization.GetString("AccessDenied", LocalResourceFile),
                ModuleMessage.ModuleMessageType.YellowWarning);
        }
    }
}


text:
exports.up = function (knex, Promise) {
  return knex.schema.createTable('DirectPaymentFile', function (table) {
    table.increments('PaymentFileId')
    table.string('FileType', 20).notNullable()
    table.dateTime('DateCreated').notNullable()
    table.string('Filepath', 250).notNullable()
    table.boolean('IsEnabled').defaultTo(true)
  })
    .catch(function (error) {
      console.log(error)
      throw error
    })
}

exports.down = function (knex, Promise) {
  return knex.schema.dropTable('DirectPaymentFile')
    .catch(function (error) {
      console.log(error)
      throw error
    })
}


text:
package com.dremio.exec.store;

import java.util.Set;

import org.apache.calcite.plan.RelOptRule;

import com.dremio.exec.catalog.StoragePluginId;
import com.dremio.exec.catalog.conf.SourceType;
import com.dremio.exec.ops.OptimizerRulesContext;
import com.dremio.exec.planner.PlannerPhase;
import com.google.common.collect.ImmutableSet;

/**
 * Interface that must be implemented by classes used to get rules associated
 * with a storage plugin. Note that implementations must have a zero-argument
 * constructor.
 */
public interface StoragePluginRulesFactory {

  /**
   * Get rules for this type of plugin. We only add rules for types once across instances of each type.
   * @param optimizerContext
   * @param phase
   * @param pluginType
   * @return
   */
  Set<RelOptRule> getRules(OptimizerRulesContext optimizerContext, PlannerPhase phase, SourceType pluginType);

  /**
   * Get rules for this plugin instance. We call this for each plugin instance.
   * @param optimizerContext
   * @param phase
   * @param pluginId
   * @return
   */
  Set<RelOptRule> getRules(OptimizerRulesContext optimizerContext, PlannerPhase phase, StoragePluginId pluginId);

  public static class NoOpPluginRulesFactory implements StoragePluginRulesFactory {

    @Override
    public Set<RelOptRule> getRules(OptimizerRulesContext optimizerContext, PlannerPhase phase, SourceType pluginType) {
      return ImmutableSet.of();
    }

    @Override
    public Set<RelOptRule> getRules(OptimizerRulesContext optimizerContext, PlannerPhase phase, StoragePluginId pluginId) {
      return ImmutableSet.of();
    }

  }

  public abstract class StoragePluginTypeRulesFactory implements StoragePluginRulesFactory {
    @Override
    public Set<RelOptRule> getRules(OptimizerRulesContext optimizerContext, PlannerPhase phase, StoragePluginId pluginId) {
      return ImmutableSet.of();
    }
  }
}


text:
/**
 * @fileOverview Load locales, any dynamic post-script loading activities.
 */

Exhibit.jQuery(document).ready(function() {
    var delays, localeLoaded;
    // Without threading, this shouldn't introduce a race condition,
    // but it is definitely a problem if concurrency comes into play.
    // Maybe refactoring so everything uses the delay queue under the hood
    // would make more sense.
    delays = [];
    localeLoaded = false;

    Exhibit.jQuery(document).bind("delayCreation.exhibit", function(evt, delayID) {
        delays.push(delayID);
    });

    Exhibit.jQuery(document).bind("delayFinished.exhibit", function(evt, delayID) {
        var idx = delays.indexOf(delayID);
        if (idx >= 0) {
            delays.splice(idx, 1);
            if (delays.length === 0 && localeLoaded) {
                delays = null;
                Exhibit.jQuery(document).trigger("scriptsLoaded.exhibit");
            }
        }
    });

    Exhibit.jQuery(document).bind("localeSet.exhibit", function(evt, localeURLs) {
        var i;
        for (i = 0; i < localeURLs.length; i++) {
            Exhibit.includeJavascriptFile(null, localeURLs[i]);
        }
        Exhibit.jQuery(document).trigger("loadExtensions.exhibit");
    });

    Exhibit.jQuery(document).bind("error.exhibit", function(evt, e, msg) {
        Exhibit.UI.hideBusyIndicator();
        Exhibit.Debug.exception(e, msg);
        alert(msg);
    });

    Exhibit.jQuery(document).one("localeLoaded.exhibit", function(evt) {
        localeLoaded = true;
        if (delays.length === 0) {
            Exhibit.jQuery(document).trigger("scriptsLoaded.exhibit");
        }
    });

    Exhibit.jQuery(document).one("scriptsLoaded.exhibit", function(evt) {
        Exhibit.jQuery(document).trigger("registerStaticComponents.exhibit", Exhibit.staticRegistry);
        Exhibit.jQuery(document).trigger("staticComponentsRegistered.exhibit");
    });

    if (Exhibit.params.autoCreate) {
        Exhibit.jQuery(document).one("staticComponentsRegistered.exhibit", function(evt) {
            Exhibit.autoCreate();
        });
    }

    Exhibit.jQuery(document).one("exhibitConfigured.exhibit", function(evt, ex) {
        Exhibit.Bookmark.init();
        Exhibit.History.init(ex, Exhibit.params.persist);
    });

    // Signal recording
    Exhibit.jQuery(document).one("loadExtensions.exhibit", function(evt) {
        Exhibit.signals["loadExtensions.exhibit"] = true;
    });

    Exhibit.jQuery(document).one("exhibitConfigured.exhibit", function(evt) {
        Exhibit.signals["exhibitConfigured.exhibit"] = true;
    });

    Exhibit.checkBackwardsCompatibility();
    Exhibit.staticRegistry = new Exhibit.Registry(true);

    Exhibit.jQuery("link[rel='exhibit-extension']").each(function(idx, el) {
        Exhibit.includeJavascriptFile(null, Exhibit.jQuery(el).attr("href"), false);
    });

    Exhibit.wait(function() {
        Exhibit.jQuery(document).trigger("registerLocalization.exhibit", Exhibit.staticRegistry);
    });
});


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
	<title>Vagrant-Chef</title>

	<link href="slideshow.css" rel="stylesheet" />
	<link href="theme.css" rel="stylesheet" />

Vagrant & Chef

Infrastructure as a code

Why?

People work faster

Don't focus on configuration but on the PRODUCT!

Improves Engenering, QA, Demo and CI

Local install issues

everything must be installed manually

developers don't know the "production" config

a lot of "works on my machine" bugs

multiple projects

keep development environment in sync with the team

keep wiki updated

nobody reads the wiki anyway

long onboarding time for new team members

developers are forced to one particular OS

Vagrant

"tool for creating and distributing virtualized development environments"

The Vagrant Way

encourages automation to set up environment

simple workflow

					$ git checkout ...
					$ vagrant up
					# code, code, code ...
					$ git pull
					$ vagrant provision

The Vagrant Way

developers uses own editors, browsers, and tools

existence of Vagrant is transparent and unimportant

operations engineers work on system automation scripts

they test those scripts on Vagrant boxes

production == development

Vagrant provisioners

puppet

chef

shell scripts

Chef

"systems and cloud infrastructure automation framework that makes it easy to deploy servers and applications"

Why Chef?

"configuration management as a service"

"remove people from the process of building automated infrastructure"

"powered by Ruby and a simple DSL"

How it works?

nodes, roles

cookbooks, recipes, resources

ensures that actions are not performed if the resources have not changed

order matters

Chef Modes

cookbooks in central repo

cookbooks on the node (aka chef-solo)

Berkshelf

Bundler for cookbooks

				Example of Berksfile

					site :opscode

					cookbook 'mysql'
					cookbook 'java'
					cookbook 'tomcat', path: 'lib/local-tomcat-cookbook'

Berkshelf

			AMP Berksfile

				site 'http://antenna.eng-cookbooks'

				cookbook 'amp-manager'
				cookbook 'gsb'
				cookbook 'ec'
				cookbook 'mdm'
				cookbook 'cloud'

Demo

Summing up..

What can we improve?

project dependencies management

setup environment quickly

testing on CI

testing infrastructure itself

put abstractions around complex problems

Thank You!

To read...

Vagrant (www.vagrantup.com)

Chef (docs.opscode.com)


text:
int main(void){
	printf("hello world!\n");
	return 0;
}


text:
<?php

use Bolt\Extension\Bolt\HelloWorld\Extension;

$app['extensions']->register(new Extension($app));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 4: 294 (1950)

#### Original name
Cladosporium ladinum E. Müll.

### Remarks
null


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0004_auto_20150319_1104'),
    ]

    operations = [
        migrations.AlterField(
            model_name='post',
            name='attachments',
            field=models.ManyToManyField(to='blog.Attachment'),
            preserve_default=True,
        ),
    ]


text:
CCPhysicsShape *CCPhysicsShape::create(cpShape *shape)
{
    CCPhysicsShape *shapeObject = new CCPhysicsShape(shape);
    shapeObject->autorelease();
    return shapeObject;
}

CCPhysicsShape::~CCPhysicsShape(void)
{
    cpShapeFree(m_shape);
//    CCLOG("CCPhysicsShape::~CCPhysicsShape(void)");
}

cpShape *CCPhysicsShape::getShape(void)
{
    return m_shape;
}

float CCPhysicsShape::getElasticity(void)
{
    return cpShapeGetElasticity(m_shape);
}

void CCPhysicsShape::setElasticity(float elasticity)
{
    cpShapeSetElasticity(m_shape, elasticity);
}

float CCPhysicsShape::getFriction(void)
{
    return cpShapeGetFriction(m_shape);
}

void CCPhysicsShape::setFriction(float friction)
{
    cpShapeSetFriction(m_shape, friction);
}

bool CCPhysicsShape::isSensor(void)
{
    return cpShapeGetSensor(m_shape);
}

void CCPhysicsShape::setIsSensor(bool isSensor)
{
    cpShapeSetSensor(m_shape, isSensor);
}

int CCPhysicsShape::getCollisionType(void)
{
    return cpShapeGetCollisionType(m_shape);
}

void CCPhysicsShape::setCollisionType(int collisionType)
{
    cpShapeSetCollisionType(m_shape, (cpCollisionType)collisionType);
}

int CCPhysicsShape::getCollisionGroup(void)
{
    return (int)cpShapeGetGroup(m_shape);
}

void CCPhysicsShape::setCollisionGroup(int group)
{
    cpShapeSetGroup(m_shape, (cpGroup)group);
}

int CCPhysicsShape::getCollisionLayers(void)
{
    return (int)cpShapeGetLayers(m_shape);
}

void CCPhysicsShape::setCollisionLayers(int layers)
{
    cpShapeSetLayers(m_shape, (cpLayers)layers);
}


text:
from ingenico.connect.sdk.data_object import DataObject
from ingenico.connect.sdk.domain.services.definitions.payment_context import PaymentContext

class GetIINDetailsRequest(DataObject):
    """
    | Input for the retrieval of the IIN details request.
    """

    __bin = None
    __payment_context = None

    @property
    def bin(self):
        """
        | The first digits of the credit card number from left to right with a minimum of 6 digits. Providing additional digits can result in more co-brands being returned.

        Type: str
        """
        return self.__bin

    @bin.setter
    def bin(self, value):
        self.__bin = value

    @property
    def payment_context(self):
        """
        | Optional payment context to refine the IIN lookup to filter out payment products not applicable to your payment.

        Type: :class:`ingenico.connect.sdk.domain.services.definitions.payment_context.PaymentContext`
        """
        return self.__payment_context

    @payment_context.setter
    def payment_context(self, value):
        self.__payment_context = value

    def to_dictionary(self):
        dictionary = super(GetIINDetailsRequest, self).to_dictionary()
        if self.bin is not None:
            dictionary['bin'] = self.bin
        if self.payment_context is not None:
            dictionary['paymentContext'] = self.payment_context.to_dictionary()
        return dictionary

    def from_dictionary(self, dictionary):
        super(GetIINDetailsRequest, self).from_dictionary(dictionary)
        if 'bin' in dictionary:
            self.bin = dictionary['bin']
        if 'paymentContext' in dictionary:
            if not isinstance(dictionary['paymentContext'], dict):
                raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['paymentContext']))
            value = PaymentContext()
            self.payment_context = value.from_dictionary(dictionary['paymentContext'])
        return self


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Attenuation of Chromium in Alkaline Environments Chromium Substitution in Ettringites and C4AH12- Monosulfates|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2017-01-26" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

Final Report

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Attenuation of Chromium in Alkaline Environments Chromium Substitution in Ettringites and C4AH12- Monosulfates

    EPA Grant Number: R823388

    Title: Attenuation of Chromium in Alkaline Environments Chromium Substitution in Ettringites and C4AH12- Monosulfates

    Investigators:
     Palmer, Carl D.

    Institution:

      Oregon Graduate Institute of Science & Technology

    Current Institution:

          Portland State University

    	EPA Project Officer:

           Lasat, Mitch

      Project Period:
      October 1, 1995 through
        September 30, 1998

        Project Amount:

          $176,630

      RFA:
      Exploratory Research - Engineering (1995)

          Recipients Lists

      Research Category:

          Engineering and Environmental Chemistry
          ,
          Land and Waste Management

Description:

      	Chromium is a strong oxidizing agent that is acutely toxic,
teratogenic, mutagenic, and carcinogenic. It can be found in several types of
alkaline environments including naturally alkaline soils, waste mixtures
containing bases, fly ash, cements and concrete, and chromite ore processing
wastes. Chromium containing solids found is such environments include
ettringites (Ca6Al2(CrO4)3(OH)12.26H2O) and calcium alumino-chromate
(3CaO.Al2O3.CaCrO4.12H2O), and bentorite (Ca6(Cr+)4(SO2)3(OH)12.26H2O). These
solid phases affect the concentration of chromium in the environment impact
decisions concerning the remediation and disposal of contaminated materials.
Although chromate substitution in ettringites has been recognized, little is
known about the solubility of phases, particularly those phases with
intermediate compositions in the solid solutions. We will close this gap in our
knowledge through a series of experiments that will help us identify the
conditions under which these mineral phases are stable and determine their
ability to attenuate the migration chromium in the environment. We will
synthesize phases of intermediate composition in the solid solution series. We
will measure the solubility of chromate ettringites, calcium alumino-chromate,
and Cr(III)-ettringite from 4 to 50 C and thereby determine their solubility
products and their enthalpies of reaction. We will identify reaction pathways
for the solid solutions by both dissolution and precipitation. Finally, we will
attempt to establish thermodynamic equilibrium for intermediates in the
solid-solution series.

This work will allow us to develop a conceptual understanding of the role of
chromate ettringites in attenuating chromate in alkaline environments. The
results of this study will aid in the design of better waste stabilization
techniques, will assist in the interpretation of the long term viability of
grouts used at mixed waste sites, and will help determine the transport and fate of chromium in alkaline environments.

Supplemental Keywords:

      waste management, hazardous wastes, waste stabilization, solidification and stabilization., RFA, Scientific Discipline, Toxics, Waste, Ecosystem Protection/Environmental Exposure & Risk, Environmental Chemistry, Fate & Transport, Hazardous Waste, Hazardous, 33/50, Environmental Engineering, fate and transport, chromium & chromium compounds, bentorite, teratogenic, waste stabilization, fly ash, alkaline environments, ettringites, monosulfates, hazardous chemicals, carcinogen, attenuation

Progress and Final Reports:

                Final Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Thursday, January 26, 2017


text:
<?xml version="1.0" encoding="iso-8859-1"?>

<document xmlns="http://maven.apache.org/XDOC/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">
	<properties>
	    <title>Apache Bigtop downloads</title>
	</properties>

			<subsection name="Latest Release" id="releases"></subsection>

				You can download the latest most stable release of Apache Bigtop project.
				Source code of the framework will allow you to build, deploy, test, and
				work with distributed (cluster) software for processing of large amounts
				of data.

					The latest release of Apache Bigtop software framework

					Bigtop 1.3.0 (pgp sha256 sha512)

					Repositories of instsallable binary packages built with latest release
					of the Apache Bitop project

					Installable binary artifacts

			<subsection name="Previous Releases" id="archived"></subsection>

					1.2.1 released on 2017-11-12

					Bigtop 1.2.1(pgp md5 sha1)

					1.2.0 released on 2017-03-30

					Bigtop 1.2.0(pgp md5 sha1)

					1.1.0 released on 2016-01-31

					Bigtop 1.1.0(pgp md5 sha1)

					1.0.0 released on 2015-08-12

					Bigtop 1.0.0(pgp md5 sha1)

			<subsection name="To verify Bigtop releases using GPG:" id="gpg"></subsection>

					Download the release bigtop-X.Y.Z-project.tar.gz from links above.

					Download the signature file pgp(bigtop-X.Y.Z-project.tar.gz.asc) from links above.

					Download the Bigtop KEYS file.

					$ gpg --import KEYS

					$ gpg --verify bigtop-X.Y.Z-src.tar.gz.asc

			<subsection name="To verify Bigtop releases using SHA-256 or SHA-512:" id="checksum"></subsection>

					Download the release bigtop-X.Y.Z-project.tar.gz from links above.

					Download the checksum file sha256/512 from links above.

					$ shasum -a 256 bigtop-X.Y.Z-src.tar.gz

					$ shasum -a 512 bigtop-X.Y.Z-src.tar.gz

			<subsection name="To verify Bigtop releases using SHA-1 or MD5(previous releases only):" id="checksum_prev"></subsection>

					Download the release bigtop-X.Y.Z-project.tar.gz from links above.

					Download the checksum file sha1 or md5 from links above.

					$ shasum bigtop-X.Y.Z-src.tar.gz

					$ md5 bigtop-X.Y.Z-src.tar.gz

</document>


text:
export GO111MODULE=on
VERSION=$(shell git describe --tags --candidates=1 --dirty)
FLAGS=-X main.Version=$(VERSION) -s -w

# To create a new release:
#  $ git tag vx.x.x
#  $ git push --tags
#  $ make clean
#  $ make release     # this will create 3 binaries in ./bin
#
#  Next, go to https://github.com/99designs/iamy/releases/new
#  - select the tag version you just created
#  - Attach the binaries from ./bin/*

release: bin/iamy-linux-amd64 bin/iamy-darwin-amd64 bin/iamy-windows-386.exe

bin/iamy-linux-amd64:
	@mkdir -p bin
	GOOS=linux GOARCH=amd64 go build -o $@ -ldflags="$(FLAGS)" .

bin/iamy-darwin-amd64:
	@mkdir -p bin
	GOOS=darwin GOARCH=amd64 go build -o $@ -ldflags="$(FLAGS)" .

bin/iamy-windows-386.exe:
	@mkdir -p bin
	GOOS=windows GOARCH=386 go build -o $@ -ldflags="$(FLAGS)" .

clean:
	rm -f bin/*


text:
/**
 * This is Barnes Hut simulation algorithm, generalized for n-dimensional case.
 *
 * http://www.cs.princeton.edu/courses/archive/fall03/cs126/assignments/barnes-hut.html
 */
var Vector = require('../vector.js');

module.exports = function(options) {
  options = options || {};
  options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;
  options.theta = typeof options.theta === 'number' ? options.theta : 0.8;

  // we require deterministic randomness here
  var random = require('ngraph.random').random(1984),
    InsertStack = require('./insertStack.js'),
    isSamePosition = require('./isSamePosition.js');

  var gravity = options.gravity,
    dim = options.dimension,
    updateQueue = [],
    insertStack = new InsertStack(),
    theta = options.theta,
    newNode = require('./nodeFactory.js')(dim),

    root = newNode(),
    tempLeft = new Vector(dim),
    tempRight = new Vector(dim),

    // Inserts body to the tree
    insert = function(newBody) {
      insertStack.reset();
      insertStack.push(root, newBody);

      while (!insertStack.isEmpty()) {
        var stackItem = insertStack.pop(),
          node = stackItem.node,
          body = stackItem.body;

        if (!node.body) {
          // This is internal node. Update the total mass of the node and center-of-mass.
          var pos = body.pos;
          node.mass += body.mass;
          node.massVector.moveByScale(body.mass, pos);

          // Recursively insert the body in the appropriate orthant.
          // But first find the appropriate quadrant.
          tempLeft.assign(node.left);
          tempRight.assignMedian(node.right, node.left);

          var quadIdx = 0; // Assume we are in the 0's quad.
          for (var i = 0; i < pos.length; ++i) {
            if (pos[i] > tempRight[i]) {
              quadIdx += Math.pow(2, i);
              var oldLeft = tempLeft[i];
              tempLeft[i] = tempRight[i];
              tempRight[i] = tempRight[i] + (tempRight[i] - oldLeft);
            }
          }

          var child = node[quadIdx];
          if (!child) {
            // The node is internal but this quadrant is not taken. Add subnode to it.
            child = newNode();
            child.left.assign(tempLeft);
            child.right.assign(tempRight);
            child.body = body;

            node[quadIdx] = child;
          } else {
            // continue searching in this quadrant.
            insertStack.push(child, body);
          }
        } else {
          // We are trying to add to the leaf node.
          // We have to convert current leaf into internal node
          // and continue adding two nodes.
          var oldBody = node.body;
          node.body = null; // internal nodes do not carry bodies

          if (isSamePosition(oldBody.pos, body.pos)) {
            // Next layout iteration should get larger bounding box in the first step and fix this
            return;
          }
          // Next iteration should subdivide node further.
          insertStack.push(node, oldBody);
          insertStack.push(node, body);
        }
      }
    },

    update = function(sourceBody) {
      var queue = updateQueue,
        v, r, i,
        force = new Vector(dim),
        queueLength = 1,
        shiftIdx = 0,
        pushIdx = 1;

      queue[0] = root;

      while (queueLength) {
        var node = queue[shiftIdx],
          body = node.body;

        queueLength -= 1;
        shiftIdx += 1;
        var differentBody = (body !== sourceBody);
        if (body && differentBody) {
          // If the current node is a leaf node (and it is not source body),
          // calculate the force exerted by the current node on body, and add this
          // amount to body's net force.
          tempLeft.assignSub(body.pos, sourceBody.pos);
          r = tempLeft.norm();

          if (r === 0) {
            // Poor man's protection against zero distance.
            tempLeft.assignUniform((random.nextDouble() - 0.5) / 50);
            r = tempLeft.norm();
          }

          // This is standard gravitation force calculation but we divide
          // by r^3 to save two operations when normalizing force vector.
          v = gravity * body.mass * sourceBody.mass / (r * r * r);
          force.moveByScale(v, tempLeft);
        } else if (differentBody) {
          // Otherwise, calculate the ratio s / r,  where s is the width of the region
          // represented by the internal node, and r is the distance between the body
          // and the node's center-of-mass
          tempLeft.assignWeightedDiff(node.massVector, node.mass, sourceBody.pos);
          r = tempLeft.norm();

          if (r === 0) {
            tempLeft.assignUniform((random.nextDouble() - 0.5) / 50);
            r = tempLeft.norm();
          }

          // If s / r < θ, treat this internal node as a single body, and calculate the
          // force it exerts on sourceBody, and add this amount to sourceBody's net force.
          if ((node.right[0] - node.left[0]) / r < theta) {
            // in the if statement above we consider node's width only
            // because the region was squarified during tree creation.
            // Thus there is no difference between using width or height.
            v = gravity * node.mass * sourceBody.mass / (r * r * r);
            force.moveByScale(v, tempLeft);
          } else {
            // Otherwise, run the procedure recursively on each of the current node's children.
            for (i = 0; i < node.orthants; ++i) {
              if (node[i]) {
                queue[pushIdx] = node[i];
                queueLength += 1;
                pushIdx += 1;
              }
            }
          }
        }
      }
      sourceBody.force.add(force);
    },

    insertBodies = function(bodies) {
      tempLeft.assignUniform(Number.POSITIVE_INFINITY);
      tempRight.assignUniform(Number.NEGATIVE_INFINITY);
      var i, max = bodies.length;

      // To reduce orthant tree depth we are looking for exact bounding box of all particles.
      i = max;
      var maxSide = 0;
      while (i--) {
        var pos = bodies[i].pos;
        for (var j = 0; j < pos.length ; j++) {
          if (pos[j] < tempLeft[j]) tempLeft[j] = pos[j];
          if (pos[j] > tempRight[j]) tempRight[j] = pos[j];
          var sideLength = tempRight[j] - tempLeft[j];
          if (sideLength > maxSide) maxSide = sideLength;
        }
      }

      newNode.reset();

      root = newNode();
      root.left.assign(tempLeft);
      root.right.assignUniformAdd(tempLeft, maxSide);

      i = max - 1;
      if (i > 0) {
        root.body = bodies[i];
      }
      while (i--) {
        insert(bodies[i], root);
      }
    };

  return {
    insertBodies: insertBodies,
    updateBodyForce: update,
    options: function(newOptions) {
      if (newOptions) {
        if (typeof newOptions.gravity === 'number') {
          gravity = newOptions.gravity;
        }
        if (typeof newOptions.theta === 'number') {
          theta = newOptions.theta;
        }

        return this;
      }

      return {
        gravity: gravity,
        theta: theta
      };
    }
  };
};


text:
package org.apache.oodt.cas.protocol.cli.action;

//OODT imports
import org.apache.oodt.cas.cli.exception.CmdLineActionException;
import org.apache.oodt.cas.protocol.ProtocolFactory;

/**
 * {@link ProtocolAction} for get a list of supported {@link ProtocolFactory}s.
 *
 * @author bfoster (Brian Foster)
 */
public class GetSupportedFactoriesCliAction extends ProtocolCliAction {

   @Override
   public void execute(ActionMessagePrinter printer)
         throws CmdLineActionException {
      try {
         printer.println("Supported Factories:");
         for (ProtocolFactory factory : getProtocolManager().getFactories()) {
            System.out.println(" - " + factory.getClass().getCanonicalName());
         }
      } catch (Exception e) {
         throw new CmdLineActionException(
               "Failed to get supported factories : " + e.getMessage(), e);
      }
   }
}


text:
package privet

import (
	"bytes"
	"crypto/rand"
	"crypto/sha1"
	"encoding/base64"
	"time"
)

const (
	deviceSecretLength = 24             // 24 bytes == 192 bits
	tokenTimeout       = 24 * time.Hour // Specified in GCP Privet doc.
)

// xsrfSecret generates and validates XSRF tokens.
type xsrfSecret []byte

func newXSRFSecret() xsrfSecret {
	// Generate a random device secret.
	deviceSecret := make([]byte, deviceSecretLength)
	rand.Read(deviceSecret)
	return deviceSecret
}

func (x xsrfSecret) newToken() string {
	t := time.Now()
	return x.newTokenProvideTime(t)
}

func (x xsrfSecret) newTokenProvideTime(t time.Time) string {
	tb := int64ToBytes(t.Unix())
	sum := sha1.Sum(append(x, tb...))
	token := append(sum[:], tb...)
	return base64.StdEncoding.EncodeToString(token)
}

func (x xsrfSecret) isTokenValid(token string) bool {
	return x.isTokenValidProvideTime(token, time.Now())
}

func (x xsrfSecret) isTokenValidProvideTime(token string, now time.Time) bool {
	tokenBytes, err := base64.StdEncoding.DecodeString(token)
	if err != nil {
		return false
	}

	if len(tokenBytes) != sha1.Size+8 {
		return false
	}

	tb := tokenBytes[sha1.Size:]
	t := time.Unix(bytesToInt64(tb), 0)
	if now.Sub(t) > tokenTimeout {
		return false
	}
	if t.Sub(now) > 0 {
		return false
	}

	sum := sha1.Sum(append(x, tb...))
	if 0 != bytes.Compare(sum[:], tokenBytes[:sha1.Size]) {
		return false
	}

	return true
}

func int64ToBytes(v int64) []byte {
	b := make([]byte, 8)
	for i := range b {
		b[i] = byte(v >> uint(8*i))
	}
	return b
}

func bytesToInt64(b []byte) int64 {
	if len(b) != 8 {
		return 0
	}
	var v int64
	for i := range b {
		v |= int64(b[i]) << uint(8*i)
	}
	return v
}


text:
"""
Join this site to a pool
"""

from __future__ import absolute_import, division, print_function

import os
import sys
from functools import partial

import iceprod.server.basic_config
import iceprod.server.RPCinternal

def main(cfgfile):
    cfg = iceprod.server.basic_config.BasicConfig()
    cfg.read_file(cfgfile)
    class Response:
        pass
    kwargs = {
        'address':cfg.messaging_url,
        'block':False,
        'service_name':'join_pool',
        'service_class':Response(),
        'async':False,
    }
    messaging = iceprod.server.RPCinternal.RPCService(**kwargs)
    messaging.start()

    master_url = raw_input('master_url:')
    passkey = raw_input('passkey:')
    messaging.config.set(key='master',
                         value={'status':'','url':master_url,'passkey':passkey})

if __name__ == '__main__':
    import argparse

    # Override values with cmdline options
    parser = argparse.ArgumentParser(description='IceProd Server')
    parser.add_argument('-f','--file',dest='file',type=str,default=None,
                        help='Path to config file')
    args = parser.parse_args()

    if args.file:
        cfgfile = os.path.expanduser(os.path.expandvars(args.file))
    else:
        cfgfile = iceprod.server.basic_config.locateconfig()

    main(cfgfile)


text:
require 'facturacion_electronica/version'
require 'services/pac_provider_fm'
require 'bill_xml_request'

module FacturacionElectronica
  PACS = { 'FacturacionModerna' => PacProviderFM }

  def self.cancel_cfdi request
    pac_service = choose_service(request[:pac_provider], '', request[:user_keys])
    pac_service.cancel request[:user_keys],
      request[:biller][:rfc],
      request[:uuid]
  end

  def self.create_cfdi request
    if valid_params?(request)
      new_xml_request = (BillXmlRequest.new_xml request[:biller],
                          request[:bill]).generate_xml_request
      pac_service = choose_service(request[:pac_provider], new_xml_request, request[:user_keys])
      pac_service.rining request[:user_keys]
    else
      { status: false, error_msg: 'Parametros invalidos' }
    end
  end

  def self.register_rfc request
    pac_service = choose_service(request[:pac_provider], '', request[:user_keys])
    pac_service.enable_rfc request[:user_keys], request[:biller]
  end

  private

  class << self
    def valid_params? request
      result = true
      [:user_keys, :pac_provider, :biller, :bill].each do |k|
        result = (request.has_key?(k) && is_valid?(request[k])) unless result == false
      end
      result
    end

    def is_valid? param_value
      !param_value.empty?
    end

    def choose_service(pac_provider, xml_request, user_keys)
      PACS[pac_provider].new xml_request, user_keys
    end
  end

end


text:
package com.senla.autoservice.ui.action.ordermenu;

import com.senla.autoservice.ui.action.IAction;

public class ShowOrderForPeroidTimeAction implements IAction {

	@Override
	public void excute() {
		// TODO Auto-generated method stub

	}

}


text:
import datetime as dt
import re

import pytest
import pytz

import stix2

from ...exceptions import InvalidValueError
from .constants import FAKE_TIME, MALWARE_ID, MALWARE_KWARGS

EXPECTED_MALWARE = """{
    "type": "malware",
    "id": "malware--9c4638ec-f1de-4ddb-abf4-1b760417654e",
    "created": "2016-05-12T08:17:27.000Z",
    "modified": "2016-05-12T08:17:27.000Z",
    "name": "Cryptolocker",
    "labels": [
        "ransomware"
    ]
}"""

def test_malware_with_all_required_properties():
    now = dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc)

    mal = stix2.v20.Malware(
        type="malware",
        id=MALWARE_ID,
        created=now,
        modified=now,
        labels=["ransomware"],
        name="Cryptolocker",
    )

    assert mal.serialize(pretty=True) == EXPECTED_MALWARE

def test_malware_with_empty_optional_field():
    now = dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc)

    mal = stix2.v20.Malware(
        type="malware",
        id=MALWARE_ID,
        created=now,
        modified=now,
        labels=["ransomware"],
        name="Cryptolocker",
        external_references=[],
    )

    assert mal.serialize(pretty=True) == EXPECTED_MALWARE

def test_malware_autogenerated_properties(malware):
    assert malware.type == 'malware'
    assert malware.id == 'malware--00000000-0000-4000-8000-000000000001'
    assert malware.created == FAKE_TIME
    assert malware.modified == FAKE_TIME
    assert malware.labels == ['ransomware']
    assert malware.name == "Cryptolocker"

    assert malware['type'] == 'malware'
    assert malware['id'] == 'malware--00000000-0000-4000-8000-000000000001'
    assert malware['created'] == FAKE_TIME
    assert malware['modified'] == FAKE_TIME
    assert malware['labels'] == ['ransomware']
    assert malware['name'] == "Cryptolocker"

def test_malware_type_must_be_malware():
    with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
        stix2.v20.Malware(type='xxx', **MALWARE_KWARGS)

    assert excinfo.value.cls == stix2.v20.Malware
    assert excinfo.value.prop_name == "type"
    assert excinfo.value.reason == "must equal 'malware'."
    assert str(excinfo.value) == "Invalid value for Malware 'type': must equal 'malware'."

def test_malware_id_must_start_with_malware():
    with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
        stix2.v20.Malware(id='my-prefix--', **MALWARE_KWARGS)

    assert excinfo.value.cls == stix2.v20.Malware
    assert excinfo.value.prop_name == "id"
    assert excinfo.value.reason == "must start with 'malware--'."
    assert str(excinfo.value) == "Invalid value for Malware 'id': must start with 'malware--'."

def test_malware_required_properties():
    with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
        stix2.v20.Malware()

    assert excinfo.value.cls == stix2.v20.Malware
    assert excinfo.value.properties == ["labels", "name"]

def test_malware_required_property_name():
    with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
        stix2.v20.Malware(labels=['ransomware'])

    assert excinfo.value.cls == stix2.v20.Malware
    assert excinfo.value.properties == ["name"]

def test_cannot_assign_to_malware_attributes(malware):
    with pytest.raises(stix2.exceptions.ImmutableError) as excinfo:
        malware.name = "Cryptolocker II"

    assert str(excinfo.value) == "Cannot modify 'name' property in 'Malware' after creation."

def test_invalid_kwarg_to_malware():
    with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
        stix2.v20.Malware(my_custom_property="foo", **MALWARE_KWARGS)

    assert excinfo.value.cls == stix2.v20.Malware
    assert excinfo.value.properties == ['my_custom_property']
    assert str(excinfo.value) == "Unexpected properties for Malware: (my_custom_property)."

@pytest.mark.parametrize(
    "data", [
        EXPECTED_MALWARE,
        {
            "type": "malware",
            "id": MALWARE_ID,
            "created": "2016-05-12T08:17:27.000Z",
            "modified": "2016-05-12T08:17:27.000Z",
            "labels": ["ransomware"],
            "name": "Cryptolocker",
        },
    ],
)
def test_parse_malware(data):
    mal = stix2.parse(data, version="2.0")

    assert mal.type == 'malware'
    assert mal.id == MALWARE_ID
    assert mal.created == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc)
    assert mal.modified == dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc)
    assert mal.labels == ['ransomware']
    assert mal.name == "Cryptolocker"

def test_parse_malware_invalid_labels():
    data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE)
    with pytest.raises(InvalidValueError) as excinfo:
        stix2.parse(data, version="2.0")
    assert "Invalid value for Malware 'labels'" in str(excinfo.value)

def test_parse_malware_kill_chain_phases():
    kill_chain = """
      "kill_chain_phases": [
        {
          "kill_chain_name": "lockheed-martin-cyber-kill-chain",
          "phase_name": "reconnaissance"
        }
      ]"""
    data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain)
    mal = stix2.parse(data, version="2.0")
    assert mal.kill_chain_phases[0].kill_chain_name == "lockheed-martin-cyber-kill-chain"
    assert mal.kill_chain_phases[0].phase_name == "reconnaissance"
    assert mal['kill_chain_phases'][0]['kill_chain_name'] == "lockheed-martin-cyber-kill-chain"
    assert mal['kill_chain_phases'][0]['phase_name'] == "reconnaissance"

def test_parse_malware_clean_kill_chain_phases():
    kill_chain = """
      "kill_chain_phases": [
        {
          "kill_chain_name": "lockheed-martin-cyber-kill-chain",
          "phase_name": 1
        }
      ]"""
    data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain)
    mal = stix2.parse(data, version="2.0")
    assert mal['kill_chain_phases'][0]['phase_name'] == "1"