text:
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*
 * Provides federated streams for handling call arguments
 *
 * InArgStream is for handling incoming arg parts from call frames.  It handles
 * dispatching the arg chunks into .arg{1,2,3} streams.
 *
 * OutArgStream is for creating outgoing arg parts by writing to .arg{1,2,3}
 * streams.  It handles buffering as many parts as are written within one event
 * loop tick into an Array of arg chunks.  Such array is then flushed using
 * setImmediate.
 *
 * Due to the semantic complexity involved here, this code is tested by an
 * accompanying exhaistive search test in test/argstream.js.  This test has
 * both unit tests (disabled by default for speed) and an integration test.
 */

var inherits = require('util').inherits;
var EventEmitter = require('./lib/event_emitter');
var PassThrough = require('readable-stream').PassThrough;
var Ready = require('ready-signal');
var errors = require('./errors');

function ArgStream() {
    var self = this;
    EventEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.frameEvent = self.defineEvent('frame');
    self.finishEvent = self.defineEvent('finish');

    self.arg1 = StreamArg();
    self.arg2 = StreamArg();
    self.arg3 = StreamArg();

    self.arg1.on('error', passError);
    self.arg2.on('error', passError);
    self.arg3.on('error', passError);
    function passError(err) {
        self.errorEvent.emit(self, err);
    }

    self.arg2.on('start', function onArg2Start() {
        if (!self.arg1._writableState.ended) self.arg1.end();
    });
    self.arg3.on('start', function onArg3Start() {
        if (!self.arg2._writableState.ended) self.arg2.end();
    });
}

inherits(ArgStream, EventEmitter);

function InArgStream() {
    if (!(this instanceof InArgStream)) {
        return new InArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self.streams = [self.arg1, self.arg2, self.arg3];
    self._iStream = 0;
    self.finished = false;
    self._numFinished = 0;
    self.arg1.on('finish', argFinished);
    self.arg2.on('finish', argFinished);
    self.arg3.on('finish', argFinished);
    function argFinished() {
        if (++self._numFinished >= 3 && !self.finished) {
            self.finished = true;
            self.finishEvent.emit(self);
        }
    }
}

inherits(InArgStream, ArgStream);

InArgStream.prototype.handleFrame = function handleFrame(parts, isLast) {
    var self = this;
    var stream = self.streams[self._iStream];

    if (self.finished) {
        // return new Error('unknown frame handling state');
        return errors.ArgStreamFinishedError();
    }

    for (var i = 0; i < parts.length; i++) {
        if (i > 0) stream = advance();
        if (!stream) break;
        if (parts[i].length) stream.write(parts[i]);
    }
    if (i < parts.length) {
        return errors.ArgStreamExceededFramePartsError();
    }

    if (isLast) {
        while (stream) stream = advance();
    }

    return null;

    function advance() {
        if (self._iStream < self.streams.length) {
            self.streams[self._iStream].end();
            self._iStream++;
        }
        return self.streams[self._iStream];
    }
};

function OutArgStream() {
    if (!(this instanceof OutArgStream)) {
        return new OutArgStream();
    }
    var self = this;
    ArgStream.call(self);
    self._flushImmed = null;
    self.finished = false;
    self.frame = [Buffer(0)];
    self.currentArgN = 1;
    self.arg1.on('data', function onArg1Data(chunk) {
        self._handleFrameChunk(1, chunk);
    });
    self.arg2.on('data', function onArg2Data(chunk) {
        self._handleFrameChunk(2, chunk);
    });
    self.arg3.on('data', function onArg3Data(chunk) {
        self._handleFrameChunk(3, chunk);
    });

    self.arg1.on('finish', function onArg1Finish() {
        self._handleFrameChunk(1, null);
    });
    self.arg2.on('finish', function onArg2Finish() {
        self._handleFrameChunk(2, null);
    });
    self.arg3.on('finish', function onArg3Finish() {
        if (!self.finished) {
            self._handleFrameChunk(3, null);
            self._flushParts(true);
            self.finished = true;
            self.finishEvent.emit(self);
        }
    });
}

inherits(OutArgStream, ArgStream);

OutArgStream.prototype._handleFrameChunk = function _handleFrameChunk(n, chunk) {
    var self = this;
    if (n < self.currentArgN) {
        self.errorEvent.emit(self, errors.ArgChunkOutOfOrderError({
            current: self.currentArgN,
            got: n
        }));
    } else if (n > self.currentArgN) {
        if (n - self.currentArgN > 1) {
            self.errorEvent.emit(self, errors.ArgChunkGapError({
                current: self.currentArgN,
                got: n
            }));
        }
        self.currentArgN++;
        self.frame.push(chunk);
    } else if (chunk === null) {
        if (++self.currentArgN <= 3) {
            self.frame.push(Buffer(0));
        }
    } else {
        self._appendFrameChunk(chunk);
    }
    self.deferFlushParts();
};

OutArgStream.prototype._appendFrameChunk = function _appendFrameChunk(chunk) {
    var self = this;
    var i = self.frame.length - 1;
    var buf = self.frame[i];
    if (buf.length) {
        self.frame[i] = Buffer.concat([buf, chunk]);
    } else {
        self.frame[i] = chunk;
    }
};

OutArgStream.prototype.deferFlushParts = function deferFlushParts() {
    var self = this;
    if (!self._flushImmed) {
        self._flushImmed = setImmediate(function() {
            self._flushParts();
        });
    }
};

OutArgStream.prototype._flushParts = function _flushParts(isLast) {
    var self = this;
    if (self._flushImmed) {
        clearImmediate(self._flushImmed);
        self._flushImmed = null;
    }
    if (self.finished) return;
    isLast = Boolean(isLast);
    var frame = self.frame;
    self.frame = [Buffer(0)];
    if (frame.length) self.frameEvent.emit(self, [frame, isLast]);
};

function StreamArg(options) {
    if (!(this instanceof StreamArg)) {
        return new StreamArg(options);
    }
    var self = this;
    PassThrough.call(self, options);
    self.started = false;
    self.onValueReady = self.onValueReady.bind(self);
    self.buf = null;
}
inherits(StreamArg, PassThrough);

StreamArg.prototype._write = function _write(chunk, encoding, callback) {
    var self = this;
    if (!self.started) {
        self.started = true;
        self.emit('start');
    }
    PassThrough.prototype._write.call(self, chunk, encoding, callback);
};

StreamArg.prototype.onValueReady = function onValueReady(callback) {
    var self = this;
    self.onValueReady = Ready();
    bufferStreamData(self, self.onValueReady.signal);
    self.onValueReady(callback);
};

function bufferStreamData(stream, callback) {
    var parts = [];
    stream.on('data', onData);
    stream.on('error', finish);
    stream.on('end', finish);
    function onData(chunk) {
        parts.push(chunk);
    }
    function finish(err) {
        stream.removeListener('data', onData);
        stream.removeListener('error', finish);
        stream.removeListener('end', finish);
        var buf = Buffer.concat(parts);
        stream.buf = buf;
        if (err === undefined) err = null;
        callback(err, buf);
    }
}

module.exports.InArgStream = InArgStream;
module.exports.OutArgStream = OutArgStream;


text:
#include <ck_barrier.h>
#include <ck_pr.h>

void
ck_barrier_centralized(struct ck_barrier_centralized *barrier,
		       struct ck_barrier_centralized_state *state,
		       unsigned int n_threads)
{
	unsigned int sense, value;

	/*
	 * Every execution context has a sense associated with it.
	 * This sense is reversed when the barrier is entered. Every
	 * thread will spin on the global sense until the last thread
	 * reverses it.
	 */
	sense = state->sense = ~state->sense;
	value = ck_pr_faa_uint(&barrier->value, 1);
	if (value == n_threads - 1) {
		ck_pr_store_uint(&barrier->value, 0);
		ck_pr_fence_memory();
		ck_pr_store_uint(&barrier->sense, sense);
		return;
	}

	ck_pr_fence_load();
	while (sense != ck_pr_load_uint(&barrier->sense))
		ck_pr_stall();

	ck_pr_fence_memory();
	return;
}

redpajama_set_name: RedPajamaGithub


text:
package vanadis.lang.piji;

/**
 * Exception for signalling configuration problems
 *
 * @author Kjetil Valstadsve
 */
class ConfigurationException extends PijiException {

    private static final long serialVersionUID = -564930216188395713L;

    ConfigurationException(String message) {
        super(message);
    }

    /**
     * Error info
     *
     * @param message The info
     * @param cause Cause
     */
    ConfigurationException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
{% extends 'user/base.html' %}

{% block inline_css %}
{{block.super}}
{% include 'album/album_set.css' %}
{% endblock %}

{% block title %}
{{block.super}} >
Albums
{% endblock %}

{% block user_content %}
{% include 'album/paginated_album_set.html' with album_page=album_page %}
{% endblock %}


text:
class Log < ActiveRecord::Base

  def self.last_entry_for(hostname)
    where("data->>'hostname' = ?", hostname.sub(/\.$/, '')).last
  end

  def method_missing(id)
    data && data.fetch(id.to_s, nil)
  end

end


text:
namespace ui {

// A helper class for crafting a fuchsia.ui.pointer.TouchEvent table.
class TouchEventBuilder {
 public:
  TouchEventBuilder();
  ~TouchEventBuilder();

  TouchEventBuilder& AddTime(zx_time_t time);
  TouchEventBuilder& AddSample(fuchsia::ui::pointer::TouchInteractionId id,
                               fuchsia::ui::pointer::EventPhase phase,
                               std::array<float, 2> position);
  TouchEventBuilder& AddViewParameters(
      std::array<std::array<float, 2>, 2> view,
      std::array<std::array<float, 2>, 2> viewport,
      std::array<float, 9> transform);
  TouchEventBuilder& AddResult(
      fuchsia::ui::pointer::TouchInteractionResult result);

  fuchsia::ui::pointer::TouchEvent Build();
  std::vector<fuchsia::ui::pointer::TouchEvent> BuildAsVector();

 private:
  absl::optional<zx_time_t> time_;
  absl::optional<fuchsia::ui::pointer::ViewParameters> params_;
  absl::optional<fuchsia::ui::pointer::TouchPointerSample> sample_;
  absl::optional<fuchsia::ui::pointer::TouchInteractionResult> result_;
};

// A helper class for crafting a fuchsia.ui.pointer.MouseEvent table.
class MouseEventBuilder {
 public:
  MouseEventBuilder();
  ~MouseEventBuilder();

  MouseEventBuilder& AddTime(zx_time_t time);
  MouseEventBuilder& AddSample(uint32_t id,
                               std::array<float, 2> position,
                               std::vector<uint8_t> pressed_buttons);
  MouseEventBuilder& AddViewParameters(
      std::array<std::array<float, 2>, 2> view,
      std::array<std::array<float, 2>, 2> viewport,
      std::array<float, 9> transform);
  MouseEventBuilder& AddMouseDeviceInfo(uint32_t id,
                                        std::vector<uint8_t> buttons);

  fuchsia::ui::pointer::MouseEvent Build();
  std::vector<fuchsia::ui::pointer::MouseEvent> BuildAsVector();

 private:
  absl::optional<zx_time_t> time_;
  absl::optional<fuchsia::ui::pointer::ViewParameters> params_;
  absl::optional<fuchsia::ui::pointer::MousePointerSample> sample_;
  absl::optional<fuchsia::ui::pointer::MouseDeviceInfo> device_info_;
};

}  // namespace ui

#endif  // UI_EVENTS_FUCHSIA_FAKES_POINTER_EVENT_UTILITY_H_


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

  <title>Module: YAML [The Book of Hobix]</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Module
          YAML

            In:

                lib/hobix/base.rb

Classes and Modules

      Class YAML::Omap

[Validate]


text:
package com.xinqihd.sns.gameserver.admin.gui;

import java.util.HashSet;

import javax.swing.JOptionPane;

import com.xinqihd.sns.gameserver.admin.action.CopyMongoCollectionAction;
import com.xinqihd.sns.gameserver.admin.action.game.MyTableModelDeleteRowAction;
import com.xinqihd.sns.gameserver.admin.config.ConfigKey;
import com.xinqihd.sns.gameserver.admin.config.ConfigManager;
import com.xinqihd.sns.gameserver.admin.gui.ext.MyPanel;
import com.xinqihd.sns.gameserver.admin.gui.ext.MyTablePanel;
import com.xinqihd.sns.gameserver.admin.gui.table.GamedataEditorRenderFactory;
import com.xinqihd.sns.gameserver.admin.model.GeneralMongoModel;
import com.xinqihd.sns.gameserver.admin.util.ImageUtil;
import com.xinqihd.sns.gameserver.service.RefreshMyTableService;

/**
 * It implements the GameDataPanel
 * @author wangqi
 *
 */
public class TaskGameDataPanel extends AbstractTaskPanel {

	private static TaskGameDataPanel instance = new TaskGameDataPanel();

	public TaskGameDataPanel() {
		init();
	}

	public static TaskGameDataPanel getInstance() {
		return instance;
	}

	public void init() {
		//创建工作区域
		String collection = "gamedata";
		super.initModel(collection);

		hiddenFields.add("_id");
		model.setHiddenFields(hiddenFields);

		myTable.getTable().setColumnOrders(new String[]{"key", "desc", "default", "value"});

		RefreshMyTableService service = new RefreshMyTableService(model);
		service.execute();

		myTable.setTitle("游戏基础数据");
		myTable.setTableModel(model);
		myTable.setEnableAddRow(false);
		myTable.setDelRowAction(new MyTableModelDeleteRowAction(myTable.getTable()));
		myTable.setEnableDelRow(false);
		GamedataEditorRenderFactory factory = new GamedataEditorRenderFactory(model);
		myTable.getTable().setRenderFactory(factory);
		myTable.getTable().setEditorFactory(factory);
		myTable.setBackupAction(backupAction);

		this.add(myTable, "width 100%, height 100%");
	}

}


text:
<?php

namespace Brainapp\CoreBundle\Form\AccountForm;

use Brainapp\CoreBundle\Form\AccountForm\AbstractUserAccountFormType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 *
 * @author Chris Schneider
 *
 */
class CreateUserAccountFormType extends AbstractUserAccountFormType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
	{
		parent::buildForm($builder, $options);

		$builder->add("accountStartValue", "number", array('label' => 'Startsaldo',
                                                           'attr' => array('class' => 'form-control',
                                                                           'placeholder' => 'Startsaldo',
                                                                           'aria-describedby' => 'sizing-addon2')));
	}

	public function getName()
	{
		return "createUserAccountForm";
	}
}


text:
MailWeaver
==========

Forward an e-mail to a mailing list and proxy responses to the sender if (s)he is not a member of this list

Scenario
--------

The $hackerspace has a discussion list at list@$domain and a contact addresss at $kontakt@$domain.

An outside party who is not a member on the list sends an e-mail to kontakt@$domain.

MailWeaver receives this e-mail and puts it on a curation list. All curators, i.e. those who would normally receive kontakt@$domain are informed about the new message. They have three choices:
a) Ignore the e-mail or mark it as spam.
b) Simply forward the e-mail, regaining the e-mail forward functionality.
c) Forward the e-mail to list@$domain as if it was originally sent there.

