text:
use crate::{
    export::metrics::{
        self,
        aggregation::{Temporality, TemporalitySelector},
        Accumulation, AggregatorSelector, Checkpointer, CheckpointerFactory, LockedCheckpointer,
        LockedProcessor, Processor, Reader, Record,
    },
    metrics::{aggregators::Aggregator, sdk_api::Descriptor},
};
use core::fmt;
use fnv::FnvHasher;
use opentelemetry_api::{
    attributes::{hash_attributes, AttributeSet},
    metrics::{MetricsError, Result},
};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;

/// Create a new basic processor
pub fn factory<A, T>(aggregator_selector: A, temporality_selector: T) -> BasicProcessorBuilder
where
    A: AggregatorSelector + Send + Sync + 'static,
    T: TemporalitySelector + Send + Sync + 'static,
{
    BasicProcessorBuilder {
        aggregator_selector: Arc::new(aggregator_selector),
        temporality_selector: Arc::new(temporality_selector),
        memory: false,
    }
}

pub struct BasicProcessorBuilder {
    aggregator_selector: Arc<dyn AggregatorSelector + Send + Sync>,
    temporality_selector: Arc<dyn TemporalitySelector + Send + Sync>,
    memory: bool,
}

impl BasicProcessorBuilder {
    /// Memory controls whether the processor remembers metric instruments and
    /// attribute sets that were previously reported.
    ///
    /// When Memory is `true`, [`Reader::try_for_each`] will visit metrics that were
    /// not updated in the most recent interval.
    pub fn with_memory(mut self, memory: bool) -> Self {
        self.memory = memory;
        self
    }
}

impl fmt::Debug for BasicProcessorBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BasicProcessorBuilder")
            .field("memory", &self.memory)
            .finish()
    }
}

impl CheckpointerFactory for BasicProcessorBuilder {
    fn checkpointer(&self) -> Arc<dyn Checkpointer + Send + Sync> {
        Arc::new(BasicProcessor {
            aggregator_selector: Arc::clone(&self.aggregator_selector),
            temporality_selector: Arc::clone(&self.temporality_selector),
            state: Mutex::new(BasicProcessorState::with_memory(self.memory)),
        })
    }
}

/// Basic metric integration strategy
pub struct BasicProcessor {
    aggregator_selector: Arc<dyn AggregatorSelector + Send + Sync>,
    temporality_selector: Arc<dyn TemporalitySelector + Send + Sync>,
    state: Mutex<BasicProcessorState>,
}

impl Processor for BasicProcessor {
    fn aggregator_selector(&self) -> &dyn AggregatorSelector {
        self.aggregator_selector.as_ref()
    }
}

impl Checkpointer for BasicProcessor {
    fn checkpoint(
        &self,
        f: &mut dyn FnMut(&mut dyn LockedCheckpointer) -> Result<()>,
    ) -> Result<()> {
        self.state.lock().map_err(From::from).and_then(|locked| {
            f(&mut BasicLockedProcessor {
                parent: self,
                state: locked,
            })
        })
    }
}

impl fmt::Debug for BasicProcessor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BasicProcessor")
            .field("state", &self.state)
            .finish()
    }
}

/// A locked representation of the processor used where mutable references are necessary.
#[derive(Debug)]
struct BasicLockedProcessor<'a> {
    parent: &'a BasicProcessor,
    state: MutexGuard<'a, BasicProcessorState>,
}

impl<'a> LockedProcessor for BasicLockedProcessor<'a> {
    fn process(&mut self, accumulation: Accumulation<'_>) -> Result<()> {
        if self.state.started_collection != self.state.finished_collection.wrapping_add(1) {
            return Err(MetricsError::InconsistentState);
        }

        let desc = accumulation.descriptor();
        let mut hasher = FnvHasher::default();
        desc.attribute_hash().hash(&mut hasher);
        hash_attributes(&mut hasher, accumulation.attributes().into_iter());
        let key = StateKey(hasher.finish());
        let agg = accumulation.aggregator();
        let finished_collection = self.state.finished_collection;
        if let Some(value) = self.state.values.get_mut(&key) {
            // Advance the update sequence number.
            let same_collection = finished_collection == value.updated;
            value.updated = finished_collection;

            // At this point in the code, we have located an existing
            // value for some stateKey.  This can be because:
            //
            // (a) stateful aggregation is being used, the entry was
            // entered during a prior collection, and this is the first
            // time processing an accumulation for this stateKey in the
            // current collection.  Since this is the first time
            // processing an accumulation for this stateKey during this
            // collection, we don't know yet whether there are multiple
            // accumulators at work.  If there are multiple accumulators,
            // they'll hit case (b) the second time through.
            //
            // (b) multiple accumulators are being used, whether stateful
            // or not.
            //
            // Case (a) occurs when the instrument and the exporter
            // require memory to work correctly, either because the
            // instrument reports a PrecomputedSum to a DeltaExporter or
            // the reverse, a non-PrecomputedSum instrument with a
            // CumulativeExporter.  This logic is encapsulated in
            // ExportKind.MemoryRequired(MetricKind).
            //
            // Case (b) occurs when the variable `sameCollection` is true,
            // indicating that the stateKey for Accumulation has already
            // been seen in the same collection.  When this happens, it
            // implies that multiple Accumulators are being used, or that
            // a single Accumulator has been configured with an attribute key
            // filter.

            if !same_collection {
                if !value.current_owned {
                    // This is the first Accumulation we've seen for this
                    // stateKey during this collection.  Just keep a
                    // reference to the Accumulator's Aggregator. All the other cases
                    // copy Aggregator state.
                    value.current = agg.clone();
                    return Ok(());
                }
                return agg.synchronized_move(&value.current, desc);
            }

            // If the current is not owned, take ownership of a copy
            // before merging below.
            if !value.current_owned {
                let tmp = value.current.clone();
                if let Some(current) = self.parent.aggregator_selector.aggregator_for(desc) {
                    value.current = current;
                    value.current_owned = true;
                    tmp.synchronized_move(&value.current, desc)?;
                }
            }

            // Combine this `Accumulation` with the prior `Accumulation`.
            return value.current.merge(agg.as_ref(), desc);
        }

        let stateful = self
            .parent
            .temporality_selector
            .temporality_for(desc, agg.aggregation().kind())
            .memory_required(desc.instrument_kind());

        let cumulative = if stateful {
            if desc.instrument_kind().precomputed_sum() {
                // If we know we need to compute deltas, allocate one.
                return Err(MetricsError::Other("No cumulative to sum support".into()));
            }
            // Always allocate a cumulative aggregator if stateful
            self.parent.aggregator_selector.aggregator_for(desc)
        } else {
            None
        };

        self.state.values.insert(
            key,
            StateValue {
                descriptor: desc.clone(),
                attributes: accumulation.attributes().clone(),
                current_owned: false,
                current: agg.clone(),
                cumulative,
                stateful,
                updated: finished_collection,
            },
        );

        Ok(())
    }
}

impl LockedCheckpointer for BasicLockedProcessor<'_> {
    fn processor(&mut self) -> &mut dyn LockedProcessor {
        self
    }

    fn reader(&mut self) -> &mut dyn Reader {
        &mut *self.state
    }

    fn start_collection(&mut self) {
        if self.state.started_collection != 0 {
            self.state.interval_start = self.state.interval_end;
        }
        self.state.started_collection = self.state.started_collection.wrapping_add(1);
    }

    fn finish_collection(&mut self) -> Result<()> {
        self.state.interval_end = opentelemetry_api::time::now();
        if self.state.started_collection != self.state.finished_collection.wrapping_add(1) {
            return Err(MetricsError::InconsistentState);
        }
        let finished_collection = self.state.finished_collection;
        self.state.finished_collection = self.state.finished_collection.wrapping_add(1);
        let has_memory = self.state.config.memory;

        let mut result = Ok(());

        self.state.values.retain(|_key, value| {
            // Return early if previous error
            if result.is_err() {
                return true;
            }

            let mkind = value.descriptor.instrument_kind();

            let stale = value.updated != finished_collection;
            let stateless = !value.stateful;

            // The following branch updates stateful aggregators. Skip these updates
            // if the aggregator is not stateful or if the aggregator is stale.
            if stale || stateless {
                // If this processor does not require memory, stale, stateless
                // entries can be removed. This implies that they were not updated
                // over the previous full collection interval.
                if stale && stateless && !has_memory {
                    return false;
                }
                return true;
            }

            // The only kind of aggregators that are not stateless
            // are the ones needing delta to cumulative
            // conversion.  Merge aggregator state in this case.
            if !mkind.precomputed_sum() {
                // This line is equivalent to:
                // value.cumulative = value.cumulative + value.delta
                if let Some(cumulative) = value.cumulative.as_ref() {
                    result = cumulative.merge(value.current.as_ref(), &value.descriptor)
                }
            }

            true
        });

        result
    }
}

#[derive(Debug, Default)]
struct BasicProcessorConfig {
    /// Memory controls whether the processor remembers metric instruments and attribute
    /// sets that were previously reported. When Memory is true,
    /// `CheckpointSet::try_for_each` will visit metrics that were not updated in
    /// the most recent interval.
    memory: bool,
}

#[derive(Debug)]
struct BasicProcessorState {
    config: BasicProcessorConfig,
    values: HashMap<StateKey, StateValue>,
    // Note: the timestamp logic currently assumes all exports are deltas.
    process_start: SystemTime,
    interval_start: SystemTime,
    interval_end: SystemTime,
    started_collection: u64,
    finished_collection: u64,
}

impl BasicProcessorState {
    fn with_memory(memory: bool) -> Self {
        let mut state = BasicProcessorState::default();
        state.config.memory = memory;
        state
    }
}

impl Default for BasicProcessorState {
    fn default() -> Self {
        BasicProcessorState {
            config: BasicProcessorConfig::default(),
            values: HashMap::default(),
            process_start: opentelemetry_api::time::now(),
            interval_start: opentelemetry_api::time::now(),
            interval_end: opentelemetry_api::time::now(),
            started_collection: 0,
            finished_collection: 0,
        }
    }
}