Option c) is the most interesting:
The e-mail is now posted on the mailing list. In case of an answer, which would go to the list, MailWeaver forwards the response to the original sender, allowing him/her to take part in the mailing list discussion.

Forwarding is transparently done based on the message-threading mechanism and only applies to a specific discussion.

As a result, an outside party can discuss just one issue on the list without taking part in _all_ traffic on that list.Forwarding  e-mails to the generic towards the list and relaying replies is no longer a manual task and the outside party will take part in the whole discussion.

Technology
----------

* backend uses Java with [JavaMail](https://javamail.java.net/)
* data is stored in an SQL DBMS (nothing fancy to be done here)
* contemporary HTML frontend
* attached to [mailman](http://www.gnu.org/software/mailman/)?

These are just the corner stones, this part needes to be refined!


text:
<!DOCTYPE html>

        <title>Shape Margin - inherit</title>
        <link rel="author" title="Adobe" href="http://html.adobe.com/">
        <link rel="author" title="Rebecca Hauck" href="mailto:rhauck@adobe.com">
        <link rel="help" href="http://www.w3.org/TR/css-shapes-1/#shape-margin-property">
        <meta name="assert" content="The shape-margin value is not inherited and can be assigned the 'inherit' value.">
        <meta name="flags" content="ahem dom">
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1">


text:
__author__ = 'christopher'

global player_array
global last_airdrop

player_array = []
online_players = []
last_airdrop = ""
airdrops= []
import logger

class player_object(object):
    def __init__(self):
        self.name = ""
        self.entityid = 0
        self.steamid = 0
        self.ip= ""
        self.lastlogon = ""
        self.home = ""
        self.warned = 0
        self.location = ""
        self.home = ""
        self.health = 0
        self.deaths = 0
        self.zombies = 0
        self.players = 0
        self.score = 0
        self.ping = 0
        self.position = ""
        self.pois = []
        self.tprequests = []
        self.admin = False
        self.adminlevel = 0
        self.mod = False
        self.bag = ""

def player_exists(steamid):
    for person in player_array:
        if str(person.steamid) == steamid:
            return True
    return False

def player_exists_from_name(name):
    for person in player_array:
        if person.name == name:
            return True
    return False

def poi_exists(player,poiname):
    person = get_player_from_name(player)
    for poi in person.pois:
        if poiname == poi.split(",")[0]:
            return True
    return False

def add_online_player(player):
    if player not in online_players:
        online_players.append(player)

def get_online_players():
    player_list = []
    for player in online_players:
        player_list.append(player)
    return  player_list

def remove_online_player(player):
    online_players.remove(player)

def get_player_from_steamid(steamid):
    for person in player_array:
        if steamid == str(person.steamid):
            return person

def get_player_from_name(name):
    for person in player_array:
        if name == person.name:
            return person

def get_poi(player,poiname):
    person = get_player_from_name(player)
    for poi in person.pois:
        if poiname == poi.split(",")[0]:
            poilocation = poi.split(",")[1]
            return poilocation
    return ""

def add_player(name,entityid,steamid,ip,):
    logger.log("memorydb adding  new player")
    player = player_object()
    player.name = name
    player.entityid = entityid
    player.steamid = steamid
    player.ip = ip
    player_array.append(player)

def update_player(pl):
    player = get_player_from_steamid(pl.steamid)
    player.location = pl.position
    player.name = pl.name
    player.health = pl.health
    player.deaths = pl.deaths
    player.zombies = pl.zombies
    player.players= pl.players
    player.score = pl.score
    player.ping = pl.ping

def add_poi(player,name):
    person = get_player_from_name(player)
    if poi_exists(player,name):
        for poi in person.pois:
            if name == poi.split(",")[0]:
                person.pois.remove(poi)
                person.pois.append(name + "," + person.location)
    else:
        person.pois.append(name + "," + person.location)

def remove_poi(player,name):
    for person in player_array:
        if player == person.name:
            for poi in person.pois:
                if name == poi.split(",")[0]:
                    person.pois.remove(poi)

def remove_all_pois(player):
    person = get_player_from_name(player)
    del person.pois[:]

def set_player_home(player):
    person = get_player_from_name(player)
    person.home = person.location


text:
"""Support for functionality to keep track of the sun."""
import logging
from datetime import timedelta

from homeassistant.const import (
    CONF_ELEVATION,
    SUN_EVENT_SUNRISE,
    SUN_EVENT_SUNSET,
    EVENT_CORE_CONFIG_UPDATE,
)
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.helpers.sun import (
    get_astral_location,
    get_location_astral_event_next,
)
from homeassistant.util import dt as dt_util

_LOGGER = logging.getLogger(__name__)

DOMAIN = "sun"

ENTITY_ID = "sun.sun"

STATE_ABOVE_HORIZON = "above_horizon"
STATE_BELOW_HORIZON = "below_horizon"

STATE_ATTR_AZIMUTH = "azimuth"
STATE_ATTR_ELEVATION = "elevation"
STATE_ATTR_RISING = "rising"
STATE_ATTR_NEXT_DAWN = "next_dawn"
STATE_ATTR_NEXT_DUSK = "next_dusk"
STATE_ATTR_NEXT_MIDNIGHT = "next_midnight"
STATE_ATTR_NEXT_NOON = "next_noon"
STATE_ATTR_NEXT_RISING = "next_rising"
STATE_ATTR_NEXT_SETTING = "next_setting"

# The algorithm used here is somewhat complicated. It aims to cut down
# the number of sensor updates over the day. It's documented best in
# the PR for the change, see the Discussion section of:
# https://github.com/home-assistant/home-assistant/pull/23832

# As documented in wikipedia: https://en.wikipedia.org/wiki/Twilight
# sun is:
# < -18° of horizon - all stars visible
PHASE_NIGHT = "night"
# 18°-12° - some stars not visible
PHASE_ASTRONOMICAL_TWILIGHT = "astronomical_twilight"
# 12°-6° - horizon visible
PHASE_NAUTICAL_TWILIGHT = "nautical_twilight"
# 6°-0° - objects visible
PHASE_TWILIGHT = "twilight"
# 0°-10° above horizon, sun low on horizon
PHASE_SMALL_DAY = "small_day"
# > 10° above horizon
PHASE_DAY = "day"

# 4 mins is one degree of arc change of the sun on its circle.
# During the night and the middle of the day we don't update
# that much since it's not important.
_PHASE_UPDATES = {
    PHASE_NIGHT: timedelta(minutes=4 * 5),
    PHASE_ASTRONOMICAL_TWILIGHT: timedelta(minutes=4 * 2),
    PHASE_NAUTICAL_TWILIGHT: timedelta(minutes=4 * 2),
    PHASE_TWILIGHT: timedelta(minutes=4),
    PHASE_SMALL_DAY: timedelta(minutes=2),
    PHASE_DAY: timedelta(minutes=4),
}

async def async_setup(hass, config):
    """Track the state of the sun."""
    if config.get(CONF_ELEVATION) is not None:
        _LOGGER.warning(
            "Elevation is now configured in home assistant core. "
            "See https://home-assistant.io/docs/configuration/basic/"
        )
    Sun(hass)
    return True

class Sun(Entity):
    """Representation of the Sun."""

    entity_id = ENTITY_ID

    def __init__(self, hass):
        """Initialize the sun."""
        self.hass = hass
        self.location = None
        self._state = self.next_rising = self.next_setting = None
        self.next_dawn = self.next_dusk = None
        self.next_midnight = self.next_noon = None
        self.solar_elevation = self.solar_azimuth = None
        self.rising = self.phase = None
        self._next_change = None

        def update_location(event):
            self.location = get_astral_location(self.hass)
            self.update_events(dt_util.utcnow())

        update_location(None)
        self.hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, update_location)

    @property
    def name(self):
        """Return the name."""
        return "Sun"

    @property
    def state(self):
        """Return the state of the sun."""
        # 0.8333 is the same value as astral uses
        if self.solar_elevation > -0.833:
            return STATE_ABOVE_HORIZON

        return STATE_BELOW_HORIZON

    @property
    def state_attributes(self):
        """Return the state attributes of the sun."""
        return {
            STATE_ATTR_NEXT_DAWN: self.next_dawn.isoformat(),
            STATE_ATTR_NEXT_DUSK: self.next_dusk.isoformat(),
            STATE_ATTR_NEXT_MIDNIGHT: self.next_midnight.isoformat(),
            STATE_ATTR_NEXT_NOON: self.next_noon.isoformat(),
            STATE_ATTR_NEXT_RISING: self.next_rising.isoformat(),
            STATE_ATTR_NEXT_SETTING: self.next_setting.isoformat(),
            STATE_ATTR_ELEVATION: self.solar_elevation,
            STATE_ATTR_AZIMUTH: self.solar_azimuth,
            STATE_ATTR_RISING: self.rising,
        }

    def _check_event(self, utc_point_in_time, event, before):
        next_utc = get_location_astral_event_next(
            self.location, event, utc_point_in_time
        )
        if next_utc < self._next_change:
            self._next_change = next_utc
            self.phase = before
        return next_utc

    @callback
    def update_events(self, utc_point_in_time):
        """Update the attributes containing solar events."""
        self._next_change = utc_point_in_time + timedelta(days=400)

        # Work our way around the solar cycle, figure out the next
        # phase. Some of these are stored.
        self.location.solar_depression = "astronomical"
        self._check_event(utc_point_in_time, "dawn", PHASE_NIGHT)
        self.location.solar_depression = "nautical"
        self._check_event(utc_point_in_time, "dawn", PHASE_ASTRONOMICAL_TWILIGHT)
        self.location.solar_depression = "civil"
        self.next_dawn = self._check_event(
            utc_point_in_time, "dawn", PHASE_NAUTICAL_TWILIGHT
        )
        self.next_rising = self._check_event(
            utc_point_in_time, SUN_EVENT_SUNRISE, PHASE_TWILIGHT
        )
        self.location.solar_depression = -10
        self._check_event(utc_point_in_time, "dawn", PHASE_SMALL_DAY)
        self.next_noon = self._check_event(utc_point_in_time, "solar_noon", None)
        self._check_event(utc_point_in_time, "dusk", PHASE_DAY)
        self.next_setting = self._check_event(
            utc_point_in_time, SUN_EVENT_SUNSET, PHASE_SMALL_DAY
        )
        self.location.solar_depression = "civil"
        self.next_dusk = self._check_event(utc_point_in_time, "dusk", PHASE_TWILIGHT)
        self.location.solar_depression = "nautical"
        self._check_event(utc_point_in_time, "dusk", PHASE_NAUTICAL_TWILIGHT)
        self.location.solar_depression = "astronomical"
        self._check_event(utc_point_in_time, "dusk", PHASE_ASTRONOMICAL_TWILIGHT)
        self.next_midnight = self._check_event(
            utc_point_in_time, "solar_midnight", None
        )
        self.location.solar_depression = "civil"

        # if the event was solar midday or midnight, phase will now
        # be None. Solar noon doesn't always happen when the sun is
        # even in the day at the poles, so we can't rely on it.
        # Need to calculate phase if next is noon or midnight
        if self.phase is None:
            elevation = self.location.solar_elevation(self._next_change)
            if elevation >= 10:
                self.phase = PHASE_DAY
            elif elevation >= 0:
                self.phase = PHASE_SMALL_DAY
            elif elevation >= -6:
                self.phase = PHASE_TWILIGHT
            elif elevation >= -12:
                self.phase = PHASE_NAUTICAL_TWILIGHT
            elif elevation >= -18:
                self.phase = PHASE_ASTRONOMICAL_TWILIGHT
            else:
                self.phase = PHASE_NIGHT

        self.rising = self.next_noon < self.next_midnight

        _LOGGER.debug(
            "sun phase_update@%s: phase=%s", utc_point_in_time.isoformat(), self.phase
        )
        self.update_sun_position(utc_point_in_time)

        # Set timer for the next solar event
        async_track_point_in_utc_time(self.hass, self.update_events, self._next_change)
        _LOGGER.debug("next time: %s", self._next_change.isoformat())

    @callback
    def update_sun_position(self, utc_point_in_time):
        """Calculate the position of the sun."""
        self.solar_azimuth = round(self.location.solar_azimuth(utc_point_in_time), 2)
        self.solar_elevation = round(
            self.location.solar_elevation(utc_point_in_time), 2
        )

        _LOGGER.debug(
            "sun position_update@%s: elevation=%s azimuth=%s",
            utc_point_in_time.isoformat(),
            self.solar_elevation,
            self.solar_azimuth,
        )
        self.async_write_ha_state()

        # Next update as per the current phase
        delta = _PHASE_UPDATES[self.phase]
        # if the next update is within 1.25 of the next
        # position update just drop it
        if utc_point_in_time + delta * 1.25 > self._next_change:
            return
        async_track_point_in_utc_time(
            self.hass, self.update_sun_position, utc_point_in_time + delta
        )


text:
<?php

class HTMLPurifier_Strategy_Composite_Test
    extends HTMLPurifier_Strategy_Composite
{

    public function __construct(&$strategies) {
        $this->strategies =& $strategies;
    }

}

// doesn't use Strategy harness
class HTMLPurifier_Strategy_CompositeTest extends HTMLPurifier_Harness
{

    function test() {

        generate_mock_once('HTMLPurifier_Strategy');
        generate_mock_once('HTMLPurifier_Config');
        generate_mock_once('HTMLPurifier_Context');

        // setup a bunch of mock strategies to inject into our composite test

        $mock_1 = new HTMLPurifier_StrategyMock();
        $mock_2 = new HTMLPurifier_StrategyMock();
        $mock_3 = new HTMLPurifier_StrategyMock();

        // setup the object

        $strategies = array(&$mock_1, &$mock_2, &$mock_3);
        $composite = new HTMLPurifier_Strategy_Composite_Test($strategies);

        // setup expectations

        $input_1 = 'This is raw data';
        $input_2 = 'Processed by 1';
        $input_3 = 'Processed by 1 and 2';
        $input_4 = 'Processed by 1, 2 and 3'; // expected output

        $config  = new HTMLPurifier_ConfigMock();
        $context = new HTMLPurifier_ContextMock();

        $params_1 = array($input_1, $config, $context);
        $params_2 = array($input_2, $config, $context);
        $params_3 = array($input_3, $config, $context);

        $mock_1->expectOnce('execute', $params_1);
        $mock_1->setReturnValue('execute', $input_2, $params_1);

        $mock_2->expectOnce('execute', $params_2);
        $mock_2->setReturnValue('execute', $input_3, $params_2);

        $mock_3->expectOnce('execute', $params_3);
        $mock_3->setReturnValue('execute', $input_4, $params_3);

        // perform test

        $output = $composite->execute($input_1, $config, $context);
        $this->assertIdentical($input_4, $output);

    }

}

// vim: et sw=4 sts=4


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Fault-tolerant chat</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>

Fault Tolerant Chat

                Server disconnected

                {{chat.username}}@{{connectedEndPoint}}

                  {{room}}

Canal {{selectedRoom}}

        {{message.user}} dice:

{{message.text}}

{{JSON.stringify(message)}}

            <input type="text" ng-disabled="!selectedRoom" ng-keyup="$event.keyCode == 13 && chat.post()" id="message" ng-model="text" placeholder="Message..." />

            <input type="button" ng-disabled="!selectedRoom" id="send" ng-click="chat.post()" value="Enviar" />


text:
<?php
 /**
  * ----------------------------------------------------
  * | Автор: Андрей Рыжов (Dune) <info@rznw.ru>         |
  * | Сайт: www.rznw.ru                                 |
  * | Телефон: +7 (4912) 51-10-23                       |
  * | Дата: 15.07.14
  * ----------------------------------------------------
  *
  * Обертка для кеширования результатов.
  */

class Cache
{
    protected $host = 'localhost';
    protected $port = 11;

    protected $cacheAdaptor = null;

    protected $modelName = '';
    protected $model = null;
    protected $cacheMethods = [];

    /**
     * @var ServiceManager
     */
    protected $serviceManager = null;

    public function __construct($sm)
    {
        $this->serviceManager = $sm;
    }

    public function setHost($host)
    {
        $this->host = $host;
        return $this;
    }

    public function setPort($port)
    {
        $this->port = $port;
        return $this;
    }

    /**
     * @param $name имя сервиса
     * @param array $cacheMethods методы для которых включается кеширование
     * @return $this
     */
    public function setModelName($name, $cacheMethods = [])
    {
        $this->model = null;
        $this->modelName = $name;
        $this->cacheMethods = $cacheMethods;
        return $this;
    }

    public function getModelName()
    {
        return $this->modelName;
    }

    public function getModel()
    {
        if (!$this->model) {
            $this->model = $this->serviceManager->get($this->modelName);
        }
        return $this->model;
    }

    protected function _getCacheAdaptor()
    {
        if (!$this->cacheAdaptor) {
            $this->cacheAdaptor = new Memcache();
            $this->cacheAdaptor->connect($this->host, $this->port);
        }
        return $this->cacheAdaptor;
    }

    /**
     * Через этот магический метод пропускаем  все запросы к модели.
     * Указанные кешируем.
     *
     * @param $name
     * @param $arguments
     * @return array|mixed|string
     */
    public function __call($name, $arguments)
    {
        if (!in_array($name, $this->cacheMethods)) {
            $model = $this->getModel();
            return call_user_func_array([$model, $name], $arguments);
        }

        $key = 'ObjectCache' . md5($this->getModelName() . '+' . $name . '+' . serialize($arguments));

        $adaptor = $this->_getCacheAdaptor();
        if ($result = $adaptor->get($key)) {
            $result = unserialize($result);
            return $result['data'];
        }

        $model = $this->getModel();
        $result = call_user_func_array([$model, $name], $arguments);
        $storeResult = ['data' => $result, 'time' => time()];
        $adaptor->set($key, serialize($storeResult));
        return $result;
    }

}


text:
using UnityEngine;
using Klak.Chromatics;

namespace Swarm
{
    public sealed class FloatingSwarm : MonoBehaviour
    {
        #region Instancing properties

        [SerializeField] int _instanceCount = 1000;

        public int instanceCount {
            get { return _instanceCount; }
        }

        [SerializeField] TubeTemplate _template;

        public TubeTemplate template {
            get { return _template; }
        }

        [SerializeField] float _radius = 0.005f;

        public float radius {
            get { return _radius; }
            set { _radius = value; }
        }

        [SerializeField, Range(0, 1)] float _trim = 1;

        public float trim {
            get { return _trim; }
            set { _trim = value; }
        }

        #endregion

        #region Dynamics and attractor properteis

        [SerializeField] Transform _attractor;

        public Transform attractor {
            get { return _attractor; }
            set { _attractor = value; }
        }

        [SerializeField] Vector3 _attractorPosition = Vector3.zero;

        public Vector3 attractorPosition {
            get { return _attractorPosition; }
            set { _attractorPosition = value; }
        }

        [SerializeField] float _attractorSpread = 0.01f;

        public float attractorSpread {
            get { return _attractorSpread; }
            set { _attractorSpread = value; }
        }

        [SerializeField] float _attractorForce = 5.0f;

        public float attractorForce {
            get { return _attractorForce; }
            set { _attractorForce = value; }
        }

        [SerializeField, Range(0, 1)] float _forceRandomness = 0.5f;

        public float forceRandomness {
            get { return _forceRandomness; }
            set { _forceRandomness = value; }
        }

        [SerializeField, Range(0, 6)] float _drag = 2.0f;

        public float drag {
            get { return _drag; }
            set { _drag = value; }
        }

        #endregion

        #region Noise field properties

        [SerializeField] float _headNoiseForce = 0.5f;

        public float headNoiseForce {
            get { return _headNoiseForce; }
            set { _headNoiseForce = value; }
        }

        [SerializeField] float _headNoiseFrequency = 0.5f;

        public float headNoiseFrequency {
            get { return _headNoiseFrequency; }
            set { _headNoiseFrequency = value; }
        }

        [SerializeField] float _trailNoiseVelocity = 0.01f;

        public float trailNoiseVelocity {
            get { return _trailNoiseVelocity; }
            set { _trailNoiseVelocity = value; }
        }

        [SerializeField] float _trailNoiseFrequency = 0.5f;

        public float trailNoiseFrequency {
            get { return _trailNoiseFrequency; }
            set { _trailNoiseFrequency = value; }
        }

        [SerializeField] float _noiseSpread = 0.5f;

        public float noiseSpread {
            get { return _noiseSpread; }
            set { _noiseSpread = value; }
        }

        [SerializeField] float _noiseMotion = 0.15f;

        public float noiseMotion {
            get { return _noiseMotion; }
            set { _noiseMotion = value; }
        }

        #endregion

        #region Material properties

        [SerializeField] Material _material;

        public Material material {
            get { return _material; }
        }

        [SerializeField] CosineGradient _gradient;

        public CosineGradient gradient {
            get { return _gradient; }
            set { _gradient = value; }
        }

        #endregion

        #region Misc properties

        [SerializeField] int _randomSeed;

        public int randomSeed {
            set { _randomSeed = value; }
        }

        #endregion

        #region Hidden attributes

        [SerializeField, HideInInspector] ComputeShader _compute;

        #endregion

        #region Private members

        ComputeBuffer _drawArgsBuffer;
        ComputeBuffer _positionBuffer;
        ComputeBuffer _velocityBuffer;
        ComputeBuffer _tangentBuffer;
        ComputeBuffer _normalBuffer;
        bool _materialCloned;
        MaterialPropertyBlock _props;
        Vector3 _noiseOffset;

        Vector4 AttractorVector {
            get {
                var p = _attractor ? _attractor.position : _attractorPosition;
                p = transform.InverseTransformPoint(p);
                return new Vector4(p.x, p.y, p.z, _attractorSpread);
            }
        }

        #endregion

        #region Compute configurations

        const int kThreadCount = 64;
        int ThreadGroupCount { get { return _instanceCount / kThreadCount; } }
        int InstanceCount { get { return kThreadCount * ThreadGroupCount; } }
        int HistoryLength { get { return _template.segments + 1; } }

        #endregion

        #region Public Methods

        public void ResetPositions()
        {
            if (_positionBuffer != null)
            {
                // Invoke the initialization kernel.
                var kernel = _compute.FindKernel("FloatingInit");
                _compute.SetInt("InstanceCount", InstanceCount);
                _compute.SetInt("HistoryLength", HistoryLength);
                _compute.SetVector("Attractor", AttractorVector);
                _compute.SetBuffer(kernel, "PositionBuffer", _positionBuffer);
                _compute.SetBuffer(kernel, "VelocityBuffer", _velocityBuffer);
                _compute.SetBuffer(kernel, "TangentBuffer", _tangentBuffer);
                _compute.SetBuffer(kernel, "NormalBuffer", _normalBuffer);
                _compute.Dispatch(kernel, ThreadGroupCount, 1, 1);
            }
        }

        #endregion

        #region MonoBehaviour functions

        void OnValidate()
        {
            _instanceCount = Mathf.Max(kThreadCount, _instanceCount);
            _radius = Mathf.Max(0, _radius);
            _attractorSpread = Mathf.Max(0, _attractorSpread);
            _headNoiseForce = Mathf.Max(0, _headNoiseForce);
            _headNoiseFrequency = Mathf.Max(0, _headNoiseFrequency);
            _trailNoiseVelocity = Mathf.Max(0, _trailNoiseVelocity);
            _trailNoiseFrequency = Mathf.Max(0, _trailNoiseFrequency);
            _noiseSpread = Mathf.Max(0, _noiseSpread);
        }

        void Start()
        {
            // Initialize the indirect draw args buffer.
            _drawArgsBuffer = new ComputeBuffer(
                1, 5 * sizeof(uint), ComputeBufferType.IndirectArguments
            );

            _drawArgsBuffer.SetData(new uint[5] {
                _template.mesh.GetIndexCount(0), (uint)InstanceCount, 0, 0, 0
            });

            // Allocate compute buffers.
            _positionBuffer = new ComputeBuffer(HistoryLength * InstanceCount, 16);
            _velocityBuffer = new ComputeBuffer(InstanceCount, 16);
            _tangentBuffer = new ComputeBuffer(HistoryLength * InstanceCount, 16);
            _normalBuffer = new ComputeBuffer(HistoryLength * InstanceCount, 16);

            ResetPositions();

            // This property block is used only for avoiding an instancing bug.
            _props = new MaterialPropertyBlock();
            _props.SetFloat("_UniqueID", Random.value);

            // Clone the given material before using.
            _material = new Material(_material);
            _material.name += " (cloned)";
            _materialCloned = true;

            _noiseOffset = Vector3.one * _randomSeed;
        }

        void OnDestroy()
        {
            if (_drawArgsBuffer != null) _drawArgsBuffer.Release();
            if (_positionBuffer != null) _positionBuffer.Release();
            if (_velocityBuffer != null) _velocityBuffer.Release();
            if (_tangentBuffer != null) _tangentBuffer.Release();
            if (_normalBuffer != null) _normalBuffer.Release();
            if (_materialCloned) Destroy(_material);
        }

        void Update()
        {
            var delta = Mathf.Min(Time.deltaTime, 1.0f / 30);

            if (delta > 0)
            {
                // Invoke the update compute kernel.
                var kernel = _compute.FindKernel("FloatingUpdate");

                _compute.SetInt("_InstanceCount", InstanceCount);
                _compute.SetInt("_HistoryLength", HistoryLength);

                _compute.SetFloat("RandomSeed", _randomSeed);
                _compute.SetFloat("DeltaTime", delta);

                _compute.SetVector("Attractor", AttractorVector);
                var minForce = _attractorForce * (1 - _forceRandomness);
                _compute.SetVector("Force", new Vector2(minForce, _attractorForce));
                _compute.SetFloat("Drag", Mathf.Exp(-_drag * delta));

                _compute.SetFloat("HeadNoiseForce", _headNoiseForce);
                _compute.SetFloat("HeadNoiseFrequency", _headNoiseFrequency);
                _compute.SetFloat("TrailNoiseVelocity", _trailNoiseVelocity);
                _compute.SetFloat("TrailNoiseFrequency", _trailNoiseFrequency);
                _compute.SetFloat("NoiseSpread", _noiseSpread / InstanceCount);
                _compute.SetVector("NoiseOffset", _noiseOffset);

                _compute.SetBuffer(kernel, "PositionBuffer", _positionBuffer);
                _compute.SetBuffer(kernel, "VelocityBuffer", _velocityBuffer);

                _compute.Dispatch(kernel, ThreadGroupCount, 1, 1);

                // Invoke the reconstruction kernel.
                kernel = _compute.FindKernel("FloatingReconstruct");

                _compute.SetBuffer(kernel, "PositionBufferRO", _positionBuffer);
                _compute.SetBuffer(kernel, "TangentBuffer", _tangentBuffer);
                _compute.SetBuffer(kernel, "NormalBuffer", _normalBuffer);

                _compute.Dispatch(kernel, ThreadGroupCount, 1, 1);
            }

            // Draw the mesh with instancing.
            _material.SetFloat("_Radius", _radius);

            _material.SetVector("_GradientA", _gradient.coeffsA);
            _material.SetVector("_GradientB", _gradient.coeffsB);
            _material.SetVector("_GradientC", _gradient.coeffsC2);
            _material.SetVector("_GradientD", _gradient.coeffsD2);

            _material.SetMatrix("_LocalToWorld", transform.localToWorldMatrix);
            _material.SetMatrix("_WorldToLocal", transform.worldToLocalMatrix);

            _material.SetBuffer("_PositionBuffer", _positionBuffer);
            _material.SetBuffer("_TangentBuffer", _tangentBuffer);
            _material.SetBuffer("_NormalBuffer", _normalBuffer);

            _material.SetInt("_InstanceCount", InstanceCount);
            _material.SetInt("_HistoryLength", HistoryLength);
            _material.SetInt("_IndexLimit", (int)(_trim * HistoryLength));

            Graphics.DrawMeshInstancedIndirect(
                _template.mesh, 0, _material,
                new Bounds(Vector3.zero, Vector3.one * 1000),
                _drawArgsBuffer, 0, _props
            );

            // Move the noise field.
            _noiseOffset += Vector3.one * _noiseMotion * delta;
        }

        #endregion
    }
}


text:
namespace extensions {

namespace {

// The key into the Extension prefs for an Extension's specific reporting
// settings.
const char kStoreExtensionErrorsPref[] = "store_extension_errors";

// This is the default mask for which errors to report. That is, if an extension
// does not have specific preference set, this will be used instead.
const int kDefaultMask = 0;

const char kAppsDeveloperToolsExtensionId[] =
    "ohmmkhmmmpcnpikjeljgnaoabkaalbgc";

}  // namespace

void ErrorConsole::Observer::OnErrorAdded(const ExtensionError* error) {
}

void ErrorConsole::Observer::OnErrorsRemoved(
    const std::set<std::string>& extension_ids) {
}

void ErrorConsole::Observer::OnErrorConsoleDestroyed() {
}

ErrorConsole::ErrorConsole(Profile* profile)
     : enabled_(false),
       default_mask_(kDefaultMask),
       profile_(profile),
       prefs_(NULL),
       registry_observer_(this) {
  pref_registrar_.Init(profile_->GetPrefs());
  pref_registrar_.Add(prefs::kExtensionsUIDeveloperMode,
                      base::Bind(&ErrorConsole::OnPrefChanged,
                                 base::Unretained(this)));

  registry_observer_.Add(ExtensionRegistry::Get(profile_));

  CheckEnabled();
}

ErrorConsole::~ErrorConsole() {
  FOR_EACH_OBSERVER(Observer, observers_, OnErrorConsoleDestroyed());
}

// static
ErrorConsole* ErrorConsole::Get(content::BrowserContext* browser_context) {
  return ErrorConsoleFactory::GetForBrowserContext(browser_context);
}

void ErrorConsole::SetReportingForExtension(const std::string& extension_id,
                                            ExtensionError::Type type,
                                            bool enabled) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!enabled_ || !crx_file::id_util::IdIsValid(extension_id))
    return;

  int mask = default_mask_;
  // This call can fail if the preference isn't set, but we don't really care
  // if it does, because we just use the default mask instead.
  prefs_->ReadPrefAsInteger(extension_id, kStoreExtensionErrorsPref, &mask);

  if (enabled)
    mask |= 1 << type;
  else
    mask &= ~(1 << type);

  prefs_->UpdateExtensionPref(extension_id,
                              kStoreExtensionErrorsPref,
                              new base::FundamentalValue(mask));
}

void ErrorConsole::SetReportingAllForExtension(
    const std::string& extension_id, bool enabled) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!enabled_ || !crx_file::id_util::IdIsValid(extension_id))
    return;

  int mask = enabled ? (1 << ExtensionError::NUM_ERROR_TYPES) - 1 : 0;

  prefs_->UpdateExtensionPref(extension_id,
                              kStoreExtensionErrorsPref,
                              new base::FundamentalValue(mask));
}

bool ErrorConsole::IsReportingEnabledForExtension(
    const std::string& extension_id) const {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!enabled_ || !crx_file::id_util::IdIsValid(extension_id))
    return false;

  return GetMaskForExtension(extension_id) != 0;
}

void ErrorConsole::UseDefaultReportingForExtension(
    const std::string& extension_id) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!enabled_ || !crx_file::id_util::IdIsValid(extension_id))
    return;

  prefs_->UpdateExtensionPref(extension_id, kStoreExtensionErrorsPref, NULL);
}

void ErrorConsole::ReportError(std::unique_ptr<ExtensionError> error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!enabled_ || !crx_file::id_util::IdIsValid(error->extension_id()))
    return;

  int mask = GetMaskForExtension(error->extension_id());
  if (!(mask & (1 << error->type())))
    return;

  const ExtensionError* weak_error = errors_.AddError(std::move(error));
  FOR_EACH_OBSERVER(Observer, observers_, OnErrorAdded(weak_error));
}