impl Reader for BasicProcessorState {
    fn try_for_each(
        &mut self,
        temporality_selector: &dyn TemporalitySelector,
        f: &mut dyn FnMut(&Record<'_>) -> Result<()>,
    ) -> Result<()> {
        if self.started_collection != self.finished_collection {
            return Err(MetricsError::InconsistentState);
        }

        self.values.iter().try_for_each(|(_key, value)| {
            let instrument_kind = value.descriptor.instrument_kind();

            let agg;
            let start;

            // If the processor does not have memory and it was not updated in the
            // prior round, do not visit this value.
            if !self.config.memory && value.updated != self.finished_collection.wrapping_sub(1) {
                return Ok(());
            }

            match temporality_selector
                .temporality_for(&value.descriptor, value.current.aggregation().kind())
            {
                Temporality::Cumulative => {
                    // If stateful, the sum has been computed.  If stateless, the
                    // input was already cumulative. Either way, use the
                    // checkpointed value:
                    if value.stateful {
                        agg = value.cumulative.as_ref();
                    } else {
                        agg = Some(&value.current);
                    }

                    start = self.process_start;
                }
                Temporality::Delta => {
                    // Precomputed sums are a special case.
                    if instrument_kind.precomputed_sum() {
                        return Err(MetricsError::Other("No cumulative to delta".into()));
                    }

                    agg = Some(&value.current);
                    start = self.interval_start;
                }
            }

            let res = f(&metrics::record(
                &value.descriptor,
                &value.attributes,
                agg,
                start,
                self.interval_end,
            ));

            if let Err(MetricsError::NoDataCollected) = res {
                Ok(())
            } else {
                res
            }
        })
    }
}

#[derive(Debug, PartialEq, Eq, Hash)]
struct StateKey(u64);

#[derive(Debug)]
struct StateValue {
    /// Instrument descriptor
    descriptor: Descriptor,

    /// Instrument attributes
    attributes: AttributeSet,

    /// Indicates the last sequence number when this value had process called by an
    /// accumulator.
    updated: u64,

    /// Indicates that a cumulative aggregation is being maintained, taken from the
    /// process start time.
    stateful: bool,

    /// Indicates that "current" was allocated
    /// by the processor in order to merge results from
    /// multiple `Accumulator`s during a single collection
    /// round, which may happen either because:
    ///
    /// (1) multiple `Accumulator`s output the same `Accumulation.
    /// (2) one `Accumulator` is configured with dimensionality reduction.
    current_owned: bool,

    /// The output from a single `Accumulator` (if !current_owned) or an
    /// `Aggregator` owned by the processor used to accumulate multiple values in a
    /// single collection round.
    current: Arc<dyn Aggregator + Send + Sync>,