void ErrorConsole::RemoveErrors(const ErrorMap::Filter& filter) {
  std::set<std::string> affected_ids;
  errors_.RemoveErrors(filter, &affected_ids);
  FOR_EACH_OBSERVER(Observer, observers_, OnErrorsRemoved(affected_ids));
}

const ErrorList& ErrorConsole::GetErrorsForExtension(
    const std::string& extension_id) const {
  return errors_.GetErrorsForExtension(extension_id);
}

void ErrorConsole::AddObserver(Observer* observer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  observers_.AddObserver(observer);
}

void ErrorConsole::RemoveObserver(Observer* observer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  observers_.RemoveObserver(observer);
}

bool ErrorConsole::IsEnabledForChromeExtensionsPage() const {
  if (!profile_->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode))
    return false;  // Only enabled in developer mode.
  if (GetCurrentChannel() > version_info::Channel::DEV &&
      !FeatureSwitch::error_console()->IsEnabled())
    return false;  // Restricted to dev channel or opt-in.

  return true;
}

bool ErrorConsole::IsEnabledForAppsDeveloperTools() const {
  return ExtensionRegistry::Get(profile_)->enabled_extensions()
      .Contains(kAppsDeveloperToolsExtensionId);
}

void ErrorConsole::CheckEnabled() {
  bool should_be_enabled = IsEnabledForChromeExtensionsPage() ||
                           IsEnabledForAppsDeveloperTools();
  if (should_be_enabled && !enabled_)
    Enable();
  if (!should_be_enabled && enabled_)
    Disable();
}