    /// If `Some`, refers to an `Aggregator` owned by the processor used to store
    /// the last cumulative value.
    cumulative: Option<Arc<dyn Aggregator + Send + Sync>>,
}


text:
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.BurstCodeAnalysis.Analyzers.ReferenceExpression
{
    [SolutionComponent]
    public class BurstVariableTypeAnalyzer : IBurstProblemSubAnalyzer<IReferenceExpression>
    {
        private static bool HasAllowingBurstAttribute(ITypeOwner typeOwner)
        {
            var allowingAttribute = KnownTypes.NativeSetClassTypeToNullOnScheduleAttribute;

            return typeOwner is IAttributesOwner attributesOwner &&
                   attributesOwner.HasAttributeInstance(allowingAttribute, AttributesSource.Self);
        }

        public BurstProblemSubAnalyzerStatus CheckAndAnalyze(IReferenceExpression referenceExpression,
            IHighlightingConsumer consumer)
        {
            var element = referenceExpression.Reference.Resolve().DeclaredElement;

            if (element is not ITypeOwner typeOwner)
                return BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE;

            if (HasAllowingBurstAttribute(typeOwner))
                return BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE;

            var type = typeOwner.Type();
            var innerType = (type as IArrayType)?.ElementType ?? type;

            if (BurstCodeAnalysisUtil.IsBurstPermittedType(innerType))
                return BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE;

            var typeElement = innerType?.GetTypeElement();
            var name = typeElement?.ShortName;

            if (!name.IsNullOrEmpty())
                consumer?.AddHighlighting(new BurstLoadingManagedTypeWarning(referenceExpression, name));

            return BurstProblemSubAnalyzerStatus.WARNING_PLACED_STOP;
        }

        public int Priority => 2000;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<bill session="110" type="sr" number="566" updated="2009-01-09T21:09:04-05:00">
	<status><vote date="1210737600" datetime="2008-05-14" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1210737600" datetime="2008-05-14"/>
	<titles>
		<title type="official" as="introduced">A resolution designating June 2008 as "National Aphasia Awareness Month" and supporting efforts to increase awareness of aphasia.</title>
	</titles>
	<sponsor id="300058"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<vote date="1210737600" how="by Unanimous Consent" datetime="2008-05-14" where="s" type="vote" result="pass" ><text>Submitted in the Senate, considered, and agreed to without amendment and with a preamble by Unanimous Consent.</text><reference label="consideration" ref="CR S4202"/><reference label="text as passed Senate" ref="CR S4202"/><reference label="text of measure as introduced" ref="CR S4186"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	5/14/2008--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.)<br/>Expresses support for the goals and ideals of National Aphasia Awareness Month in June 2008.
	</summary>
</bill>


text:
package org.apache.http.impl.client.cache;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.client.cache.HttpCacheEntry;

final class CacheMap extends LinkedHashMap<String, HttpCacheEntry> {

    private static final long serialVersionUID = -7750025207539768511L;

    private final int maxEntries;

    CacheMap(int maxEntries) {
        super(20, 0.75f, true);
        this.maxEntries = maxEntries;
    }

    @Override
    protected boolean removeEldestEntry(final Map.Entry<String, HttpCacheEntry> eldest) {
        return size() > this.maxEntries;
    }

}


text:
/*
 * Action.JS
 * ActionScript-like library for JavaScript development
 *
 * Sprite class
 *
 * Conventions:
 * lowercase package names, UpperCamelCase class names, ALLCAPS constants, _preUnderscored private members, lowerCamelCase public members
 *
 * Search '**' for to-do/issues
 *
 * Eric Schmidt 2013
 * eschmidt@mit.edu | eschmidt.co
 */

(function(window, action){

	// Sprite class - a display object which can have multiple states, each of which are basic display objects (Rectangle, Image, Animation, etc)
	action.Sprite = function(){
		var _this = this;
		this.displayed = false;
		this.x = 0;
		this.y = 0;
		this.width = 0;
		this.height = 0;
		this.center = {x: 0, y: 0};
		this.scaleX = 1;
		this.scaleY = 1;
		this.rotation = 0;
		var _states = {};
		var _currentState;
		this.addState = function(name, obj){
			_states[name] = obj;
		};
		this.removeState = function(name){
			delete _states[name];
		};
		this.showState = function(name){
			_currentState = _states[name];
			_this.width = _currentState.width;
			_this.height = _currentState.height;
		};

		this.draw = function(stage){
			_currentState.x = _this.x;
			_currentState.y = _this.y;
			_currentState.center = _this.center;
			_currentState.scaleX = _this.scaleX;
			_currentState.scaleY = _this.scaleY;
			_currentState.rotation = _this.rotation;
			_currentState.draw(stage);
		};
	};

})(window, action);


text:
> `npm install --save @types/dexie`

# Summary
This package contains type definitions for Dexie v1.3.1 (https://github.com/dfahlander/Dexie.js).

# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/dexie

Additional Details
 * Last updated: Mon, 19 Sep 2016 16:15:24 GMT
 * File structure: ProperModule
 * Library Dependencies: none
 * Module Dependencies: none
 * Global values: Dexie

# Credits
These definitions were written by David Fahlander <http://github.com/dfahlander>.


text:
require File.expand_path('../../lib/sc_hash', __FILE__)

require 'rspec'
require 'pry'


text:
package rst.pdfbox.layout.text.annotations;

import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;

import rst.pdfbox.layout.text.DrawContext;
import rst.pdfbox.layout.text.Position;

/**
 * Processes an annotation.
 */
public interface AnnotationProcessor {

    /**
     * Called if an annotated object has been drawn.
     *
     * @param drawnObject
     *            the drawn object.
     * @param drawContext
     *            the drawing context.
     * @param upperLeft
     *            the upper left position the object has been drawn to.
     * @param width
     *            the width of the drawn object.
     * @param height
     *            the height of the drawn object.
     * @throws IOException
     *             by pdfbox.
     */
    void annotatedObjectDrawn(final Annotated drawnObject,
	    final DrawContext drawContext, Position upperLeft, float width,
	    float height) throws IOException;

    /**
     * Called before a page is drawn.
     *
     * @param drawContext
     *            the drawing context.
     * @throws IOException
     *             by pdfbox.
     */
    void beforePage(final DrawContext drawContext) throws IOException;

    /**
     * Called after a page is drawn.
     *
     * @param drawContext
     *            the drawing context.
     * @throws IOException
     *             by pdfbox.
     */
    void afterPage(final DrawContext drawContext) throws IOException;

    /**
     * Called after all rendering has been performed.
     *
     * @param document
     *            the document.
     * @throws IOException
     *             by pdfbox.
     */
    void afterRender(final PDDocument document) throws IOException;

}


text:
<mat-card class="tabCard">
  <mat-card-title>

Expiration

  </mat-card-title>

    <form #expirationForm="ngForm">
      <app-expiration></app-expiration>
      <button type="submit" style="display: none;" #submit></button>
    </form>

</mat-card>


text:
#import <Foundation/Foundation.h>

#if __has_feature(objc_generics) || __has_extension(objc_generics)
#  define BF_GENERIC(type) <type>
#else
#  define BF_GENERIC(type)
#  define BFGenericType id
#endif


text:
#ifndef _PASSENGER_SERVER_KIT_FD_SINK_CHANNEL_H_
#define _PASSENGER_SERVER_KIT_FD_SINK_CHANNEL_H_

#include <oxt/macros.hpp>
#include <cerrno>
#include <unistd.h>
#include <ev.h>
#include <jsoncpp/json.h>
#include <ServerKit/Channel.h>

namespace Passenger {
namespace ServerKit {

using namespace oxt;

class FdSinkChannel: protected Channel {
private:
	ev_io watcher;

	static Result _onData(Channel *channel, const MemoryKit::mbuf &buffer, int errcode) {
		return static_cast<FdSinkChannel *>(channel)->onData(buffer, errcode);
	}

	Result onData(const MemoryKit::mbuf &buffer, int errcode) {
		if (buffer.size() > 0) {
			// Data
			ssize_t ret;

			do {
				ret = ::write(watcher.fd, buffer.start, buffer.size());
			} while (ret == -1 && errno == EINTR);
			if (ret == (ssize_t) buffer.size()) {
				return Result(ret, false);
			} else if (ret >= 0) {
				ev_io_start(ctx->libev->getLoop(), &watcher);
				stop();
				return Result(ret, false);
			} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
				ev_io_start(ctx->libev->getLoop(), &watcher);
				stop();
				return Result(0, false);
			} else {
				Channel::feedError(errno);
				return Result(0, false);
			}
		} else if (errcode == 0) {
			// EOF
			return Channel::Result(0, true);
		} else {
			// Error
			// We do nothing here. The caller is responsible for handling the error.
			return Channel::Result(0, false);
		}
	}

	static void _onWritable(EV_P_ ev_io *io, int revents) {
		FdSinkChannel *self = static_cast<FdSinkChannel *>(io->data);
		ev_io_stop(self->ctx->libev->getLoop(), &self->watcher);
		self->start();
	}

	void initialize() {
		dataCallback = _onData;
		watcher.active = false;
		watcher.fd = -1;
		watcher.data = this;
	}

public:
	FdSinkChannel() {
		initialize();
	}

	FdSinkChannel(Context *context)
		: Channel(context)
	{
		initialize();
	}

	~FdSinkChannel() {
		if (ctx != NULL && ev_is_active(&watcher)) {
			ev_io_stop(ctx->libev->getLoop(), &watcher);
		}
	}

	// May only be called right after construction.
	OXT_FORCE_INLINE
	void setContext(Context *context) {
		Channel::setContext(context);
	}

	void reinitialize(int fd) {
		Channel::reinitialize();
		ev_io_init(&watcher, _onWritable, fd, EV_WRITE);
	}

	void deinitialize() {
		if (ev_is_active(&watcher)) {
			ev_io_stop(ctx->libev->getLoop(), &watcher);
		}
		watcher.fd = -1;
		Channel::deinitialize();
	}

	OXT_FORCE_INLINE
	int feed(const MemoryKit::mbuf &mbuf) {
		return Channel::feed(mbuf);
	}

	OXT_FORCE_INLINE
	int feed(BOOST_RV_REF(MemoryKit::mbuf) mbuf) {
		return Channel::feed(mbuf);
	}

	OXT_FORCE_INLINE
	int feedWithoutRefGuard(const MemoryKit::mbuf &mbuf) {
		return Channel::feedWithoutRefGuard(mbuf);
	}

	OXT_FORCE_INLINE
	int feedWithoutRefGuard(BOOST_RV_REF(MemoryKit::mbuf) mbuf) {
		return Channel::feedWithoutRefGuard(mbuf);
	}

	OXT_FORCE_INLINE
	void feedError(int errcode) {
		return Channel::feedError(errcode);
	}

	OXT_FORCE_INLINE
	int getFd() const {
		return watcher.fd;
	}

	OXT_FORCE_INLINE
	bool acceptingInput() const {
		return Channel::acceptingInput();
	}

	OXT_FORCE_INLINE
	bool mayAcceptInputLater() const {
		return Channel::mayAcceptInputLater();
	}

	OXT_FORCE_INLINE
	bool hasError() const {
		return Channel::hasError();
	}

	OXT_FORCE_INLINE
	int getErrcode() const {
		return Channel::getErrcode();
	}

	OXT_FORCE_INLINE
	bool ended() const {
		return Channel::ended();
	}

	OXT_FORCE_INLINE
	bool endAcked() const {
		return Channel::endAcked();
	}

	OXT_FORCE_INLINE
	void setConsumedCallback(ConsumedCallback callback) {
		Channel::consumedCallback = callback;
	}

	OXT_FORCE_INLINE
	Hooks *getHooks() const {
		return hooks;
	}

	OXT_FORCE_INLINE
	void setHooks(Hooks *hooks) {
		this->hooks = hooks;
	}

	Json::Value inspectAsJson() const {
		Json::Value doc = Channel::inspectAsJson();
		doc["initialized"] = watcher.fd != -1;
		doc["io_watcher_active"] = (bool) watcher.active;
		return doc;
	}
};

} // namespace ServerKit
} // namespace Passenger

#endif /* _PASSENGER_SERVER_KIT_FD_SINK_CHANNEL_H_ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiAttributeRouting.Models;

namespace WebApiAttributeRouting.Controllers
{
    // This is optional: it is just to avoid repeating the first part of the URI
    // for each action method
    [RoutePrefix("api/users")]
    public class MyFancyController : ApiController
    {
        private User[] users = new[]
        {
            new User { Id = 1, Name = "Anders" }
        };

        // If we want the action method to be at precisely the RoutePrefix for the
        // controller, we must use an empty string as Route
        [Route("")]
        [HttpGet]  // <-- This method will only be called for HTTP GET requests
        public IEnumerable<User> FetchMyDamnUsers()
        {
            return users;
        }

        // If we need to extract parameters from request and send into the controller
        // action method, we must use curly brackets {} with name of method parameter inside
        [Route("{id}")]
        [HttpGet]
        public User FetchASpecificUser(int id)
        {
            return users.Where(u => u.Id == id).Single();
        }
    }
}


text:
.class final Landroid/os/Trace$1;
.super Ljava/lang/Object;
.source "Trace.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/os/Trace;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

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

    return-void
.end method

# virtual methods
.method public run()V
    .locals 0

    invoke-static {}, Landroid/os/Trace;->-wrap0()J

    return-void
.end method


text: Greetings <b><?php echo $username; ?></b>


text:
@implementation FileSendXMLMaker

+ (NSData*)XMLToSendData:(NSData*)data filepath:(NSString*)path remained:(int)remained already:(int)already {
	DNSLogMethod
	NSString *filename = [path lastPathComponent];
	NSString *string = [GTMBase64 stringByEncodingData:data];
	NSMutableString *xml = [NSMutableString string];
	[xml appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
	[xml appendString:@"<StoreSales>"];
	[xml appendFormat:@"<status>send</status>"];
	[xml appendFormat:@"<already>%d</already>", already];
	[xml appendFormat:@"<remained>%d</remained>", remained];
	[xml appendFormat:@"<data>%@</data>", string];
	[xml appendFormat:@"<filename>%@</filename>", filename];
	[xml appendFormat:@"<databytes>%d</databytes>", [data length]];
	[xml appendString:@"</StoreSales>"];
	return [xml dataUsingEncoding:NSUTF8StringEncoding];
}

+ (NSData*)XMLToSendRequestOK {
	DNSLogMethod
	NSMutableString *xml = [NSMutableString string];
	[xml appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
	[xml appendString:@"<StoreSales>"];
	[xml appendFormat:@"<status>requestOK</status>"];
	[xml appendString:@"</StoreSales>"];
	return [xml dataUsingEncoding:NSUTF8StringEncoding];
}

+ (NSData*)XMLToSendAuthorizationFailed {
	DNSLogMethod
	NSMutableString *xml = [NSMutableString string];
	[xml appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
	[xml appendString:@"<StoreSales>"];
	[xml appendFormat:@"<status>AuthorizationFailed</status>"];
	[xml appendString:@"</StoreSales>"];
	return [xml dataUsingEncoding:NSUTF8StringEncoding];
}

+ (NSData*)XMLToSendTaskFinished {
	DNSLogMethod
	NSMutableString *xml = [NSMutableString string];
	[xml appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
	[xml appendString:@"<StoreSales>"];
	[xml appendFormat:@"<status>TaskFinished</status>"];
	[xml appendString:@"</StoreSales>"];
	return [xml dataUsingEncoding:NSUTF8StringEncoding];
}

@end


text:
package org.apache.felix.eventadmin.impl.handler;

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

import org.apache.felix.eventadmin.impl.security.PermissionsUtil;
import org.apache.felix.eventadmin.impl.util.LogWrapper;
import org.osgi.framework.Bundle;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

/**
 * This is a proxy for event handlers. It gets the real event handler
 * on demand and prepares some information for faster processing.
 *
 * It checks the timeout handling for the implementation as well as
 * putting the handler on the deny list.
 *
 * @author Felix Project Team
 */
public class EventHandlerProxy {

    /** The service reference for the event handler. */
    private final ServiceReference<EventHandler> reference;

    /** The handler context. */
    private final EventHandlerTracker.HandlerContext handlerContext;

    /** The event topics. */
    private volatile String[] topics;

    /** Optional filter. */
    private volatile Filter filter;

    /** Lazy fetched event handler. */
    private volatile EventHandler handler;

    /** Is this handler denied? */
    private final AtomicBoolean denied = new AtomicBoolean();

    /** Use timeout. */
    private boolean useTimeout;

    /** Deliver async ordered. */
    private boolean asyncOrderedDelivery;

    /**
     * Create an EventHandlerProxy.
     *
     * @param context The handler context
     * @param reference Reference to the EventHandler
     */
    public EventHandlerProxy(final EventHandlerTracker.HandlerContext context,
                    final ServiceReference<EventHandler> reference)
    {
        this.handlerContext = context;
        this.reference = reference;
    }

    /**
     * Update the state with current properties from the service
     * @return true if the handler configuration is valid.
     */
    public boolean update()
    {
        this.denied.set(false);
        boolean valid = true;
        // First check, topic
        final Object topicObj = reference.getProperty(EventConstants.EVENT_TOPIC);
        if (topicObj instanceof String)
        {
            if ( topicObj.toString().equals("*") )
            {
                this.topics = null;
            }
            else
            {
                this.topics = new String[] {topicObj.toString()};
            }
        }
        else if (topicObj instanceof String[])
        {
            // check if one value matches '*'
            final String[] values = (String[])topicObj;
            boolean matchAll = false;
            for(int i=0;i<values.length;i++)
            {
                if ( "*".equals(values[i]) )
                {
                    matchAll = true;
                }
            }
            if ( matchAll )
            {
                this.topics = null;
            }
            else
            {
                this.topics = values;
            }
        }
        else if (topicObj instanceof Collection)
        {
            @SuppressWarnings("unchecked")
            final Collection<Object> col = (Collection<Object>)topicObj;
            final String[] values = new String[col.size()];
            int index = 0;
            // check if one value matches '*'
            final Iterator<Object> i = col.iterator();
            boolean matchAll = false;
            while ( i.hasNext() )
            {
                final String v = i.next().toString();
                values[index] = v;
                index++;
                if ( "*".equals(v) )
                {
                    matchAll = true;
                }
            }
            if ( matchAll )
            {
                this.topics = null;
            }
            else
            {
                this.topics = values;
            }
        }
        else if ( topicObj == null && !this.handlerContext.requireTopic )
        {
            this.topics = null;
        }
        else
        {
            final String reason;
            if ( topicObj == null )
            {
                reason = "Missing";
            }
            else
            {
                reason = "Neither of type String nor String[] : " + topicObj.getClass().getName();
            }
            LogWrapper.getLogger().log(
                            this.reference,
                            LogWrapper.LOG_WARNING,
                            "Invalid EVENT_TOPICS : " + reason + " - Ignoring ServiceReference ["
                                            + this.reference + " | Bundle("
                                            + this.reference.getBundle() + ")]");
            this.topics = null;
            valid = false;
        }
        // Second check filter (but only if topics is valid)
        Filter handlerFilter = null;
        if ( valid )
        {
            final Object filterObj = reference.getProperty(EventConstants.EVENT_FILTER);
            if (filterObj instanceof String)
            {
                try
                {
                    handlerFilter = this.handlerContext.bundleContext.createFilter(filterObj.toString());
                }
                catch (final InvalidSyntaxException e)
                {
                    valid = false;
                    LogWrapper.getLogger().log(
                                    this.reference,
                                    LogWrapper.LOG_WARNING,
                                    "Invalid EVENT_FILTER - Ignoring ServiceReference ["
                                                    + this.reference + " | Bundle("
                                                    + this.reference.getBundle() + ")]", e);
                }
            }
            else if ( filterObj != null )
            {
                valid = false;
                LogWrapper.getLogger().log(
                                this.reference,
                                LogWrapper.LOG_WARNING,
                                "Invalid EVENT_FILTER - Ignoring ServiceReference ["
                                                + this.reference + " | Bundle("
                                                + this.reference.getBundle() + ")]");
            }
        }
        this.filter = handlerFilter;

        // new in 1.3 - deliver
        this.asyncOrderedDelivery = true;
        Object delivery = reference.getProperty(EventConstants.EVENT_DELIVERY);
        if ( delivery instanceof Collection )
        {
            @SuppressWarnings("unchecked")
            final Collection<String> col = (Collection<String>)delivery;
            delivery = col.toArray(new String[col.size()]);
        }
        if ( delivery instanceof String )
        {
            this.asyncOrderedDelivery =  !(EventConstants.DELIVERY_ASYNC_UNORDERED.equals(delivery.toString()));
        }
        else if ( delivery instanceof String[] )
        {
            final String[] deliveryArray = (String[])delivery;
            boolean foundOrdered = false, foundUnordered = false;
            for(int i=0; i<deliveryArray.length; i++)
            {
                final String value = deliveryArray[i];
                if ( EventConstants.DELIVERY_ASYNC_UNORDERED.equals(value) )
                {
                    foundUnordered = true;
                }
                else if ( EventConstants.DELIVERY_ASYNC_ORDERED.equals(value) )
                {
                    foundOrdered = true;
                }
                else
                {
                    LogWrapper.getLogger().log(
                                    this.reference,
                                    LogWrapper.LOG_WARNING,
                                    "Invalid EVENT_DELIVERY - Ignoring invalid value for event delivery property " + value + " of ServiceReference ["
                                                    + this.reference + " | Bundle("
                                                    + this.reference.getBundle() + ")]");

                }
            }
            if ( !foundOrdered && foundUnordered )
            {
                this.asyncOrderedDelivery = false;
            }
        }
        else if ( delivery != null )
        {
            LogWrapper.getLogger().log(
                            this.reference,
                            LogWrapper.LOG_WARNING,
                            "Invalid EVENT_DELIVERY - Ignoring event delivery property " + delivery + " of ServiceReference ["
                                            + this.reference + " | Bundle("
                                            + this.reference.getBundle() + ")]");
        }
        // make sure to release the handler
        this.release();

        return valid;
    }

    /**
     * Get some info about the event handler
     * @return Handler info
     */
    public String getInfo() {
        return this.reference.toString() + " [Bundle " + this.reference.getBundle() + "]";
    }

    /**
     * Dispose the proxy and release the handler
     */
    public void dispose()
    {
        this.release();
    }

    /**
     * Get the event handler.
     * @return The event handler or {@code null}
     */
    private synchronized EventHandler obtain() {
        if (this.handler == null)
        {
            try
            {
                this.handler = this.handlerContext.bundleContext.getService(this.reference);
                if ( this.handler != null )
                {
                    this.checkTimeout(this.handler.getClass().getName());
                }
            }
            catch (final IllegalStateException ignore)
            {
                // event handler might be stopped - ignore
            }
        }
        return this.handler;
    }

    /**
     * Release the handler
     */
    private synchronized void release()
    {
        if ( this.handler != null )
        {
            try
            {
                this.handlerContext.bundleContext.ungetService(this.reference);
            }
            catch (final IllegalStateException ignore)
            {
                // event handler might be stopped - ignore
            }
            this.handler = null;
        }
    }

    /**
     * Get the topics of this handler.
     * If this handler matches all topics {@code null} is returned
     * @return The topics of this handler or {@code null}
     */
    public String[] getTopics()
    {
        return this.topics;
    }

    /**
     * Check if this handler is allowed to receive the event
     * - denied
     * - check filter
     * - check permission
     * @param event The event
     * @return {@code true} if the event can be delivered
     */
    public boolean canDeliver(final Event event)
    {
        if ( this.denied.get() )
        {
            return false;
        }
        final Bundle bundle = reference.getBundle();
        // is service unregistered?
        if (bundle == null)
        {
            return false;
        }

        // filter match
        final Filter eventFilter = this.filter;
        if ( eventFilter != null && !event.matches(eventFilter) )
        {
            return false;
        }

        // permission check
        final Object p = PermissionsUtil.createSubscribePermission(event.getTopic());
        if (p != null && !bundle.hasPermission(p) )
        {
            return false;
        }

        return true;
    }

    /**
     * Should a timeout be used for this handler?
     * @return {@code true} if a timeout should be used
     */
    public boolean useTimeout()
    {
        return this.useTimeout;
    }

    /**
     * Should async events be delivered in order?
     * @return {@code true} if async events should be delivered in order
     */
    public boolean isAsyncOrderedDelivery()
    {
        return this.asyncOrderedDelivery;
    }

    /**
     * Check the timeout configuration for this handler.
     * @param className Handler name
     */
    private void checkTimeout(final String className)
    {
        if ( this.handlerContext.ignoreTimeoutMatcher != null )
        {
            for(int i=0;i<this.handlerContext.ignoreTimeoutMatcher.length;i++)
            {
                if ( this.handlerContext.ignoreTimeoutMatcher[i] != null)
                {
                    if ( this.handlerContext.ignoreTimeoutMatcher[i].match(className) )
                    {
                        this.useTimeout = false;
                        return;
                    }
                }
            }
        }
        this.useTimeout = true;
    }

    /**
     * Send the event.
     * @param event The event
     */
    public void sendEvent(final Event event)
    {
        final EventHandler handlerService = this.obtain();
        if (handlerService == null)
        {
            return;
        }

        try
        {
            handlerService.handleEvent(event);
        }
        catch (final Throwable e)
        {
            // The spec says that we must catch exceptions and log them:
            LogWrapper.getLogger().log(
                            this.reference,
                            LogWrapper.LOG_ERROR,
                            String.format("Exception during event dispatch [%s | %s | Bundle(%s) | Handler(%s)]",
                                event, this.reference, this.reference.getBundle(), handlerService), e);
        }
    }

    /**
     * Deny the handler.
     */
    public void denyEventHandler()
    {
        if ( this.denied.compareAndSet(false, true) ) {
            final EventHandler handlerService = this.handler;
            LogWrapper.getLogger().log(
                    LogWrapper.LOG_ERROR,
                    String.format("Denying event handler from ServiceReference [%s | Bundle(%s)%s] due to timeout!",
                        this.reference,
                        this.reference.getBundle(),
                        handlerService == null ? "" : " | Handler(".concat(handlerService.getClass().getName()).concat(")")));

            this.release();
    	}
    }

    public boolean isDenied()
    {
        return this.denied.get();
    }
}


text:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

namespace Aspose.Plugins.AsposeVSOpenXML
{
    class Program
    {
        private static string FilePath = @"..\..\..\..\Sample Files\";
        private static string fileName = FilePath + "OpenDocumentFromStream.docx";

        static void Main(string[] args)
        {
            string txt = "Append text in body - OpenAndAddToWordprocessingStream";
            Stream stream = File.Open(fileName, FileMode.Open);
            OpenAndAddToWordprocessingStream(stream, txt);
            stream.Close();
        }

        private static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
        {
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(stream, true);
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
            Paragraph para = body.AppendChild(new Paragraph());
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text(txt));
            wordprocessingDocument.Close();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:iceVaccineSpecificationFile xmlns:ns2="org.cdsframework.util.support.data.ice.vaccine">
    <vaccine code="07" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="mumps"/>
    <vaccineGroup code="500" codeSystem="2.16.840.1.113883.3.795.12.100.1" codeSystemName="ICE Vaccine Group" displayName="MMR"/>
    <cdsVersion>org.nyc.cir^ICE^1.0.0</cdsVersion>
    <ns2:liveVirusVaccine>true</ns2:liveVirusVaccine>
    <ns2:vaccineActive>true</ns2:vaccineActive>
    <ns2:manufacturerCode/>
    <vaccineComponent code="07" codeSystem="2.16.840.1.113883.12.292" codeSystemName="CVX" displayName="mumps"/>
    <diseaseImmunity code="MUMPS" codeSystem="2.16.840.1.113883.3.795.12.100.20" codeSystemName="ICE Disease" displayName="Mumps"/>
    <openCdsMembership code="ICE07" displayName="Mumps"/>
    <primaryOpenCdsConcept code="ICE07" displayName="Mumps"/>
</ns2:iceVaccineSpecificationFile>


text:
namespace FDMC.Controllers
{
    using System.Linq;
    using System.Text;
    using Attributes;
    using Microsoft.EntityFrameworkCore;
    using Models;
    using Models.BindingModels;
    using Models.ViewModels;
    using SimpleMvc.Framework.Attributes.Methods;
    using SimpleMvc.Framework.Interfaces;

    public class KittenController : HomeController
    {
        [HttpGet]
        [AuthorizeLogin]
        public IActionResult Add() => this.View();

        [HttpPost]
        [AuthorizeLogin]
        public IActionResult Add(KittenAddBindingModel model)
        {
            if (!this.IsValidModel(model))
            {
                return this.BuildErrorView();
            }

            using (this.Context)
            {
                var breed = this.Context
                    .Breeds
                    .FirstOrDefault(b => b.Name == model.Breed);

                if (breed == null)
                {
                    this.Model.Data["error"] = "Invalid breed";
                    return this.View();
                }

                var kitten = new Kitten
                {
                    Name = model.Name,
                    Age = model.Age,
                    Breed = breed
                };

                this.Context.Kittens.Add(kitten);
                this.Context.SaveChanges();

                return this.RedirectToAction("/kittens/all");
            }
        }

        [HttpGet]
        [AuthorizeLogin]
        public IActionResult All()
        {
            var kittens = this.Context
                .Kittens
                .Include(k => k.Breed)
                .Select(KittenAllViewModel.FromKitten)
                .Select(vm =>
                    $@"

Name: {vm.Name}

Age: {vm.Age}

Breed: {vm.Breed}

")
                .ToList();

            var sb = new StringBuilder();
            sb.Append(@"
");

            for (var i = 0; i < kittens.Count; i++)
            {
                sb.Append(kittens[i]);

                if (i % 3 == 2)
                {
                    sb.Append(@"

");
                }
            }

            sb.Append("
");

            this.Model.Data["kittens"] = sb.ToString();
            return this.View();
        }
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProcessUtils.h"

#include "nsString.h"

#include <sys/prctl.h>

namespace mozilla {
namespace ipc {

void SetThisProcessName(const char *aName)
{
  prctl(PR_SET_NAME, (unsigned long)aName, 0uL, 0uL, 0uL);
}

} // namespace ipc
} // namespace mozilla


text:
@if (! $resource->enrolled)
    @include("Course::cards.request-course")
@endif


text:
package org.killbill.billing.catalog;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

import org.killbill.billing.catalog.api.PriceListSet;
import org.killbill.xmlloader.ValidationError;
import org.killbill.xmlloader.ValidationErrors;

@XmlAccessorType(XmlAccessType.NONE)
public class PriceListDefault extends DefaultPriceList {

    public PriceListDefault() {
    }

    public PriceListDefault(final DefaultPlan[] defaultPlans) {
        super(defaultPlans, PriceListSet.DEFAULT_PRICELIST_NAME);
    }

    @Override
    public ValidationErrors validate(final StandaloneCatalog catalog, final ValidationErrors errors) {
        super.validate(catalog, errors);
        if (!getName().equals(PriceListSet.DEFAULT_PRICELIST_NAME)) {
            errors.add(new ValidationError("The name of the default pricelist must be 'DEFAULT'",
                                           catalog.getCatalogURI(), DefaultPriceList.class, getName()));

        }
        return errors;
    }

    @Override
    public String getName() {
        return PriceListSet.DEFAULT_PRICELIST_NAME;
    }

}


text:
package com.kk.taurus.avplayer.ui;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kk.taurus.avplayer.R;
import com.kk.taurus.avplayer.bean.VideoBean;
import com.kk.taurus.avplayer.play.DataInter;
import com.kk.taurus.avplayer.play.ReceiverGroupManager;
import com.kk.taurus.avplayer.play.ShareAnimationPlayer;
import com.kk.taurus.avplayer.utils.ImageDisplayEngine;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ShareAnimationActivityA extends AppCompatActivity {

    @BindView(R.id.albumImage)
    ImageView mAlbumImage;
    @BindView(R.id.playIcon)
    ImageView playIcon;
    @BindView(R.id.album_layout)
    RelativeLayout mAlbumLayout;
    @BindView(R.id.layoutContainer)
    FrameLayout mLayoutContainer;
    @BindView(R.id.tv_title)
    TextView mTvTitle;

    private Unbinder unbinder;

    private DataSource mData;

    private boolean toNext;
    private ReceiverGroup mReceiverGroup;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_animation_a);
        unbinder = ButterKnife.bind(this);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        VideoBean mVideoBean = new VideoBean(
                "不想从被子里出来",
                "http://open-image.nosdn.127.net/57baaaeaad4e4fda8bdaceafdb9d45c2.jpg",
                "https://mov.bn.netease.com/open-movie/nos/mp4/2018/01/12/SD70VQJ74_sd.mp4");

        mData = new DataSource(mVideoBean.getPath());
        mData.setTitle(mVideoBean.getDisplayName());

        ImageDisplayEngine.display(this, mAlbumImage, mVideoBean.getCover(), R.mipmap.ic_launcher);
        mTvTitle.setText(mVideoBean.getDisplayName());

        mReceiverGroup = ReceiverGroupManager.get().getReceiverGroup(this);

    }

    @OnClick({R.id.album_layout, R.id.tv_title})
    public void onViewClicked(View view) {
        ShareAnimationPlayer.get().setReceiverGroup(mReceiverGroup);
        switch (view.getId()) {
            case R.id.album_layout:
                playIcon.setVisibility(View.GONE);
                ShareAnimationPlayer.get().play(mLayoutContainer, mData);
                break;
            case R.id.tv_title:
                toNext = true;
                Intent intent = new Intent(this, ShareAnimationActivityB.class);
                intent.putExtra(ShareAnimationActivityB.KEY_DATA, mData);
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
                    ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                            this, mLayoutContainer, "videoShare");
                    ActivityCompat.startActivity(this, intent, options.toBundle());
                }else{
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        playIcon.setVisibility(View.VISIBLE);

        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_TOP_ENABLE, false);
        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_SCREEN_SWITCH_ENABLE, false);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(!toNext){
            ShareAnimationPlayer.get().pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ShareAnimationPlayer.get().destroy();

        unbinder.unbind();
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Sql.Models
{
    public partial class ExportRequest : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("storageKeyType");
            writer.WriteStringValue(StorageKeyType.ToSerialString());
            writer.WritePropertyName("storageKey");
            writer.WriteStringValue(StorageKey);
            writer.WritePropertyName("storageUri");
            writer.WriteStringValue(StorageUri);
            writer.WritePropertyName("administratorLogin");
            writer.WriteStringValue(AdministratorLogin);
            writer.WritePropertyName("administratorLoginPassword");
            writer.WriteStringValue(AdministratorLoginPassword);
            if (Optional.IsDefined(AuthenticationType))
            {
                writer.WritePropertyName("authenticationType");
                writer.WriteStringValue(AuthenticationType.Value.ToSerialString());
            }
            writer.WriteEndObject();
        }
    }
}


text:
namespace WorkflowCore.Interface
{
    public interface IGreyList
    {
        void Add(string id);
        void Remove(string id);
        bool Contains(string id);
    }
}


text:
<?php

require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Util/Filter.php';
require_once 'PHPUnit/Runner/StandardTestSuiteLoader.php';

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

/**
 * Base class for all test runners.
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2008 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: 3.2.9
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 2.0.0
 * @abstract
 */
abstract class PHPUnit_Runner_BaseTestRunner implements PHPUnit_Framework_TestListener
{
    const STATUS_PASSED     = 0;
    const STATUS_SKIPPED    = 1;
    const STATUS_INCOMPLETE = 2;
    const STATUS_FAILURE    = 3;
    const STATUS_ERROR      = 4;
    const SUITE_METHODNAME  = 'suite';

    /**
     * An error occurred.
     *
     * @param  PHPUnit_Framework_Test $test
     * @param  Exception              $e
     * @param  float                  $time
     * @access public
     */
    public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        $this->testFailed(self::STATUS_ERROR, $test, $e);
    }

    /**
     * A failure occurred.
     *
     * @param  PHPUnit_Framework_Test                 $test
     * @param  PHPUnit_Framework_AssertionFailedError $e
     * @param  float                                  $time
     * @access public
     */
    public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
    {
        $this->testFailed(self::STATUS_FAILURE, $test, $e);
    }

    /**
     * Incomplete test.
     *
     * @param  PHPUnit_Framework_Test $test
     * @param  Exception              $e
     * @param  float                  $time
     * @access public
     */
    public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        $this->testFailed(self::STATUS_INCOMPLETE, $test, $e);
    }

    /**
     * Skipped test.
     *
     * @param  PHPUnit_Framework_Test $test
     * @param  Exception              $e
     * @param  float                  $time
     * @access public
     * @since  Method available since Release 3.0.0
     */
    public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
    {
        $this->testFailed(self::STATUS_SKIPPED, $test, $e);
    }

    /**
     * A testsuite started.
     *
     * @param  PHPUnit_Framework_TestSuite $suite
     * @access public
     * @since  Method available since Release 2.2.0
     */
    public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
    }

    /**
     * A testsuite ended.
     *
     * @param  PHPUnit_Framework_TestSuite $suite
     * @access public
     * @since  Method available since Release 2.2.0
     */
    public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
    }

    /**
     * A test started.
     *
     * @param  PHPUnit_Framework_Test  $test
     * @access public
     */
    public function startTest(PHPUnit_Framework_Test $test)
    {
        $this->testStarted($test->getName());
    }

    /**
     * A test ended.
     *
     * @param  PHPUnit_Framework_Test $test
     * @param  float                  $time
     * @access public
     */
    public function endTest(PHPUnit_Framework_Test $test, $time)
    {
        $this->testEnded($test->getName());
    }

    /**
     * Returns the loader to be used.
     *
     * @return PHPUnit_Runner_TestSuiteLoader
     * @access public
     */
    public function getLoader()
    {
        return new PHPUnit_Runner_StandardTestSuiteLoader;
    }

    /**
     * Returns the Test corresponding to the given suite.
     * This is a template method, subclasses override
     * the runFailed() and clearStatus() methods.
     *
     * @param  string  $suiteClassName
     * @param  string  $suiteClassFile
     * @param  boolean $syntaxCheck
     * @return PHPUnit_Framework_Test
     * @access public
     */
    public function getTest($suiteClassName, $suiteClassFile = '', $syntaxCheck = TRUE)
    {
        try {
            $testClass = $this->loadSuiteClass(
              $suiteClassName, $suiteClassFile, $syntaxCheck
            );
        }

        catch (Exception $e) {
            $this->runFailed($e->getMessage());
            return NULL;
        }

        try {
            $suiteMethod = $testClass->getMethod(self::SUITE_METHODNAME);

            if (!$suiteMethod->isStatic()) {
                $this->runFailed(
                  'suite() method must be static.'
                );

                return NULL;
            }

            try {
                $test = $suiteMethod->invoke(NULL, $testClass->getName());
            }

            catch (ReflectionException $e) {
                $this->runFailed(
                  sprintf(
                    "Failed to invoke suite() method.\n%s",

                    $e->getMessage()
                  )
                );

                return NULL;
            }
        }

        catch (ReflectionException $e) {
            $test = new PHPUnit_Framework_TestSuite($testClass);
        }

        $this->clearStatus();

        return $test;
    }

    /**
     * Override to define how to handle a failed loading of
     * a test suite.
     *
     * @param  string  $message
     * @access protected
     * @abstract
     */
    abstract protected function runFailed($message);

    /**
     * Returns the loaded ReflectionClass for a suite name.
     *
     * @param  string  $suiteClassName
     * @param  string  $suiteClassFile
     * @param  boolean $syntaxCheck
     * @return ReflectionClass
     * @access protected
     */
    protected function loadSuiteClass($suiteClassName, $suiteClassFile = '', $syntaxCheck = TRUE)
    {
        $loader = $this->getLoader();

        if ($loader instanceof PHPUnit_Runner_StandardTestSuiteLoader) {
            return $loader->load($suiteClassName, $suiteClassFile, $syntaxCheck);
        } else {
            return $loader->load($suiteClassName, $suiteClassFile);
        }
    }

    /**
     * Clears the status message.
     *
     * @access protected
     */
    protected function clearStatus()
    {
    }

    /**
     * A test started.
     *
     * @param  string  $testName
     * @access public
     * @abstract
     */
    abstract public function testStarted($testName);

    /**
     * A test ended.
     *
     * @param  string  $testName
     * @access public
     * @abstract
     */
    abstract public function testEnded($testName);

    /**
     * A test failed.
     *
     * @param  integer                                 $status
     * @param  PHPUnit_Framework_Test                 $test
     * @param  PHPUnit_Framework_AssertionFailedError $e
     * @access public
     * @abstract
     */
    abstract public function testFailed($status, PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e);
}
?>


text:
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'reversion_extras'))
from version import __version__

try:
    from setuptools import setup, Command
except ImportError:
    from distutils.core import setup, Command

version = '.'.join(str(x) for x in __version__)

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    os.system('python setup.py bdist_wheel upload')
    sys.exit()

if sys.argv[-1] == 'tag':
    os.system("git tag -a %s -m 'version %s'" % (version, version))
    os.system("git push --tags")
    sys.exit()

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

requirements = [
    'django-reversion',
]

test_requirements = [
    'pytest',
    'pytest-django',
    'tox'
]

# Add Python 2.7-specific dependencies
if sys.version < '3':
    requirements.append('mock')

# There are no Python 3-specific dependencies to add

long_description = readme + '\n\n' + history

if sys.argv[-1] == 'readme':
    print(long_description)
    sys.exit()

class PyTest(Command):
    user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]

    def initialize_options(self):
        self.pytest_args = []

    def finalize_options(self):
        pass

    def run(self):
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

setup(
    name='django-reversion-extras',
    version=version,
    description=("""Extra tools to work with django-reversion"""
                 ),
    long_description=long_description,
    author='Fabio C. Barrionuevo da Luz',
    author_email='bnafta@gmail.com',
    url='https://github.com/luzfcb/django-reversion-extras',
    packages=[
        'reversion_extras',
    ],
    package_dir={'reversion_extras': 'reversion_extras'},
    include_package_data=True,
    install_requires=requirements,
    license='BSD',
    zip_safe=False,
    classifiers=[
        'Development Status :: 1 - Planning',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development',

    ],
    keywords=(
        'django-reversion-extras, reversion, reversion-extras, '
        'django-reversion'
    ),
    cmdclass={'test': PyTest},
    test_suite='tests',
    tests_require=test_requirements
)


text:
CREATE TABLE pbAaDistN (
  x float default NULL,
  y float default NULL
) TYPE=MyISAM;


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->

    </style>

    <style name="LocalsgramActionBarTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/LocalsgramActionBar</item>
        <item name="android:popupMenuStyle">@style/PopupMenu.Actionbar_localsgram</item>
        <item name="android:actionDropDownStyle">@style/PopupMenu.Actionbar_localsgram</item>
        <item name="android:fitsSystemWindows">true</item>
        <item name="android:clipToPadding">true</item>
        <item name="android:fontFamily">sans-serif-thin</item>
    </style>

    <style name="LocalsgramActionBar" parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/theme_light_color</item>
        <item name="android:titleTextStyle">@style/Localsgram.ActionBar.TitleTextStyle</item>
        <item name="android:displayOptions">showTitle</item>
        <item name="displayOptions">showTitle</item>
        <item name="android:icon">@android:color/transparent</item> <!-- This does the magic! -->
    </style>

    <!--<style name="LocalsgramPopMenu" parent="android:Widget.Holo.Light.ListPopupWindow">-->
        <!--<item name="android:popupBackground">@drawable/option_menu_background</item>-->
    <!--</style>-->

    <style name="PopupMenu.Actionbar_localsgram" parent="android:Widget.Holo.Light.PopupMenu">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_actionbar_localsgram</item>
    </style>

    <style name="Localsgram.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_title_color</item>
    </style>

</resources>


text:
<?php

namespace Oro\Bundle\CalendarBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class DateEarlierThan extends Constraint
{
    public $field;
    public $message = "This date should be earlier than {{ field }} date";

    /**
     * {@inheritdoc}
     */
    public function getDefaultOption()
    {
        return 'field';
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredOptions()
    {
        return array('field');
    }
}


text:
include $(NACL_SDK_ROOT)/tools/common.mk

TARGET = agg-demo
LIBS = agg ppapi_simple nacl_io ppapi ppapi_cpp
SOURCES = drawing.cc
INSTALL_DIR = $(NACL_PACKAGES_PUBLISH)/$(TARGET)/$(TOOLCHAIN)

ifeq ($(TOOLCHAIN),pnacl)
EXEEXT=.pexe
else
EXEEXT=.nexe
endif

ifneq ($(TOOLCHAIN),pnacl)
# We want the nmf to contain all the .nexe we have previously
# built as well as the one currently being built, so we modify
# the list of executables that we pass to create_nmf.
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_x86_64$(EXEEXT))
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_x86_32$(EXEEXT))
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_arm$(EXEEXT))
endif

# Build rules generated by macros from common.mk:

$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))