void ErrorConsole::Enable() {
  enabled_ = true;

  // We postpone the initialization of |prefs_| until now because they can be
  // NULL in unit_tests. Any unit tests that enable the error console should
  // also create an ExtensionPrefs object.
  prefs_ = ExtensionPrefs::Get(profile_);

  notification_registrar_.Add(
      this,
      chrome::NOTIFICATION_PROFILE_DESTROYED,
      content::NotificationService::AllBrowserContextsAndSources());

  const ExtensionSet& extensions =
      ExtensionRegistry::Get(profile_)->enabled_extensions();
  for (ExtensionSet::const_iterator iter = extensions.begin();
       iter != extensions.end();
       ++iter) {
    AddManifestErrorsForExtension(iter->get());
  }
}

void ErrorConsole::Disable() {
  notification_registrar_.RemoveAll();
  errors_.RemoveAllErrors();
  enabled_ = false;
}

void ErrorConsole::OnPrefChanged() {
  CheckEnabled();
}

void ErrorConsole::OnExtensionUnloaded(content::BrowserContext* browser_context,
                                       const Extension* extension,
                                       UnloadedExtensionInfo::Reason reason) {
  CheckEnabled();
}

void ErrorConsole::OnExtensionLoaded(content::BrowserContext* browser_context,
                                     const Extension* extension) {
  CheckEnabled();
}