ifeq ($(CONFIG),Release)
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES),$(LIBS),$(DEPS)))
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif

$(eval $(call NMF_RULE,$(TARGET),))

install:
	mkdir -p $(INSTALL_DIR)
	cp $(OUTDIR)/$(TARGET)*$(EXEEXT) $(INSTALL_DIR)
	rm -f $(INSTALL_DIR)/*_unstripped*$(EXEEXT)
	cp $(OUTDIR)/$(TARGET).nmf $(INSTALL_DIR)
	cp index.html $(INSTALL_DIR)
ifeq ($(TOOLCHAIN),pnacl)
	sed -i.bak 's/x-nacl/x-pnacl/g' $(INSTALL_DIR)/index.html
endif


text:
---
layout: page
title: Endpoint provisioning and registration
permalink: /:path/
sort_idx: 10
---

* TOC
{:toc}

{% include variables.md %}

To function within the [Kaa platform]({{root_url}}Glossary/#kaa-platform), every [endpoint]({{root_url}}Glossary/#endpoint-ep) must be uniquely identified and provisioned with credentials.
This section discusses the process of endpoint authentication and the functionality of the Kaa Credentials service.

## Endpoint authentication

In the default implementation, Kaa platform uses hybrid encryption system that is based on RSA with 2048-bit key pair and AES with 256(512)-bit key.
During the start of a new session, every endpoint sends an encrypted and digitally signed session key.
Session key is a randomly generated AES key that is also encrypted with public key of the Kaa node that handles this session or request.
The digital signature of a session key is based on the private key of the endpoint.
To authenticate an endpoint and validate its request, Kaa node validates the digital signature of the session key.

Although other authentication strategies are possible, they are out of scope of this section.

## Endpoint registration

To function within a [Kaa cluster]({{root_url}}Glossary/#kaa-cluster), every endpoint must be registered using the security credentials and the endpoint profile.
During the registration process, the endpoint first communicates with one or multiple [Bootstrap services]({{root_url}}Glossary/#bootstrap-service) to obtain a list of available [Operations services]({{root_url}}Glossary/#operations-service).
Then it communicates with the Operations service to submit the endpoint data (credentials ID and the endpoint profile) and complete the registration.

The endpoint registration process is illustrated in the picture below.

![Endpoint Registration](attach/registration.png)

### List of Operations services

For security and load-balancing reasons, Kaa endpoint SDKs do not include any information about Operations services.
Instead, a [Control service]({{root_url}}Glossary/#control-service) embeds a list of available Bootstrap services into the SDK during the SDK generation process.
This list is saved as a properties file in case with Java SDK, and as a header file in case with other [SDK types]({{root_url}}Glossary/#kaa-sdk-type).
The endpoint selects a random Bootstrap service from the list and sends a resolution request to the selected Bootstrap service.
The resolution request contains the [application token]({{root_url}}Glossary/#application-token) that can be used by the Bootstrap service in specific load-balancing strategies.
The resolution response from the Bootstrap service contains a prioritized list of Operations services with their connectivity details and is signed with the Bootstrap service private key.
The endpoint verifies the signature of the response using the Bootstrap public key available from the build time parameters and saves the received information.

### Endpoint authorization

Endpoint authorization is done by validating the endpoint credentials using the corresponding Credentials service.
Credentials service can be configured for each Kaa application individually.
To do this, you can use the [Administration UI]({{root_url}}Glossary/#administration-ui) or the corresponding [server REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Application/editApplication).

![credential](attach/credentials-for-apps.png)

The endpoint credentials ID is generated based on the public RSA key hash of the endpoint.
When a new session starts, the Operations service queries the Credentials service for credentials status.
If the credentials are not valid or in use by other endpoint, Kaa node will reject the session.

### Endpoint registration data

Prior to the actual endpoint registration, Kaa platform user can use the endpoint credentials data to provision server-side profiles for new endpoints.
This server-side profile will be used during endpoint registration.
This can be useful when, for example, an endpoint manufacturer wants to provision sensitive information to the server-side endpoint profile based on the security keys that are only available during manufacturing process.
For more information, see [Administration REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Device_management/provisionCredentials).

## Credentials service

Kaa provides two Credentials service implementations out of the box:

- Trustful credentials service: default implementation that allows any endpoint to register and connect to Kaa cluster.
This service will accept credentials from any endpoint.

- Internal credentials service: allows connection to Kaa cluster only to specified list of endpoints whose credentials were previously provisioned to Kaa server.
For more information, see [Administration REST API]({{root_url}}Programming-guide/Server-REST-APIs/#!/Device_management/provisionCredentials).

### Custom implementation of Credentials service

Here is an example of a custom implementation of Credentials service:

Create a class that implements all methods of [CredentialsService interface]({{github_url}}server/node/src/main/java/org/kaaproject/kaa/server/node/service/credentials/CredentialsService.java).

```java

package org.myproject;

@Service
public class CustomCredentialsService implements CredentialsService {

	/**
	 * Provide credentials information to the external system.
	 */
	@Override
	public CredentialsDto provideCredentials(String applicationId, CredentialsDto credentials) throws CredentialsServiceException {
		// implementation
	}

	/**
	 * Returns the credentials by ID.
	 */
	@Override
	public Optional<CredentialsDto> lookupCredentials(String applicationId, String credentialsId) throws CredentialsServiceException {
		// implementation
	}

	/**
	 * Sets the status of the given credentials to CredentialsStatus.IN_USE
	 */
	@Override
	public void markCredentialsInUse(String applicationId, String credentialsId) throws CredentialsServiceException {
		// implementation
	}

	/**
	 * Revokes the given credentials by setting their status to CredentialsStatus.REVOKED
	 */
	@Override
	public void markCredentialsRevoked(String applicationId, String credentialsId) throws CredentialsServiceException {
		// implementation
	}
}

```

Register `CredentialsServiceLocator` in the `/usr/lib/kaa-node/conf/kaaNodeContext.xml` file for your new credential service.

```xml

<bean id="customCredentialsServiceLocator" class="org.kaaproject.kaa.server.node.service.credentials.InternalCredentialsServiceLocator">
    <constructor-arg ref="org.myproject.customCredentialsService"/>
</bean>

<util:map id="credentialsServiceLocatorMap">
    <entry key="Trustful" value-ref="trustfulCredentialsServiceLocator"/>
    <entry key="Internal" value-ref="internalCredentialsServiceLocator"/>
    <entry key="NEW" value-ref="customCredentialsServiceLocator"/>
</util:map>

```

The key value you added will be displayed in the **Administration UI**.

![credential](attach/credential.png)

Edit the `/usr/lib/kaa-node/conf/common-dao-context.xml` file.

```xml

<bean id="customCredentialsService" class="org.myproject.CustomCredentialsService"/>

```

### Provisioning of custom Credentials service

To provision your Credentials service:

1. Build your application:

   ```bash
      $ mvn clean install
   ```

2. Move the `.jar` file of your application from the `target` folder to the `/usr/lib/kaa-node/lib` folder.

3. If you use other package than `org.kaaproject.kaa.*`, make it scan the `kaa-node.properties` file in the `/usr/lib/kaa-node/conf` folder.
For example: `additional_plugins_scan_package=org.myproject`

4. Restart the `kaa-node` service:

   ```bash
      $ sudo service kaa-node restart
   ```


text:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');
const { sequelize } = require('./models');
const config = require('./config/config');

const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

require('./passport');

require('./routes')(app);

/* eslint-disable no-console */
sequelize.sync().then(() => {
  app.listen(config.port);
  console.log(`Server started on port ${config.port}`);
});


text:
import nltk
# nltk.download_shell()

import pandas as pd
import string
from nltk.corpus import stopwords  # words like: the, me, our
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
# https://www.analyticsvidhya.com/blog/2015/09/naive-bayes-explained/
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
# http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split

# linux:
# read and load data
'''
messages = [line.rstrip() for line in open(
    'smsspamcollection/SMSSpamCollection')]
messages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\t',
                       names=["label", "message"])
'''
# windows:
# read and load data
messgaes = [line.rstrip() for line in open(
    'D:/Github_python_ML/MachineLearning/NaturalLanguageProcessing/smsspamcollection/SMSSpamCollection'
)]
messages = pd.read_csv('D:/Github_python_ML/MachineLearning/NaturalLanguageProcessing/smsspamcollection/SMSSpamCollection', sep='\t',
                       names=["label", "message"])

# add feature of message len
messages['length'] = messages['message'].apply(len)

def text_process(mess):
    """
    Takes in a string of text, then performs the following:
    1. Remove all punctuation
    2. Remove all stopwords
    3. Returns a list of the cleaned text
    """
    # Check characters to see if they are in punctuation
    nopunc = [char for char in mess if char not in string.punctuation]

    # Join the characters again to form the string.
    nopunc = ''.join(nopunc)

    # Now just remove any stopwords
    return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]

# train test split
msg_train, msg_test, label_train, label_test = \
    train_test_split(messages['message'], messages['label'], test_size=0.2)

# making a pipline for all functions
pipeline = Pipeline([
    # strings to token integer counts
    ('bow', CountVectorizer(analyzer=text_process)),
    ('tfidf', TfidfTransformer()),  # integer counts to weighted TF-IDF scores
    # train on TF-IDF vectors w/ Naive Bayes classifier
    ('classifier', MultinomialNB()),
])

# fit the pipline
pipeline.fit(msg_train, label_train)

# predict with pipline
predictions = pipeline.predict(msg_test)
print(classification_report(predictions, label_test))


text:
using System.ComponentModel;

namespace Calabonga.Configuration.Core.Wpf3_1
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion INotifyPropertyChanged
    }
}


text:
FOUNDATION_EXPORT double VCNetEntitiesVersionNumber;
FOUNDATION_EXPORT const unsigned char VCNetEntitiesVersionString[];


text:
package de.lessvoid.nifty.renderer.lwjgl.render;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Cursor;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

import de.lessvoid.nifty.render.BlendMode;
import de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData;
import de.lessvoid.nifty.renderer.lwjgl.render.io.ImageIOImageData;
import de.lessvoid.nifty.renderer.lwjgl.render.io.TGAImageData;
import de.lessvoid.nifty.spi.render.MouseCursor;
import de.lessvoid.nifty.spi.render.RenderDevice;
import de.lessvoid.nifty.spi.render.RenderFont;
import de.lessvoid.nifty.spi.render.RenderImage;
import de.lessvoid.nifty.tools.Color;
import de.lessvoid.nifty.tools.resourceloader.NiftyResourceLoader;

/**
 * Lwjgl RenderDevice Implementation.
 * @author void
 */
public class LwjglRenderDevice implements RenderDevice {
  private static Logger log = Logger.getLogger(LwjglRenderDevice.class.getName());
  private static IntBuffer viewportBuffer = BufferUtils.createIntBuffer(4 * 4);
  private NiftyResourceLoader resourceLoader;
  private int viewportWidth = -1;
  private int viewportHeight = -1;
  private long time;
  private long frames;
  private long lastFrames;
  private boolean displayFPS = false;
  private boolean logFPS = false;
  private RenderFont fpsFont;

  // we keep track of which GL states we've already set to make sure we don't set
  // the same state twice.
  private boolean currentTexturing = true;
  private BlendMode currentBlendMode = null;
  private boolean currentClipping = false;
  private int currentClippingX0 = 0;
  private int currentClippingY0 = 0;
  private int currentClippingX1 = 0;
  private int currentClippingY1 = 0;

  private StringBuilder buffer = new StringBuilder();
  private int quadCount;
  private int glyphCount;

  /**
   * The standard constructor. You'll use this in production code. Using this
   * constructor will configure the RenderDevice to not log FPS on System.out.
   */
  public LwjglRenderDevice() {
    time = System.currentTimeMillis();
    frames = 0;
  }

  /**
   * The development mode constructor allows to display the FPS on screen when
   * the given flag is set to true. Note that setting displayFPS to false will
   * still log the FPS on System.out every couple of frames.
   * @param displayFPS
   */
  public LwjglRenderDevice(final boolean displayFPS) {
    this();
    this.logFPS = true;
    this.displayFPS = displayFPS;
  }

  @Override
  public void setResourceLoader(final NiftyResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;

    if (this.displayFPS) {
      fpsFont = createFont("fps.fnt");
    }
  }

  /**
   * Get Width.
   * @return width of display mode
   */
  public int getWidth() {
    if (viewportWidth == -1) {
      getViewport();
    }
    return viewportWidth;
  }

  /**
   * Get Height.
   * @return height of display mode
   */
  public int getHeight() {
    if (viewportHeight == -1) {
      getViewport();
    }
    return viewportHeight;
  }

  private void getViewport() {
    GL11.glGetInteger(GL11.GL_VIEWPORT, viewportBuffer);
    viewportWidth = viewportBuffer.get(2);
    viewportHeight = viewportBuffer.get(3);
    if (log.isLoggable(Level.FINE)) {
      log.fine("Viewport: " + viewportWidth + ", " + viewportHeight);
    }
  }

  public void beginFrame() {
    log.fine("beginFrame()");

    // set inital states for each frame
    GL11.glEnable(GL11.GL_BLEND);
    GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
    setBlendMode(BlendMode.BLEND);

    GL11.glEnable(GL11.GL_TEXTURE_2D);
    currentTexturing = true;

    GL11.glDisable(GL11.GL_SCISSOR_TEST);
    currentClipping = false;
    currentClippingX0 = 0;
    currentClippingY0 = 0;
    currentClippingX1 = 0;
    currentClippingY1 = 0;
    quadCount = 0;
    glyphCount = 0;
  }

  public void endFrame() {
    log.fine("endFrame");
    frames++;
    long diff = System.currentTimeMillis() - time;
    if (diff >= 1000) {
      time += diff;
      lastFrames = frames;

      buffer.setLength(0);
      buffer.append("FPS: ");
      buffer.append(lastFrames);
      buffer.append(" (");
      buffer.append(String.format("%f", 1000.f / lastFrames));
      buffer.append(" ms)");
      buffer.append(", Total Tri: ");
      buffer.append(quadCount*2);
      buffer.append(" (Text: ");
      buffer.append(glyphCount*2);
      buffer.append(")");
      buffer.append(", Total Vert: ");
      buffer.append(quadCount*4);
      buffer.append(" (Text: ");
      buffer.append(glyphCount*4);
      buffer.append(")");

      if (logFPS) {
        System.out.println(buffer.toString());
      }
      frames = 0;
    }
    if (displayFPS) {
      renderFont(fpsFont, buffer.toString(), 10, getHeight() - fpsFont.getHeight() - 10, Color.WHITE, 1.0f, 1.0f);
    }

    // currently the RenderDevice interface does not support a way to be notified when the resolution is changed
    // so we reset the viewportWidth and viewportHeight here so that we only call getViewport() once per frame and
    // not each time someone calls getWidth() or getHeight().
    viewportWidth = -1;
    viewportHeight = -1;

    checkGLError();
  }

  public void clear() {
    log.fine("clear()");

    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
  }

  /**
   * Create a new RenderImage.
   * @param filename filename
   * @param filterLinear linear filter the image
   * @return RenderImage
   */
  public RenderImage createImage(final String filename, final boolean filterLinear) {
    return new LwjglRenderImage(filename, filterLinear, resourceLoader);
  }

  /**
   * Create a new RenderFont.
   * @param filename filename
   * @return RenderFont
   */
  public RenderFont createFont(final String filename) {
    return new LwjglRenderFont(filename, this, resourceLoader);
  }

  /**
   * Render a quad.
   * @param x x
   * @param y y
   * @param width width
   * @param height height
   * @param color color
   */
  public void renderQuad(final int x, final int y, final int width, final int height, final Color color) {
    log.fine("renderQuad()");

    if (currentTexturing) {
      GL11.glDisable(GL11.GL_TEXTURE_2D);
      currentTexturing = false;
    }

    GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
    GL11.glBegin(GL11.GL_QUADS);
      GL11.glVertex2i(x,         y);
      GL11.glVertex2i(x + width, y);
      GL11.glVertex2i(x + width, y + height);
      GL11.glVertex2i(x,         y + height);
    GL11.glEnd();
    quadCount++;
  }

  public void renderQuad(final int x, final int y, final int width, final int height, final Color topLeft, final Color topRight, final Color bottomRight, final Color bottomLeft) {
    log.fine("renderQuad2()");

    if (currentTexturing) {
      GL11.glDisable(GL11.GL_TEXTURE_2D);
      currentTexturing = false;
    }
    GL11.glBegin(GL11.GL_QUADS);
      GL11.glColor4f(topLeft.getRed(), topLeft.getGreen(), topLeft.getBlue(), topLeft.getAlpha());
      GL11.glVertex2i(x,         y);
      GL11.glColor4f(topRight.getRed(), topRight.getGreen(), topRight.getBlue(), topRight.getAlpha());
      GL11.glVertex2i(x + width, y);
      GL11.glColor4f(bottomRight.getRed(), bottomRight.getGreen(), bottomRight.getBlue(), bottomRight.getAlpha());
      GL11.glVertex2i(x + width, y + height);
      GL11.glColor4f(bottomLeft.getRed(), bottomLeft.getGreen(), bottomLeft.getBlue(), bottomLeft.getAlpha());
      GL11.glVertex2i(x,         y + height);
    GL11.glEnd();
    quadCount++;
  }

  /**
   * Render the image using the given Box to specify the render attributes.
   * @param x x
   * @param y y
   * @param width width
   * @param height height
   * @param color color
   * @param scale scale
   */
  public void renderImage(final RenderImage image, final int x, final int y, final int width, final int height, final Color color, final float scale) {
    log.fine("renderImage()");

    if (width < 0) {
      log.warning("Attempt to render image with negative width");
      return;
    }
    if (height < 0) {
      log.warning("Attempt to render image with negative height");
      return;
    }

    if (!currentTexturing) {
      GL11.glEnable(GL11.GL_TEXTURE_2D);
      currentTexturing = true;
    }
    GL11.glPushMatrix();
    GL11.glTranslatef(x + width / 2, y + height / 2, 0.0f);
    GL11.glScalef(scale, scale, 1.0f);
    GL11.glTranslatef(-(x + width / 2), -(y + height / 2), 0.0f);

    LwjglRenderImage internalImage = (LwjglRenderImage) image;
    internalImage.bind();

    float textureWidth = (float)internalImage.getTextureWidth();
    float textureHeight = (float)internalImage.getTextureHeight();
    float imageWidth = (float)internalImage.getWidth();
    float imageHeight = (float)internalImage.getHeight();

    float u1 = imageWidth / textureWidth;
    float v1 = imageHeight / textureHeight;

    GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
    GL11.glBegin(GL11.GL_QUADS);
      GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex2i(x,         y);
      GL11.glTexCoord2f(  u1, 0.0f); GL11.glVertex2i(x + width, y);
      GL11.glTexCoord2f(  u1,   v1); GL11.glVertex2i(x + width, y + height);
      GL11.glTexCoord2f(0.0f,   v1); GL11.glVertex2i(x,         y + height);
    GL11.glEnd();
    GL11.glPopMatrix();
    quadCount++;
  }

  /**
   * Render sub image.
   * @param x x
   * @param y y
   * @param w w
   * @param h h
   * @param srcX x
   * @param srcY y
   * @param srcW w
   * @param srcH h
   * @param color color
   */
  public void renderImage(
      final RenderImage image,
      final int x,
      final int y,
      final int w,
      final int h,
      final int srcX,
      final int srcY,
      final int srcW,
      final int srcH,
      final Color color,
      final float scale,
      final int centerX,
      final int centerY) {
    log.fine("renderImage2()");

    if (w < 0) {
      log.warning("Attempt to render image with negative width");
      return;
    }
    if (h < 0) {
      log.warning("Attempt to render image with negative height");
      return;
    }

    if (!currentTexturing) {
      GL11.glEnable(GL11.GL_TEXTURE_2D);
      currentTexturing = true;
    }
    GL11.glPushMatrix();
    GL11.glTranslatef(centerX, centerY, 0.0f);
    GL11.glScalef(scale, scale, 1.0f);
    GL11.glTranslatef(-(centerX), -(centerY), 0.0f);

    LwjglRenderImage internalImage = (LwjglRenderImage) image;
    internalImage.bind();

    float textureWidth = (float)internalImage.getTextureWidth();
    float textureHeight = (float)internalImage.getTextureHeight();

    float u0 = srcX / textureWidth;
    float v0 = srcY / textureHeight;
    float u1 = (srcX + srcW) / textureWidth;
    float v1 = (srcY + srcH) / textureHeight;

    GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
    GL11.glBegin(GL11.GL_QUADS);
      GL11.glTexCoord2f(u0, v0); GL11.glVertex2i(x,     y);
      GL11.glTexCoord2f(u1, v0); GL11.glVertex2i(x + w, y);
      GL11.glTexCoord2f(u1, v1); GL11.glVertex2i(x + w, y + h);
      GL11.glTexCoord2f(u0, v1); GL11.glVertex2i(x,     y + h);
    GL11.glEnd();

    GL11.glPopMatrix();
    quadCount++;
  }

  /**
   * render the text.
   * @param text text
   * @param x x
   * @param y y
   * @param color color
   * @param fontSize size
   */
  public void renderFont(final RenderFont font, final String text, final int x, final int y, final Color color, final float fontSizeX, final float fontSizeY) {
    log.fine("renderFont()");

    if (!currentTexturing) {
      GL11.glEnable(GL11.GL_TEXTURE_2D);
      currentTexturing = true;
    }
    setBlendMode(BlendMode.BLEND);
    int count = 0;
    if (color == null) {
      count = ((LwjglRenderFont)font).getFont().drawStringWithSize(x, y, text, fontSizeX, fontSizeY);
    } else {
      count = ((LwjglRenderFont)font).getFont().renderWithSizeAndColor(x, y, text, fontSizeX, fontSizeY, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
    }
    glyphCount += count;
    quadCount += count;
  }

  private void checkGLError() {
    int error= GL11.glGetError();
    if (error != GL11.GL_NO_ERROR) {
      String glerrmsg = GLU.gluErrorString(error);
      log.warning("Error: (" + error + ") " + glerrmsg);
      try {
        throw new Exception();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * Enable clipping to the given region.
   * @param x0 x0
   * @param y0 y0
   * @param x1 x1
   * @param y1 y1
   */
  public void enableClip(final int x0, final int y0, final int x1, final int y1) {
    log.fine("enableClip()");

    if (currentClipping && currentClippingX0 == x0 && currentClippingY0 == y0 && currentClippingX1 == x1 && currentClippingY1 == y1) {
      return;
    }
    currentClipping = true;
    currentClippingX0 = x0;
    currentClippingY0 = y0;
    currentClippingX1 = x1;
    currentClippingY1 = y1;

    GL11.glScissor(x0, getHeight() - y1, x1 - x0, y1 - y0);
    GL11.glEnable(GL11.GL_SCISSOR_TEST);
  }

  /**
   * Disable Clip.
   */
  public void disableClip() {
    log.fine("disableClip()");

    if (!currentClipping) {
      return;
    }
    GL11.glDisable(GL11.GL_SCISSOR_TEST);
    currentClipping = false;
    currentClippingX0 = 0;
    currentClippingY0 = 0;
    currentClippingX1 = 0;
    currentClippingY1 = 0;
  }

  public void setBlendMode(final BlendMode renderMode) {
    log.fine("setBlendMode()");

    if (renderMode.equals(currentBlendMode)) {
      return;
    }
    currentBlendMode = renderMode;
    if (currentBlendMode.equals(BlendMode.BLEND)) {
      GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
    } else if (currentBlendMode.equals(BlendMode.MULIPLY)) {
      GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO);
    }
  }

  public MouseCursor createMouseCursor(final String filename, final int hotspotX, final int hotspotY) throws IOException {
    return new LwjglMouseCursor(loadMouseCursor(filename, hotspotX, hotspotY));
  }

  public void enableMouseCursor(final MouseCursor mouseCursor) {
    Cursor nativeCursor = null;
    if (mouseCursor != null) {
      nativeCursor = ((LwjglMouseCursor) mouseCursor).getCursor();
    }
    try {
      Mouse.setNativeCursor(nativeCursor);
    } catch (LWJGLException e) {
      log.warning(e.getMessage());
    }
  }

  public void disableMouseCursor() {
    try {
      Mouse.setNativeCursor(null);
    } catch (LWJGLException e) {
      log.warning(e.getMessage());
    }
  }

  private Cursor loadMouseCursor(final String name, final int hotspotX, final int hotspotY) throws IOException {
    ImageData imageLoader = createImageLoader(name);
    InputStream source = null;
    try {
      source = resourceLoader.getResourceAsStream(name);
      ByteBuffer imageData = imageLoader.loadMouseCursorImage(source);
      imageData.rewind();
      int width = imageLoader.getWidth();
      int height = imageLoader.getHeight();
      return new Cursor(width, height, hotspotX, height - hotspotY - 1, 1, imageData.asIntBuffer(), null);
    } catch (LWJGLException e) {
      throw new IOException(e);
    } finally {
      if (source != null) {
        source.close();
      }
    }
  }

  private ImageData createImageLoader(final String name) {
    if (name.endsWith(".tga")) {
      return new TGAImageData();
    }
    return new ImageIOImageData();
  }
}