void ErrorConsole::OnExtensionInstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    bool is_update) {
  // We don't want to have manifest errors from previous installs. We want
  // to keep runtime errors, though, because extensions are reloaded on a
  // refresh of chrome:extensions, and we don't want to wipe our history
  // whenever that happens.
  errors_.RemoveErrors(ErrorMap::Filter::ErrorsForExtensionWithType(
      extension->id(), ExtensionError::MANIFEST_ERROR), nullptr);
  AddManifestErrorsForExtension(extension);
}

void ErrorConsole::OnExtensionUninstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    extensions::UninstallReason reason) {
  errors_.RemoveErrors(ErrorMap::Filter::ErrorsForExtension(extension->id()),
                       nullptr);
}

void ErrorConsole::AddManifestErrorsForExtension(const Extension* extension) {
  const std::vector<InstallWarning>& warnings =
      extension->install_warnings();
  for (std::vector<InstallWarning>::const_iterator iter = warnings.begin();
       iter != warnings.end(); ++iter) {
    ReportError(std::unique_ptr<ExtensionError>(new ManifestError(
        extension->id(), base::UTF8ToUTF16(iter->message),
        base::UTF8ToUTF16(iter->key), base::UTF8ToUTF16(iter->specific))));
  }
}

void ErrorConsole::Observe(int type,
                           const content::NotificationSource& source,
                           const content::NotificationDetails& details) {
  DCHECK_EQ(chrome::NOTIFICATION_PROFILE_DESTROYED, type);
  Profile* profile = content::Source<Profile>(source).ptr();
  // If incognito profile which we are associated with is destroyed, also
  // destroy all incognito errors.
  if (profile->IsOffTheRecord() && profile_->IsSameProfile(profile))
    errors_.RemoveErrors(ErrorMap::Filter::IncognitoErrors(), nullptr);
}

int ErrorConsole::GetMaskForExtension(const std::string& extension_id) const {
  // Registered preferences take priority over everything else.
  int pref = 0;
  if (prefs_->ReadPrefAsInteger(extension_id, kStoreExtensionErrorsPref, &pref))
    return pref;

  // If the extension is unpacked, we report all error types by default.
  const Extension* extension =
      ExtensionRegistry::Get(profile_)->GetExtensionById(
          extension_id, ExtensionRegistry::EVERYTHING);
  if (extension && extension->location() == Manifest::UNPACKED)
    return (1 << ExtensionError::NUM_ERROR_TYPES) - 1;

  // Otherwise, use the default mask.
  return default_mask_;
}

}  // namespace extensions


text:
package org.sagebionetworks.web.client.widget.entity.controller;

import org.sagebionetworks.repo.model.entitybundle.v2.EntityBundle;
import org.sagebionetworks.web.client.utils.Callback;

public interface UploadController {
  /**
   * Check that the user can upload data to a container.
   *
   * @param parentId The ID entity upload destination.
   * @param entityClassName The full class name of the entity to be created.
   * @param callback
   */
  public void checkUploadToEntity(EntityBundle bundle, Callback callback);
}


text:
package it.uniroma2.sag.kelp.predictionfunction.model;

import it.uniroma2.sag.kelp.data.label.Label;

import java.util.List;

/**
 * It is a model which aggregates BinaryModels. It is mainly adopted in multiclass learning tasks.
 *
 * @author Simone Filice
 *
 */
public class MulticlassModel implements Model{

	/**
	 *
	 */
	private static final long serialVersionUID = 4503770841547110120L;
	protected List<Label> labels;
	private List<BinaryModel> models;

	/**
	 * @return the models
	 */
	public List<BinaryModel> getModels() {
		return models;
	}

	/**
	 * @param models the models to set
	 */
	public void setModels(List<BinaryModel> models) {
		this.models = models;
	}

	/**
	 * @return the labels
	 */
	public List<Label> getLabels() {
		return labels;
	}

	/**
	 * @param labels the labels to set
	 */
	public void setLabels(List<Label> labels) {
		this.labels = labels;
	}

	@Override
	public void reset() {
		for(BinaryModel model : this.models){
			model.reset();
		}
	}

}


text:
package viper.util

import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.{BlockingQueue, LinkedBlockingQueue}

import scala.collection.mutable
import scala.collection.JavaConversions._

/**
 * A utility that uses a thread to progress single events, and another thread
 * to report them in batches.
 */
class AsyncChunker[T](name: String, periodMillis: Int, process: () => Option[T], deliver: Seq[T] => Unit) {

  private val running = new AtomicBoolean(true)
  private val threads = new mutable.ArrayBuffer[Thread]()
  private val buffer = new LinkedBlockingQueue[T]()

  def start() {
    val processing = new ProcessingThread(buffer)
    val delivery = new DeliveryThread(buffer, deliver)

    threads ++= Seq(processing, delivery)

    processing.start()
    delivery.start()
  }

  def stop() {
    running.set(false)
    threads.foreach(_.join())
    buffer.clear()
  }

  class ProcessingThread(buffer: BlockingQueue[T])
    extends Thread(name + "-processing") {

    override def run() {
      while (running.get) {
        process().foreach(buffer.put(_))
      }
    }
  }

  class DeliveryThread(buffer: BlockingQueue[T], notify: Seq[T] => Unit)
    extends Thread(name + "-delivery") {

    override def run() {
      while (running.get) {
        val records = new java.util.ArrayList[T](500)
        // Obtain all records currently read, and deliver them as a batch
        buffer.drainTo(records)
        if (!records.isEmpty) {
          notify(records.toSeq)
        }
        Thread.sleep(periodMillis)
      }
    }
  }

}


text:
@interface PodsDummy_Pods_GlowingLabel_Example : NSObject
@end
@implementation PodsDummy_Pods_GlowingLabel_Example
@end


text:
package resources

import "github.com/awslabs/goformation/cloudformation/policies"

// AWSServerlessFunction_DeadLetterQueue AWS CloudFormation Resource (AWS::Serverless::Function.DeadLetterQueue)
// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#deadletterqueue-object
type AWSServerlessFunction_DeadLetterQueue struct {

	// TargetArn AWS CloudFormation Property
	// Required: true
	// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
	TargetArn string `json:"TargetArn,omitempty"`

	// Type AWS CloudFormation Property
	// Required: true
	// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
	Type string `json:"Type,omitempty"`

	// _deletionPolicy represents a CloudFormation DeletionPolicy
	_deletionPolicy policies.DeletionPolicy

	// _dependsOn stores the logical ID of the resources to be created before this resource
	_dependsOn []string

	// _metadata stores structured data associated with this resource
	_metadata map[string]interface{}
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSServerlessFunction_DeadLetterQueue) AWSCloudFormationType() string {
	return "AWS::Serverless::Function.DeadLetterQueue"
}

// DependsOn returns a slice of logical ID names this resource depends on.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSServerlessFunction_DeadLetterQueue) DependsOn() []string {
	return r._dependsOn
}

// SetDependsOn specify that the creation of this resource follows another.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSServerlessFunction_DeadLetterQueue) SetDependsOn(dependencies []string) {
	r._dependsOn = dependencies
}

// Metadata returns the metadata associated with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSServerlessFunction_DeadLetterQueue) Metadata() map[string]interface{} {
	return r._metadata
}

// SetMetadata enables you to associate structured data with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSServerlessFunction_DeadLetterQueue) SetMetadata(metadata map[string]interface{}) {
	r._metadata = metadata
}

// SetDeletionPolicy applies an AWS CloudFormation DeletionPolicy to this resource
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html
func (r *AWSServerlessFunction_DeadLetterQueue) SetDeletionPolicy(policy policies.DeletionPolicy) {
	r._deletionPolicy = policy
}


text:
package com.hellblazer.utils.fd.impl;

import com.hellblazer.utils.fd.FailureDetector;
import com.hellblazer.utils.fd.FailureDetectorFactory;

/**
 *
 * @author Hal Hildebrand
 *
 */
public class AdaptiveFailureDetectorFactory implements FailureDetectorFactory {
    private double convictionThreshold;
    private int    windowSize;
    private long   expectedSampleInterval;
    private int    initialSamples;
    private double minimumInterval;
    private double scale;

    public AdaptiveFailureDetectorFactory() {
    }

    /**
     *
     * @param convictionThreshold
     *            - the level of certainty that must be met before conviction.
     *            This value must be <= 1.0
     * @param windowSize
     *            - the number of samples in the window
     * @param scale
     *            - a scale factor to accomidate the real world
     * @param expectedSampleInterval
     *            - the expected sample interval, used to prime the detector
     * @param initialSamples
     *            - the number of initial samples to prime the detector
     * @param minimumInterval
     *            - the minimum inter arival interval
     */
    public AdaptiveFailureDetectorFactory(double convictionThreshold,
                                          int windowSize, double scale,
                                          long expectedSampleInterval,
                                          int initialSamples,
                                          double minimumInterval) {
        if (convictionThreshold > 1.0) {
            throw new IllegalArgumentException(
                                               String.format("Conviction threshold %s must be <= 1.0",
                                                             convictionThreshold));
        }
        this.convictionThreshold = convictionThreshold;
        this.windowSize = windowSize;
        this.expectedSampleInterval = expectedSampleInterval;
        this.initialSamples = initialSamples;
        this.minimumInterval = minimumInterval;
        this.scale = scale;
    }

    @Override
    public FailureDetector create() {
        return new AdaptiveFailureDetector(convictionThreshold, windowSize,
                                           scale, expectedSampleInterval,
                                           initialSamples, minimumInterval);
    }

    /**
     * @return the convictionThreshold
     */
    public double getConvictionThreshold() {
        return convictionThreshold;
    }

    /**
     * @return the expectedSampleInterval
     */
    public long getExpectedSampleInterval() {
        return expectedSampleInterval;
    }

    /**
     * @return the initialSamples
     */
    public int getInitialSamples() {
        return initialSamples;
    }

    /**
     * @return the minimumInterval
     */
    public double getMinimumInterval() {
        return minimumInterval;
    }

    /**
     * @return the scale
     */
    public double getScale() {
        return scale;
    }

    /**
     * @return the windowSize
     */
    public int getWindowSize() {
        return windowSize;
    }

    /**
     * @param convictionThreshold
     *            the convictionThreshold to set
     */
    public void setConvictionThreshold(double convictionThreshold) {
        this.convictionThreshold = convictionThreshold;
    }

    /**
     * @param expectedSampleInterval
     *            the expectedSampleInterval to set
     */
    public void setExpectedSampleInterval(long expectedSampleInterval) {
        this.expectedSampleInterval = expectedSampleInterval;
    }

    /**
     * @param initialSamples
     *            the initialSamples to set
     */
    public void setInitialSamples(int initialSamples) {
        this.initialSamples = initialSamples;
    }

    /**
     * @param minimumInterval
     *            the minimumInterval to set
     */
    public void setMinimumInterval(double minimumInterval) {
        this.minimumInterval = minimumInterval;
    }

    /**
     * @param scale
     *            the scale to set
     */
    public void setScale(double scale) {
        this.scale = scale;
    }

    /**
     * @param windowSize
     *            the windowSize to set
     */
    public void setWindowSize(int windowSize) {
        this.windowSize = windowSize;
    }

}


text:
package com.hazelcast.client.impl.protocol.codec;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;
import com.hazelcast.client.impl.protocol.codec.custom.*;

import javax.annotation.Nullable;

import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

/*
 * This file is auto-generated by the Hazelcast Client Protocol Code Generator.
 * To change this file, edit the templates or the protocol
 * definitions on the https://github.com/hazelcast/hazelcast-client-protocol
 * and regenerate it.
 */

/**
 * Creates a publisher that does not include value for the cache events it sends.
 */
@Generated("587cabf82b59b06e640c763def06036f")
public final class ContinuousQueryPublisherCreateCodec {
    //hex: 0x160200
    public static final int REQUEST_MESSAGE_TYPE = 1442304;
    //hex: 0x160201
    public static final int RESPONSE_MESSAGE_TYPE = 1442305;
    private static final int REQUEST_BATCH_SIZE_FIELD_OFFSET = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_BUFFER_SIZE_FIELD_OFFSET = REQUEST_BATCH_SIZE_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_DELAY_SECONDS_FIELD_OFFSET = REQUEST_BUFFER_SIZE_FIELD_OFFSET + INT_SIZE_IN_BYTES;
    private static final int REQUEST_POPULATE_FIELD_OFFSET = REQUEST_DELAY_SECONDS_FIELD_OFFSET + LONG_SIZE_IN_BYTES;
    private static final int REQUEST_COALESCE_FIELD_OFFSET = REQUEST_POPULATE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES;
    private static final int REQUEST_INITIAL_FRAME_SIZE = REQUEST_COALESCE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES;
    private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;

    private ContinuousQueryPublisherCreateCodec() {
    }

    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"})
    public static class RequestParameters {

        /**
         * Name of the map.
         */
        public java.lang.String mapName;

        /**
         * Name of query cache.
         */
        public java.lang.String cacheName;

        /**
         * The predicate to filter events which will be applied to the QueryCache.
         */
        public com.hazelcast.internal.serialization.Data predicate;

        /**
         * The size of batch. After reaching this minimum size, node immediately sends buffered events to QueryCache.
         */
        public int batchSize;

        /**
         * Maximum number of events which can be stored in a buffer of partition.
         */
        public int bufferSize;

        /**
         * The minimum number of delay seconds which an event waits in the buffer of node.
         */
        public long delaySeconds;

        /**
         * Flag to enable/disable initial population of the QueryCache.
         */
        public boolean populate;

        /**
         * Flag to enable/disable coalescing. If true, then only the last updated value for a key is placed in the
         * batch, otherwise all changed values are included in the update.
         */
        public boolean coalesce;
    }

    public static ClientMessage encodeRequest(java.lang.String mapName, java.lang.String cacheName, com.hazelcast.internal.serialization.Data predicate, int batchSize, int bufferSize, long delaySeconds, boolean populate, boolean coalesce) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        clientMessage.setRetryable(true);
        clientMessage.setOperationName("ContinuousQuery.PublisherCreate");
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);
        encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);
        encodeInt(initialFrame.content, REQUEST_BATCH_SIZE_FIELD_OFFSET, batchSize);
        encodeInt(initialFrame.content, REQUEST_BUFFER_SIZE_FIELD_OFFSET, bufferSize);
        encodeLong(initialFrame.content, REQUEST_DELAY_SECONDS_FIELD_OFFSET, delaySeconds);
        encodeBoolean(initialFrame.content, REQUEST_POPULATE_FIELD_OFFSET, populate);
        encodeBoolean(initialFrame.content, REQUEST_COALESCE_FIELD_OFFSET, coalesce);
        clientMessage.add(initialFrame);
        StringCodec.encode(clientMessage, mapName);
        StringCodec.encode(clientMessage, cacheName);
        DataCodec.encode(clientMessage, predicate);
        return clientMessage;
    }

    public static ContinuousQueryPublisherCreateCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        RequestParameters request = new RequestParameters();
        ClientMessage.Frame initialFrame = iterator.next();
        request.batchSize = decodeInt(initialFrame.content, REQUEST_BATCH_SIZE_FIELD_OFFSET);
        request.bufferSize = decodeInt(initialFrame.content, REQUEST_BUFFER_SIZE_FIELD_OFFSET);
        request.delaySeconds = decodeLong(initialFrame.content, REQUEST_DELAY_SECONDS_FIELD_OFFSET);
        request.populate = decodeBoolean(initialFrame.content, REQUEST_POPULATE_FIELD_OFFSET);
        request.coalesce = decodeBoolean(initialFrame.content, REQUEST_COALESCE_FIELD_OFFSET);
        request.mapName = StringCodec.decode(iterator);
        request.cacheName = StringCodec.decode(iterator);
        request.predicate = DataCodec.decode(iterator);
        return request;
    }

    public static ClientMessage encodeResponse(java.util.Collection<com.hazelcast.internal.serialization.Data> response) {
        ClientMessage clientMessage = ClientMessage.createForEncode();
        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);
        encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);
        clientMessage.add(initialFrame);

        ListMultiFrameCodec.encode(clientMessage, response, DataCodec::encode);
        return clientMessage;
    }

    /**
    * Array of keys.
    */
    public static java.util.List<com.hazelcast.internal.serialization.Data> decodeResponse(ClientMessage clientMessage) {
        ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();
        //empty initial frame
        iterator.next();
        return ListMultiFrameCodec.decode(iterator, DataCodec::decode);
    }

}


text:
In this section, PoliTHINK and JACPoL Policy Engines are compared.  We summarize the comparison in the table as below:

|                        | [PoliTHINK](https://github.com/reTHINK-project/dev-runtime-core/tree/develop/src/policy) | [JACPoL](https://github.com/reTHINK-project/dev-msg-node-nodejs/tree/master/src/main/components/policyEngine) |
| ---------------------- | :--------------------------------------: | :--------------------------------------: |
| Programming Language   |                 Javascript                  |                 Javascript                  |
| Environment            |               Runtime Core and Messaging Node               |              Messaging Node              |
| Administrative Domain  |                 End User and CSP                |                   CSP                    |
| Policy Management      |             Locally Defined              |           Remotely Maintained            |
| Policy Language Syntax |                   JSON                   |                   JSON                   |
| Architecture           |                 PDP/PEP                  |             PDP/PEP/PRP/PIP              |
| Access Control Scheme  |                   ABAC                   |                   ABAC                   |
| User Interface         |                   Yes                    |                    No                    |
| Complex Rule           |              Partly Support              |                 Support                  |
| Obligation             |                 Support                  |                 Support                  |
| Context Awareness      |                   Yes                    |                   Yes                    |
| Policy Readability     |                  Medium                  |                   High                   |
| Policy Expressiveness  |                  Medium                  |                   High                   |
| Policy Index           |              Partly Support              |                 Support                  |

As we can see, the two policy engines have the following features in common:

- Both are developed in Javascript.
- Both policy languages follow JSON syntax.
- Both employ ABAC access control scheme.
- Both support obligation and are context sensible.
- Both adopt PEP/PDP architecture.

On the other hand, they have following differences:

- The PoliTHINK was designed to be used in the runtime browser for the end user and in the backend Message Node for the CSP, while the JACPoL is limited to be used in the backend component for the CSP.
- The PoliTHINK policies are managed locally through a user web interface, while the JACPoL policies are maintained remotely in a repository.
- In addition to PDP, PEP components, the JACPoL policy engine has additional modules such as PIP and PRP.
- The JACPoL policy engine does not have a web UI.
- The PoliTHINK policy engine does not fully support complex rule or policy index, which would be illustrated further in the subsequent paragraphs.
- At last, although both use JSON syntax, the JACPoL policy language semantics is more expressive and readable than the PoliTHINK policy language.

In the following text we compare policy specification languages of the two policy engines. Please refer to here for more information about [the runtime policy language](https://github.com/reTHINK-project/specs/blob/master/policy-management/runtime/policy-specification-language.md) [5] and here for [the CSP policy language](https://github.com/reTHINK-project/dev-msg-node-nodejs/tree/master/src/main/components/policyEngine/prp/policy) [3].

**Readability.** Given the rule as below for example, we can see that for the same rule, the JACPoL policy language is more readable than the PoliTHINK policy.

<img src="./images/examplerule.png" width="940" height="360" />

**Fig. 7 - A runtime rule example (upper) and a CSP rule example (lower) to verify working hours.**

**Expressiveness.** From the above example we can see both policy language can express complex condition using logical operators (AND, OR, NOT) to combine constraints on multiple attributes. However, in addition to that, the CSP policy language also support the following semantics that the runtime policy language does not support:

```json
{"sumOf x y": {"not": {"anyOf": [
        {"between": "j k"},
        {"equals": "z"}]}}}
```

in which the string "sumOf x y" is an *attribute condition*. The keyword *sumOf* defines a function to compute the sum of attributes *x* and *y*, which is to be evaluated by the subsequent *condition expression*. Please note that a parameter like *j, k* or *z* can also possibly be another attribute instead of an explicit value. In this sense, we can see that the CSP policy language can do more flexible examination on the attributes using various operations.

**Scalability.** Both policy languages support rule index using a *target* field to verify the applicability of a given rule. However, the PoliTHINK policy language does not include this concept for policy index, which may cause it less scalable and not efficient.


text:
.class Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;
.super Ljava/lang/Object;
.source "IconMenuPresenter.java"

# interfaces
.implements Lcom/android/internal/view/menu/MenuPresenter$Callback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/view/menu/IconMenuPresenter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "SubMenuPresenterCallback"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

# direct methods
.method constructor <init>(Lcom/android/internal/view/menu/IconMenuPresenter;)V
    .locals 0

    .prologue
    .line 176
    iput-object p1, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onCloseMenu(Lcom/android/internal/view/menu/MenuBuilder;Z)V
    .locals 2
    .param p1, "menu"    # Lcom/android/internal/view/menu/MenuBuilder;
    .param p2, "allMenusAreClosing"    # Z

    .prologue
    .line 179
    iget-object v0, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    const/4 v1, 0x0

    iput v1, v0, Lcom/android/internal/view/menu/IconMenuPresenter;->mOpenSubMenuId:I

    .line 180
    iget-object v0, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    iget-object v0, v0, Lcom/android/internal/view/menu/IconMenuPresenter;->mOpenSubMenu:Lcom/android/internal/view/menu/MenuDialogHelper;

    if-eqz v0, :cond_0

    .line 181
    iget-object v0, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    iget-object v0, v0, Lcom/android/internal/view/menu/IconMenuPresenter;->mOpenSubMenu:Lcom/android/internal/view/menu/MenuDialogHelper;

    invoke-virtual {v0}, Lcom/android/internal/view/menu/MenuDialogHelper;->dismiss()V

    .line 182
    iget-object v0, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    const/4 v1, 0x0

    iput-object v1, v0, Lcom/android/internal/view/menu/IconMenuPresenter;->mOpenSubMenu:Lcom/android/internal/view/menu/MenuDialogHelper;

    .line 184
    :cond_0
    return-void
.end method

.method public onOpenSubMenu(Lcom/android/internal/view/menu/MenuBuilder;)Z
    .locals 2
    .param p1, "subMenu"    # Lcom/android/internal/view/menu/MenuBuilder;

    .prologue
    .line 188
    if-eqz p1, :cond_0

    .line 189
    iget-object v0, p0, Lcom/android/internal/view/menu/IconMenuPresenter$SubMenuPresenterCallback;->this$0:Lcom/android/internal/view/menu/IconMenuPresenter;

    check-cast p1, Lcom/android/internal/view/menu/SubMenuBuilder;

    .end local p1    # "subMenu":Lcom/android/internal/view/menu/MenuBuilder;
    invoke-virtual {p1}, Lcom/android/internal/view/menu/SubMenuBuilder;->getItem()Landroid/view/MenuItem;

    move-result-object v1

    invoke-interface {v1}, Landroid/view/MenuItem;->getItemId()I

    move-result v1

    iput v1, v0, Lcom/android/internal/view/menu/IconMenuPresenter;->mOpenSubMenuId:I

    .line 191
    :cond_0
    const/4 v0, 0x0

    return v0
.end method


text:
package com.covertbagel.neko;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import java.util.List;
import java.util.Random;

import static android.app.NotificationManager.IMPORTANCE_DEFAULT;

public final class NekoService extends JobService {

    private static final int JOB_ID = 42;
    private static final int CAT_NOTIFICATION = 1;
    private static final long SECONDS = 1000;
    private static final long MINUTES = 60 * SECONDS;
    private static final long INTERVAL_FLEX = 5 * MINUTES;
    private static final float INTERVAL_JITTER_FRAC = 0.25f;
    private static final long[] PURR = {0, 40, 20, 40, 20, 40, 20, 40, 20, 40, 20, 40};
    private static final String CHANNEL_ID = "arrivals";
    private static final String CHANNEL_NAME = "Arrivals";
    private static final String TAG = "NekoService";
    static final Random RANDOM = new Random();

    @SuppressWarnings("ObsoleteSdkInt")
    @Override
    public boolean onStartJob(JobParameters params) {
        final PrefState prefs = new PrefState(this);
        final int food = prefs.getFoodState();
        if (food != 0) {
            prefs.setFoodState(0); // nom
            final Cat cat;
            final List<Cat> cats = prefs.getCats();
            final int[] probs = getResources().getIntArray(R.array.food_new_cat_prob);
            final float newCatProb = (float)((food < probs.length) ? probs[food] : 50) / 100f;
            if (cats.size() == 0 || RANDOM.nextFloat() <= newCatProb) {
                cat = Cat.create(this);
                prefs.addCat(cat);
            } else {
                cat = cats.get(RANDOM.nextInt(cats.size()));
            }
            final NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                if (Build.VERSION.SDK_INT >= 29) {
                    final NotificationChannel channel =
                            new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, IMPORTANCE_DEFAULT);
                    channel.setSound(null, null);
                    channel.setVibrationPattern(PURR);
                    manager.createNotificationChannel(channel);
                }
                manager.notify(CAT_NOTIFICATION, cat.buildNotification(this, CHANNEL_ID, PURR));
            } else {
                Log.w(TAG, "Null NotificationManager in onStartJob()");
            }
        }
        cancelJob(this);
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }

    static void registerJobIfNeeded(Context context, long intervalMinutes) {
        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        if (jobScheduler == null) {
            Log.w(TAG, "Null JobScheduler in registerJobIfNeeded()");
            return;
        }
        if (jobScheduler.getPendingJob(JOB_ID) == null) {
            registerJob(context, intervalMinutes);
        }
    }

    public static void registerJob(Context context, long intervalMinutes) {
        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        if (jobScheduler == null) {
            Log.w(TAG, "Null JobScheduler in registerJob()");
            return;
        }
        jobScheduler.cancel(JOB_ID);
        long interval = intervalMinutes * MINUTES;
        final long jitter = (long)(INTERVAL_JITTER_FRAC * interval);
        interval += (long)(Math.random() * (2 * jitter)) - jitter;
        final JobInfo jobInfo =
                new JobInfo.Builder(JOB_ID, new ComponentName(context, NekoService.class))
                        .setPeriodic(interval, INTERVAL_FLEX).build();
        jobScheduler.schedule(jobInfo);
    }

    public static void cancelJob(Context context) {
        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        if (jobScheduler == null) {
            Log.w(TAG, "Null JobScheduler in cancelJob()");
            return;
        }
        jobScheduler.cancel(JOB_ID);
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.fasterxml.jackson.databind.jsonschema (jackson-databind 2.14.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.fasterxml.jackson.databind.jsonschema

Interfaces

SchemaAware

Classes

JsonSchema

Annotation Types

JsonSerializableSchema


text:
import sys
import os
from subprocess import Popen
from subprocess import PIPE

from cloudpickle import dumps
from pickle import loads

try:
    from suprocess import TimeoutExpired
    timeout_supported = True
except ImportError:
    # no support for timeout in Python 2
    class TimeoutExpired(Exception):
        pass
    timeout_supported = False

def subprocess_pickle_echo(input_data):
    """Echo function with a child Python process

    Pickle the input data into a buffer, send it to a subprocess via
    stdin, expect the subprocess to unpickle, re-pickle that data back
    and send it back to the parent process via stdout for final unpickling.

    >>> subprocess_pickle_echo([1, 'a', None])
    [1, 'a', None]

    """
    pickled_input_data = dumps(input_data)
    cmd = [sys.executable, __file__]
    cwd = os.getcwd()
    proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd)
    try:
        comm_kwargs = {}
        if timeout_supported:
            comm_kwargs['timeout'] = 5
        out, err = proc.communicate(pickled_input_data, **comm_kwargs)
        if proc.returncode != 0 or len(err):
            message = "Subprocess returned %d: " % proc.returncode
            message += err.decode('utf-8')
            raise RuntimeError(message)
        return loads(out)
    except TimeoutExpired:
        proc.kill()
        out, err = proc.communicate()
        message = u"\n".join([out.decode('utf-8'), err.decode('utf-8')])
        raise RuntimeError(message)

def pickle_echo(stream_in=None, stream_out=None):
    """Read a pickle from stdin and pickle it back to stdout"""
    if stream_in is None:
        stream_in = sys.stdin
    if stream_out is None:
        stream_out = sys.stdout

    # Force the use of bytes streams under Python 3
    if hasattr(stream_in, 'buffer'):
        stream_in = stream_in.buffer
    if hasattr(stream_out, 'buffer'):
        stream_out = stream_out.buffer

    input_bytes = stream_in.read()
    stream_in.close()
    unpickled_content = loads(input_bytes)
    stream_out.write(dumps(unpickled_content))
    stream_out.close()

if __name__ == '__main__':
    pickle_echo()