text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;

using Microsoft.Research.DataStructures;
using Microsoft.Research.Graphs;

namespace Microsoft.Research.CodeAnalysis
{
    using Tag = System.String;
    using SubroutineContext = FList<STuple<CFGBlock, CFGBlock, string>>;
    using System.Diagnostics.Contracts;

    ///
    /// Used to pass a handler to emit warnings
    ///
    public delegate void ErrorHandler(string format, params string[] args);

    ///
    /// Represents a filter that determines what handlers apply to a given context.
    ///
    /// <typeparam name="Label">Underlying program point representation</typeparam>
    /// <typeparam name="Data">Client data type for auxiliary client information</typeparam>
    /// <typeparam name="Type">Type for exception filter</typeparam>
    public interface IHandlerFilter<Type, Data>
    {
        /// Given handler is a catch handler with given exception filter.
        /// <param name="data">Client specific data that helps client determine match</param>
        /// <param name="exception">Catch type</param>
        /// <param name="stopPropagation">Client should set this to true if no outer enclosing handlers are possible</param>
        /// <returns>true if handler applies, false, if handler does not apply</returns>
        bool Catch(Data data, Type exception, out bool stopPropagation);

        /// Given handler is a filter handler with filter code.
        /// <param name="data">Client specific data that helps client determine match</param>
        /// <param name="filterCode">Code determining applicability of filter</param>
        /// <param name="stopPropagation">Client should set this to true if no outer enclosing handlers are possible</param>
        /// <returns>true if handler applies, false, if handler does not apply</returns>
        bool Filter(Data data, APC filterCode, out bool stopPropagation);
    }
    ///
    /// An abstract view of a control flow graph, generic over underlying code.
    ///
    public partial interface ICFG
    {
        ///
        /// The entry point of the method
        ///
        APC Entry { get; }

        ///
        /// The entry point of the method after all requires contracts
        ///
        APC EntryAfterRequires { get; }

        ///
        /// The normal exit point of the method
        ///
        APC NormalExit { get; }

        ///
        /// The exceptional exit point of the method
        ///
        APC ExceptionExit { get; }

        ///
        /// If the label has a single successor, then this returns the unique post pc.
        /// Otherwise the result is equal to label.
        ///
        APC Post(APC label);

        ///
        /// Returns the immediate normal successor program point if there is a single one.
        /// Otherwise, must use Successors which returns all (or 0).
        ///
        [Pure]
        bool HasSingleSuccessor(APC ppoint, out APC singleSuccessor);

        ///
        /// Provides the immediate normal successor program points of the given ppoint
        ///
        [Pure]
        IEnumerable<APC> Successors(APC ppoint);

        ///
        /// Returns the immediate normal predecessor program point if there is a single one.
        /// Otherwise, must use Predecessor which returns all (or 0).
        ///
        [Pure]
        bool HasSinglePredecessor(APC ppoint, out APC singlePredecessor, bool skipContracts = false);

        ///
        /// Provides the immediate normal predecessor program points of the given ppoint
        ///
        [Pure]
        IEnumerable<APC> Predecessors(APC ppoint, bool skipContracts = false);

        ///
        /// If ppoint is the beginning of a call instruction, then this provides the first PC prior to
        /// ppoint and prior to any requires of the call
        ///
        [Pure]
        APC PredecessorPCPriorToRequires(APC ppoint);

        ///
        /// Returns true if the given program point is the target of multiple forward control
        /// transfers.
        ///
        [Pure]
        bool IsJoinPoint(APC ppoint);

        ///
        /// Returns true if the given program point is the target of multiple backward control
        /// transfers.
        ///
        [Pure]
        bool IsSplitPoint(APC ppoint);

        ///
        /// Returns true if the given program point is a back edge target in a forward traversal
        ///
        [Pure]
        bool IsForwardBackEdgeTarget(APC ppoint);

        ///
        /// Returns true if the given program point is a back edge target in a backward traversal
        ///
        [Pure]
        bool IsBackwardBackEdgeTarget(APC ppoint);

        ///
        /// Returns true if the edge described by the two program points is a back edge in a forward
        /// traversal of the CFG.
        /// NOTE: the edge must be an edge related by the Successors relation above, not
        /// an arbitrary pair.
        ///
        [Pure]
        bool IsForwardBackEdge(APC from, APC to);

        ///
        /// Returns true if the edge described by the two program points is a back edge in a backward
        /// traversal of the CFG.
        /// NOTE: the edge must be an edge related by the Predecessor relation above, not
        /// an arbitrary pair.
        ///
        [Pure]
        bool IsBackwardBackEdge(APC from, APC to);

        ///
        /// Returns the APC corresponding to loop heads.
        ///
        IEnumerable<CFGBlock> LoopHeads { get; }

        ///
        /// Returns true if the program point is the first point in a logical block
        ///
        [Pure]
        bool IsBlockStart(APC ppoint);

        ///
        /// Returns true if the program point is the last point in a logical block
        ///
        [Pure]
        bool IsBlockEnd(APC ppoint);

        ///
        /// Returns a set of program points that are possible execution continuations if
        /// an exception is raised at the given ppoint.
        ///
        /// The supplied predicate allows the client to determine which handlers are possible
        /// candidates. The predicate is called from closest enclosing to outermost.
        ///
        /// <param name="data">Arbitrary client data passed to the handler predicate</param>
        /// <returns>A set of continuation program points that represent how execution continues to a chosen handler.
        /// The continuation includes Finally and Fault executions that intervene between the given ppoint and a
        /// chosen handler.
        /// </returns>
        [Pure]
        IEnumerable<APC> ExceptionHandlers<Type, Data>(APC ppoint, Data data, IHandlerFilter<Type, Data> handlerPredicate);

        ///
        /// Returns a graph wrapper for the cfg that can be used with standard graph algorithms.
        /// There's only one APC used per block (the first in the block), and the set of nodes is not
        /// explicitly given.
        ///
        [Pure]
        IGraph<APC, Unit> AsForwardGraph(bool includeExceptionEdges);

        ///
        /// Returns a graph wrapper for the cfg that can be used with standard graph algorithms.
        /// There's only one APC used per block (the first in the block), and the set of nodes is not
        /// explicitly given.
        ///
        [Pure]
        IGraph<APC, Unit> AsBackwardGraph(bool includeExceptionEdges, bool skipContracts);

        [Pure]
        IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit>
          GetDecoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder);

        ///
        /// Get a subroutine view of the CFG for block level operations
        ///
        Subroutine Subroutine { get; }

        ///
        /// Get the subroutines on the edge from ---> to
        ///
        FList<Pair<string, Subroutine>> GetOrdinaryEdgeSubroutines(CFGBlock from, CFGBlock to, SubroutineContext context);

        ///
        /// Returns a textual representation of an abstract PC
        ///
        [Pure]
        string ToString(APC pc);

        ///
        /// Prints out a textual representation of the CFG
        ///
        /// Also decodes the synthetic IL from the CFG generation
        /// eg. Assumes
        ///
        /// <param name="tw">Target for output</param>
        /// <param name="edgePrinter">Optional info printer for successor edges</param>
        void Print(TextWriter tw, ILPrinter<APC> ilPrinter, BlockInfoPrinter<APC>/*?*/ edgePrinter, Func<CFGBlock, IEnumerable<SubroutineContext>> contextLookup, SubroutineContext context);
    }

    #region ICFG contract binding
    [ContractClass(typeof(ICFGContract))]
    public partial interface ICFG
    {
    }

    [ContractClassFor(typeof(ICFG))]
    internal abstract class ICFGContract : ICFG
    {
        #region ICFG Members

        public APC Entry
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public APC EntryAfterRequires
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public APC NormalExit
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public APC ExceptionExit
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public APC Post(APC label)
        {
            throw new NotImplementedException();
        }

        public bool HasSingleSuccessor(APC ppoint, out APC singleSuccessor)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<APC> Successors(APC ppoint)
        {
            Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null);
            throw new NotImplementedException();
        }

        public bool HasSinglePredecessor(APC ppoint, out APC singlePredecessor, bool skipContracts)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<APC> Predecessors(APC ppoint, bool skipContracts)
        {
            Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null);
            throw new NotImplementedException();
        }

        public APC PredecessorPCPriorToRequires(APC ppoint)
        {
            Contract.Requires(ppoint.Index == 0);

            throw new NotImplementedException();
        }

        public bool IsJoinPoint(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public bool IsSplitPoint(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public bool IsForwardBackEdgeTarget(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public bool IsBackwardBackEdgeTarget(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public bool IsForwardBackEdge(APC from, APC to)
        {
            throw new NotImplementedException();
        }

        public bool IsBackwardBackEdge(APC from, APC to)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<CFGBlock> LoopHeads
        {
            get
            {
                Contract.Ensures(Contract.Result<IEnumerable<CFGBlock>>() != null);
                throw new NotImplementedException();
            }
        }

        public bool IsBlockStart(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public bool IsBlockEnd(APC ppoint)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<APC> ExceptionHandlers<Type, Data>(APC ppoint, Data data, IHandlerFilter<Type, Data> handlerPredicate)
        {
            Contract.Ensures(Contract.Result<IEnumerable<APC>>() != null);
            throw new NotImplementedException();
        }

        public IGraph<APC, Unit> AsForwardGraph(bool includeExceptionEdges)
        {
            Contract.Ensures(Contract.Result<IGraph<APC, Unit>>() != null);
            throw new NotImplementedException();
        }

        public IGraph<APC, Unit> AsBackwardGraph(bool includeExceptionEdges, bool skipContracts)
        {
            Contract.Ensures(Contract.Result<IGraph<APC, Unit>>() != null);
            throw new NotImplementedException();
        }

        public IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit> GetDecoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder)
        {
            Contract.Ensures(Contract.Result<IDecodeMSIL<APC, Local, Parameter, Method, Field, Type, Unit, Unit, IMethodContext<Field, Method>, Unit>>() != null);
            throw new NotImplementedException();
        }

        public Subroutine Subroutine
        {
            get
            {
                Contract.Ensures(Contract.Result<Subroutine>() != null);
                throw new NotImplementedException();
            }
        }

        public Tag ToString(APC pc)
        {
            Contract.Ensures(Contract.Result<string>() != null);
            throw new NotImplementedException();
        }

        public void Print(TextWriter tw, ILPrinter<APC> ilPrinter, BlockInfoPrinter<APC> edgePrinter, Func<CFGBlock, IEnumerable<SubroutineContext>> contextLookup, SubroutineContext context)
        {
            throw new NotImplementedException();
        }

        #endregion

        public FList<Pair<Tag, Subroutine>> GetOrdinaryEdgeSubroutines(CFGBlock from, CFGBlock to, SubroutineContext context)
        {
            Contract.Requires(from != null);
            Contract.Requires(to != null);
            throw new NotImplementedException();
        }
    }
    #endregion

    ///
    /// Code query
    ///
    public interface ICodeQuery : IVisitMSIL
    {
        ///
        /// Called if Code represents a nested code aggregate
        ///
        /// <param name="aggregateStart">Start label of aggregate</param>
        /// <param name="data">Client specific data threaded through the dispatch</param>
        /// <param name="current">Label where instruction is decoded</param>
        /// <param name="canBeTargetOfBranch">true if current can be a branch target. If not, the CFG can remove unnecessary program points </param>
        Result Aggregate(Label current, Label aggregateStart, bool canBeTargetOfBranch, Data data);
    }

    public interface ICodeProvider
    {
        ///
        /// Dispatches to the appropriate method in query based on the code at the given label
        ///
        R Decode<Visitor, T, R>(Label label, Visitor query, T data)
          where Visitor : ICodeQuery;

        //    Code Lookup(Label label);
        ///
        /// Returns the label of the code textually following the code at the given location (if sensible)
        ///
        /// <returns>true if next label is meaningful.</returns>
        bool Next(Label current, out Label nextLabel);

        ///
        /// Returns true if pc has source context associated with it
        ///
        bool HasSourceContext(Label pc);

        ///
        /// Returns the name of the associated document of the source context for this pc
        ///
        string SourceDocument(Label pc);

        ///
        /// Returns the first line number in the source context of this pc.
        ///
        int SourceStartLine(Label pc);

        ///
        /// Returns the last line number in the source context of this pc.
        ///
        int SourceEndLine(Label pc);

        ///
        /// Returns the first column number in the source context of this pc.
        ///
        int SourceStartColumn(Label pc);

        ///
        /// Returns the first column number in the source context of this pc.
        ///
        int SourceEndColumn(Label pc);

        ///
        /// The character index of the first character of the source context of this pc,
        /// when treating the source document as a single string.
        ///
        int SourceStartIndex(Label pc);

        ///
        /// The number of characters in the source context of this pc.
        ///
        int SourceLength(Label pc);

        ///
        /// Returns the IL offset within the method of the given instruction or 0
        ///
        int ILOffset(Label pc);

        ///
        /// If the label corresponds to a contract (assert/requires, etc), this
        /// may provide the user or tool provided condition.
        ///
        string SourceAssertionCondition(Label label);
    }

    public interface IMethodCodeProvider : ICodeProvider
    {
        ///
        /// Returns the handlers associated with the provided method
        ///
        IEnumerable<Handler> TryBlocks(Method method);

        ///
        /// Decodes ExceptionInfo for the kind of handler
        ///
        bool IsFaultHandler(Handler info);
        ///
        /// Decodes ExceptionInfo for the kind of handler
        ///
        bool IsFinallyHandler(Handler info);
        ///
        /// Decodes ExceptionInfo for the kind of handler
        ///
        bool IsCatchHandler(Handler info);
        ///
        /// Decodes ExceptionInfo for the kind of handler
        ///
        bool IsFilterHandler(Handler info);

        ///
        /// If the handler is a CatchHandler, this method returns the type of exception caught.
        /// Fails if !IsCatchHandler
        ///
        Type CatchType(Handler info);

        ///
        /// Should return true if this handler catches all Exceptions
        ///
        bool IsCatchAllHandler(Handler info);

        ///
        /// Decodes ExceptionInfo for the Label corresponding to the start of try block
        ///
        Label TryStart(Handler info);

        ///
        /// Decodes ExceptionInfo for the Label corresponding to the end of try block
        ///
        Label TryEnd(Handler info);

        ///
        /// Decodes ExceptionInfo for the Label corresponding to the start of filter decision block (if any)
        ///
        Label FilterDecisionStart(Handler info);

        ///
        /// Decodes ExceptionInfo for the Label corresponding to the start of handler block
        ///
        Label HandlerStart(Handler info);

        ///
        /// Decodes ExceptionInfo for the Label corresponding to the end of handler block
        ///
        Label HandlerEnd(Handler info);
    }

    public interface ICodeConsumer<Local, Parameter, Method, Field, Type, Data, Result>
    {
        Result Accept(ICodeProvider codeProvider, Label entryPoint, Data data);
    }

    public interface IMethodCodeConsumer<Local, Parameter, Method, Field, Type, Data, Result>
    {
        Result Accept(IMethodCodeProvider codeProvider, Label entryPoint, Method method, Data data);
    }
}


text:
function [MGx,MGy,Gxx,Gyy] = build_HudginDiscGradient(Nsubap, sub_samp, dx, mask)
% ------------HEADER-----------------
% Objective         ::  Build discrete 2-D gradient operator Gamma based on
%                       Hudgin geometry WFS. Based on function
%                       build_GammaSub.m from Qiang and Vogel under ../fdpcg/
%  input parameters ::
%                    1.Nsubap:      number of sub-apertures across the pupil
%                    2.sub_sampl:  subsampling of sensor grid. 0 if no
%                                  subsampling, 1 for 2-point subsampling,
%                                  2 for 3-point subsampling and so forth.
%                                  See Change record, 02/10/2008
%                    3. dx:        grid spacing, in meter
%                    4. mask:      sensor mask
%
%  output parameters ::
%                    1. Gamma_x:   2-D gradient operator with sensor masked
%                    2. Gamma_y:   2-D gradient operator with sensor masked
%                    3. Gxx:       periodic 1-D gradient operator - not any
%                                  longer
%                    4. Gyy:       periodic 1-D gradient operator
%                    5. srIdx:     sensor position where signals are measured - no longer available to
%                                  comply with sub-sampling procedure
%                    6. srMsk:     sensor mask - no longer available to
%                                  comply with sub-sampling procedure
%
%Created by         ::  Carlos Correia
%Creation date      ::  16/02/2007
%Change Record:     ::
%                       ccorreia 02/10/2008
%                        - Update of the sub-sampled case. Now if there is
%                       sub-sampling, the 'sub_samp' argin means how many
%                       points there are between the corners of the
%                       sub-aperture. For example: If sub_samp == 1 there
%                       is a 1-point subsampling, with the sub-aperture
%                       making 3x3 pixels size. If sub_samp == 0 then each
%                       sub-aperture is a 2x2 pixels size.
%
%                       ccorreia 22/08/2008
%                       - Now I take care of the fact there are Nx(N-1) slopes in X and (N-1)xN in Y. This
%                         same result is in the work of Ren and Dekany 2004.
% ------------HEADER END----------------

if sub_samp > 0
    % add a zeros band rightewards and downwards
    mask = [mask zeros(size(mask,1),1)];
    mask = [mask;zeros(1,size(mask,2))];
    mask = subsample_mask(mask,sub_samp);
    % remove the added band
    mask = mask(1:end-1,1:end-1);
end

twoN = (Nsubap+1)+ (Nsubap)*sub_samp;
twoN_sq = twoN^2;
nskip = 2^sub_samp;
n_act = Nsubap+1;

% build 1-D periodic gradient operators
onevec = ones(twoN_sq,1);
Gyy = spdiags([onevec -onevec], [0 sub_samp+1], twoN,twoN);
Gyy(twoN,1) = -1;

Gyy1d = Gyy;
%cc, 10/10/06, I added the "floor" in the following cycles
% for i = 1 : twoN
%     if mod(floor(i-1-nskip/2), nskip) ~= 0
%         Gyy1d(i,:) = Gyy1d(i,:) * 0;
%     end
% end

% kron the 1-D gradient operators to retrieve 2-D gradient operators
%ccorreia: although it becomes a 2-D gradient operator, do not confound
%with the Laplacian (which is a curvature operator (2nd-order
%derivative)
% see Fast wave-front reconstruction by solving the Sylvester equation with the alternating direction implicit method
% Hongwu Ren and Richard Dekany, 2004. Explanations therein.
% cc, 21/08/2008 these next two lines have been updated. Now I take
% care of the fact there are Nx(N-1) slopes in X and (N-1)xN in Y. This
% same result is in the work of Ren and Dekany
Gy = kron(Gyy1d(1:length(Gyy1d),:), eye(length(Gyy1d)-1,length(Gyy1d)));
Gx = kron(eye(size(Gyy1d)),Gyy1d(1:length(Gyy1d)-1,:));

%Gy = kron(Gyy1d, eye(size(Gyy1d)));
%Gx = kron(eye(size(Gyy1d)),Gyy1d);

%cc : These "for" cycles could be replaced by a dyaddown and dyadup procedure:
%test=dyaddown(dyaddown(mask_est)');
%test1=dyadup(dyadup(test)');
%..has many times as the subsampling requires (once for no subsampling,
%twice for 2-element subsampling and so forth
%cc, 10/10/06, I added the floor (2x) in the following cycles
%clear srIdx;
% idxCnt = 0;
% for i = 1 : n_act-1
%     m = floor((i-1)*nskip + nskip/2 + 1);
%     for j = 1 : n_act-1
%         n = floor((j-1)*nskip + nskip/2 + 1);
%         if mask_extended(m, n) > 0
%             idxCnt = idxCnt + 1;
%             srIdx(idxCnt) = (m-1)*twoN + n;
%         end
%     end
% end

if nargin > 3
    srIdx = find(mask);
else
    srIdx = 1:twoN_sq-twoN;
end

%srIdx = 1:nnz(mask);
srMask = sparse(twoN,twoN);
%Positions pointed by srIdx are assigned to one, The remaining are
%zero-valued
srMask(srIdx) = ones(size(srIdx));
M_sr = spdiags(srMask(:), 0, twoN_sq-twoN, twoN_sq-twoN);
%M_sr = spdiags(srMask(:), 0, twoN_sq,twoN_sq);

MGx = M_sr * Gx;
MGy = M_sr * Gy;
MGx = MGx(srIdx,:);
MGy = MGy(srIdx,:);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace lo\core\actions\crud;

use lo\core\actions\Base;
use lo\core\db\ActiveQuery;
use lo\core\db\ActiveRecord;
use lo\core\helpers\PkHelper;
use Yii;

/**
 * Class GroupDelete
 * Класс для группового удаления моделей
 *
 * @package lo\core\actions\crud
 * @author  Lukyanov Andrey <loveorigami@mail.ru>
 */
class GroupStatus extends Base
{
    /** @var string имя параметра в запросе в котором передаются идентификаторы материалов при групповых операциях */
    public $groupIdsAttr = "selection";

    /** @var string сценарий для валидации */
    public $modelScenario = ActiveRecord::SCENARIO_SEARCH;

    public $attr = 'status';

    /** @var  int */
    public $status;

    /**
     * @throws \yii\web\ForbiddenHttpException
     */
    public function run()
    {
        /** @var ActiveRecord $class */
        $class = $this->modelClass;
        $ids = Yii::$app->request->post($this->groupIdsAttr, []);
        $ids = PkHelper::decodeAll($ids);

        if (!empty($ids)) {
            /** @var ActiveQuery $query */
            $query = $class::findByPk($ids);
            /** @var ActiveRecord $model */
            foreach ($query->all() as $model) {
                $this->canAction($model);
                $model->{$this->attr} = $this->status;
                $model->save();
            }
        }

        if (!Yii::$app->request->isAjax) {
            return $this->goBack();
        }

        return null;
    }
}


text:
package net.rkseeger.taglib.include;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class ParamTag extends TagSupport {
    String name;
    String value;

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    public void setValue(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }

    @Override
    public int doStartTag() throws JspException {
//        try {
//            pageContext.getOut().println("
ParamTag:doStartTag
");
//        } catch(IOException ex) {
//            throw new RuntimeException(ex);
//        }

        IncludeTag ancestorTag = (IncludeTag)findAncestorWithClass(this, IncludeTag.class);
        if(ancestorTag == null) {
            throw new JspException("param tag must be inside include tag");
        }
        if(ancestorTag.getEvaluated()) {
            Utilities.debug(pageContext, ancestorTag.toString() + " is evaluated already");
            throw new JspException("param tag must be before catch tag");
        } else {
            Utilities.debug(pageContext, ancestorTag.toString() + " is NOT evaluated already");
        }
        ancestorTag.addParameter(getName(), getValue());
        name = null;
        value = null;

        return SKIP_BODY;

    }

}


text:
.. _startup-sequence:

****************************
The MathJax Startup Sequence
****************************

When you load ``MathJax.js`` into a web page, it configures itself and
immediately begins loading the components it needs.  As MathJax starts
up, it uses its :ref:`signaling mechanism <synchronization>`
to indicate the actions that it is taking so that MathJax extensions
can tie into the initialization process, and so other applications
within the page can synchronize their actions with MathJax.

The startup process performs the following actions:

- It creates the ``MathJax`` variable, and defines the following
  subsystems:

  - ``MathJax.Object`` (object-oriented programming model)
  - ``MathJax.Callback`` (callbacks, signals, and queues)
  - ``MathJax.Ajax`` (file-loading and style-creation code)
  - ``MathJax.HTML`` (support code for creating HTML elements)
  - ``MathJax.Localization`` (alternative language support)
  - ``MathJax.Message`` (manages the menu line in the lower left)
  - ``MathJax.Hub`` (the core MathJax functions)

..

- It then creates the base ``MathJax.InputJax``,
  ``MathJax.OutputJax``, and ``MathJax.ElementJax`` objects.

..

- MathJax sets up the default configuration, and creates the
  signal objects used for the startup and hub actions.

..

- MathJax locates the ``<script>`` tag that loaded the ``MathJax.js``
  file, and sets the ``MathJax.Hub.config.root`` value to reflect the
  location of the MathJax root directory.

..

- MathJax determines the browser being used and its version.  It sets
  up the ``MathJax.Hub.Browser`` object, which includes the browser
  name and version, plus ``isMac``, ``isPC``, ``isMSIE``, and so on.

..

- MathJax executes the ``AuthorInit()`` function specified from in-line
  ``MathJax = {...}`` configuration.

..

- MathJax sets up the ``MathJax.Hub.queue`` command queue, and
  populates it with the commands MathJax runs at startup.  This
  includes creating the ``MathJax.Hub.Startup.onload`` onload
  handler that is used to synchronize MathJax's action with the
  loading of the page.

Once the ``MathJax.Hub.queue`` is created, the following actions are
pushed into the queue:

1.  Post the ``Begin`` startup signal

..

2.  Perform the configuration actions:

    - Post the ``Begin Config`` startup signal
    - Load any configuration files specified via ``config=`` as a script parameter
    - Perform author configuration from in-line ``MathJax = {...}``
    - Execute the content of the ``<script>`` that loaded MathJax, if it is not empty
    - Wait for the ``delayStartupUntil`` condition to be met, if one was specified
    - Execute any ``text/x-mathjax-config`` script blocks
    - load the files listed in the ``MathJax.Hub.config.config`` array
    - Post the ``End Config`` startup signal

..

3.  Load the cookie values:

    - Post the ``Begin Cookie`` startup signal
    - Load the menu cookie values
    - Use the cookie to set the renderer, if it is set
    - Post the ``End Cookie`` startup signal

..

4.  Define the MathJax styles:

    - Post the ``Begin Styles`` startup signal
    - Load the stylesheet files from the ``MathJax.Hub.config.stylesheets`` array
    - Define the stylesheet described in ``MathJax.Hub.config.styles``
    - Post the ``End Styles`` startup signal

..

5.  Initialize the Message system (the grey information box in the
    lower left)

..

6.  Load the jax configuration files:

    - Post the ``Begin Jax`` startup signal
    - Load the jax config files from the ``MathJax.Hub.config.jax`` array

      - The jax will register themselves when they are loaded

    - Post the ``End Jax`` startup signal

..

7.  Load the extension files:

    - Post the ``Begin Extensions`` startup signal
    - Load the files from the ``MathJax.Hub.config.extensions`` array

      - Most extensions will post a ``[name] Ready`` or ``Extension
        [name] Ready`` startup message when they are loaded (where
        ``[name]`` is the name of the extension)

    - Post the ``End Extensions`` startup signal

..

8.  Set the MathJax menu's renderer value based on the jax that have been
    loaded

..

9.  Wait for the onload handler to fire (in MathJax v2.0 this can
    occur on the ``DOMContentLoaded`` event rather than the page's
    ``onload`` event, so processing of mathematics can start earlier)

..

10. Set ``MathJax.isReady`` to ``true``

..

11. Perform the typesetting pass (preprocessors and processors)

    - Post the ``Begin Typeset`` startup signal
    - Post the ``Begin PreProcess`` hub signal
    - Run the registered preprocessors
    - Post the ``End PreProcess`` hub signal
    - Clear the hub signal history
    - Post the ``Begin Process`` hub signal
    - Process the math script elements on the page

      - There are a number of Hub signals generated during math
        processing, including a signal that a ``Math`` action is
        starting (with a parameter indicating what action that is),
        ``Begin`` and ``End Math Input`` messages, and ``Begin`` and
        ``End Math Output`` signals.

      - Each new math element generates a ``New Math`` hub signal
        with the math element's ID

    - Post the ``End Process`` hub signal
    - Post the ``End Typeset`` startup signal

..

12. Jump to the location specified in the URL's hash reference, if
    any.

..

13. Initiate timers to load the zoom and menu code, if it hasn't
    already been loading in the configuration (so it will be ready
    when the user needs it).

..

14. Post the ``End`` startup signal

The loading of the jax and extensions in steps 6 and 7 are now done in
parallel, rather than sequentially.  That is, all the jax and extensions
are requested simultaneously, so they load concurrently.  That means they
can load in any order, and that the begin and end signals for the jax and
extensions can be intermixed.  (In general, you will get `Begin Jax`
followed by `Begin Extensions`, but the order of `End Jax` and `End
Extensions` will depend on the files being loaded.)  Both 6 and 7 must
complete, however, before 8 will be performed.

See the `test/sample-signals.html
<https://github.com/mathjax/MathJax/tree/master/test/sample-signals.html>`_ file
to see the signals in action.


text:
cask 'coverload' do
  version '1.2.4-535'
  sha256 '854c3d128fe911fb4e5fff9046392cd6567518ffa494a87a1a92add98a059c78'

  # amazonaws.com/coverloadapp.com was verified as official when first introduced to the cask
  url "https://s3-us-west-2.amazonaws.com/coverloadapp.com/Uploads/CoverLoad-#{version}.zip"
  name 'CoverLoad'
  homepage 'https://coverloadapp.com/'

  app 'CoverLoad.app'
end


text:
package org.keycloak.adapters.saml.undertow;

import org.keycloak.adapters.saml.SamlAuthenticator;
import org.keycloak.adapters.saml.SamlDeployment;
import org.keycloak.adapters.saml.SamlSession;
import org.keycloak.adapters.saml.SamlSessionStore;
import org.keycloak.adapters.saml.profile.SamlAuthenticationHandler;
import org.keycloak.adapters.saml.profile.webbrowsersso.SamlEndpoint;
import org.keycloak.adapters.spi.HttpFacade;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class UndertowSamlEndpoint extends SamlAuthenticator {
    public UndertowSamlEndpoint(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
        super(facade, deployment, sessionStore);
    }

    @Override
    protected void completeAuthentication(SamlSession samlSession) {

    }

    @Override
    protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
        return new SamlEndpoint(facade, deployment, sessionStore);
    }
}


text:
    <!-- ******************************************************** -->
    <!-- frequently tuned properties                              -->
    <!-- ******************************************************** -->
    <property name="absoluteBeamWidth" value="500"/>
    <property name="relativeBeamWidth" value="1E-80"/>
    <property name="absoluteWordBeamWidth" value="100"/>
    <property name="relativeWordBeamWidth" value="1E-60"/>
    <property name="silenceInsertionProbability" value=".1"/>
    <property name="logLevel" value="WARNING"/>
    <!-- The next parameter determines how often intermediate results are produced
	     (and hence, how often resultListeners are called) -->
    <property name="step" value="1"/>
    <property name="recognizer" value="recognizer"/>
    <property name="scorer" value="simpleScorer"/>

    <!-- alternatives: flatLinguist | lexTreeLinguist -->
    <property name="linguist"   value="lexTreeLinguist"/>

    <!-- alternatives: fakeSearch | simpleSearch | wordPruningSearch -->
    <property name="searchManager" value="wordPruningSearch"/>

    <!-- alternatives: ngramGrammar | jsgfGrammar | forcedAligner; only relevant with flatLinguist -->
    <property name="grammar" value="jsgfGrammar"/>

    <property name="frontend" value="frontend"/>
    <!-- The minimum amount of time in speech (in milliseconds) to be considered as utterance start -->
    <property name="startSpeech" value="100"/>
    <!-- The amount of time in silence (in milliseconds) to be considered as utterance end -->
    <property name="endSilence" value="250"/>
    <!-- The amount of time (in milliseconds) before speech start to be included as speech data. -->
    <property name="speechLeader" value="30"/>
    <!-- The amount of time (in milliseconds) after speech ends to be included as speech data. -->
    <property name="speechTrailer" value="200"/>
    <!-- The speech classifier threshold. -->
    <property name="threshold" value="15"/>

    <!-- ******************************************************** -->
    <!-- The recognizer configuration                             -->
    <!-- ******************************************************** -->
    <component name="recognizer" type="edu.cmu.sphinx.recognizer.Recognizer">
        <property name="decoder" value="decoder"/>
        <propertylist name="monitors">
<!--
        	<item>threadingListener</item>
        	<item>currentASRHypothesis</item>
        	<item>confiDancer</item>
            <item>labelWriter </item>
        	<item>speedTracker </item>
            <item>memoryTracker </item>
            <item>newWordNotifierAgent </item>
			<item>TEDviewNotifier</item>
-->
        </propertylist>
    </component>

    <component name="threadingListener" type="inpro.sphinx.instrumentation.ThreadingListener">
        <property name="recognizer" value="${recognizer}"/>
        <property name="queueSize" value="1"/>
        <propertylist name="listeners">
            <item>currentASRHypothesis</item>
        </propertylist>
    </component>

    <!-- ******************************************************** -->
    <!-- The Decoder   configuration                              -->
    <!-- ******************************************************** -->
    <component name="decoder" type="edu.cmu.sphinx.decoder.Decoder">
        <property name="searchManager" value="${searchManager}"/>
        <property name="fireNonFinalResults" value="true"/>
        <property name="featureBlockSize" value="${step}"/>
    </component>

    <component name="fakeSearch" type="inpro.sphinx.decoder.FakeSearch">
        <property name="dictionary" value="dictionary"/>
        <property name="unitManager" value="unitManager"/>
        <property name="frontend" value="frontend"/>
        <property name="asrWords" value="words"/>
        <property name="asrUnits" value="phones"/>
        <property name="textGrid" value=""/>
    </component>

    <component name="simpleSearch" type="edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager">
        <property name="logMath" value="logMath"/>
        <property name="linguist" value="flatLinguist"/>
        <property name="pruner" value="trivialPruner"/>
        <property name="scorer" value="threadedScorer"/>
        <property name="activeListFactory" value="standardActiveListFactory"/>
        <property name="keepAllTokens" value="true"/>
    </component>

    <component name="wordPruningSearch" type="edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager">
        <property name="logMath" value="logMath"/>
        <property name="linguist" value="${linguist}"/>
        <property name="pruner" value="trivialPruner"/>
        <property name="scorer" value="${scorer}"/>
        <property name="activeListManager" value="activeListManager"/>
        <property name="buildWordLattice" value="true"/>
        <property name="acousticLookaheadFrames" value="1.7"/>
        <property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
        <property name="keepAllTokens" value="true"/>
    </component>

    <component name="activeListManager" type="edu.cmu.sphinx.decoder.search.SimpleActiveListManager">
        <propertylist name="activeListFactories">
            <item>standardActiveListFactory</item>
            <item>wordActiveListFactory</item>
            <item>wordActiveListFactory</item>
            <item>standardActiveListFactory</item>
            <item>standardActiveListFactory</item>
            <item>standardActiveListFactory</item>
        </propertylist>
    </component>

    <component name="standardActiveListFactory" type="edu.cmu.sphinx.decoder.search.SimpleActiveListFactory">
        <property name="logMath" value="logMath"/>
        <property name="absoluteBeamWidth" value="${absoluteBeamWidth}"/>
        <property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
    </component>

    <component name="wordActiveListFactory" type="edu.cmu.sphinx.decoder.search.SimpleActiveListFactory">
        <property name="logMath" value="logMath"/>
        <property name="absoluteBeamWidth" value="${absoluteWordBeamWidth}"/>
        <property name="relativeBeamWidth" value="${relativeWordBeamWidth}"/>
    </component>

    <component name="activeList" type="edu.cmu.sphinx.decoder.search.SortingActiveListFactory">
        <property name="logMath" value="logMath"/>
        <property name="absoluteBeamWidth" value="${absoluteBeamWidth}"/>
        <property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
    </component>

    <!--component name="trivialPruner" type="test.inpro.sphinx.DislikePruner"/-->
    <component name="trivialPruner" type="edu.cmu.sphinx.decoder.pruner.SimplePruner"/>

    <component name="simpleScorer" type="edu.cmu.sphinx.decoder.scorer.SimpleAcousticScorer">
        <property name="frontend" value="${frontend}"/>
        <property name="scoreablesKeepFeature" value="true"/>
    </component>

    <component name="threadedScorer" type="edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer">
        <property name="frontend" value="${frontend}"/>
        <property name="isCpuRelative" value="true"/>
        <property name="numThreads" value="1"/>
        <property name="minScoreablesPerThread" value="100"/>
        <property name="scoreablesKeepFeature" value="true"/>
    </component>

    <!-- ******************************************************** -->
    <!-- The linguist  configuration                              -->
    <!-- ******************************************************** -->
    <component name="lexTreeLinguist" type="edu.cmu.sphinx.linguist.lextree.LexTreeLinguist">
        <property name="logMath" value="logMath"/>
        <property name="acousticModel" value="acousticModel"/>
        <property name="languageModel" value="ngram"/>
        <property name="dictionary" value="dictionary"/>
        <property name="generateUnitStates" value="true"/>
        <property name="wantUnigramSmear" value="true"/>
        <property name="unigramSmearWeight" value="1"/>
        <property name="silenceInsertionProbability" value="${silenceInsertionProbability}"/>
        <property name="languageWeight" value="${languageWeight}"/>
        <property name="unitManager" value="unitManager"/>
        <!--property name="showCompilationProgress" value="false"/-->
    </component>

    <component name="flatLinguist" type="edu.cmu.sphinx.linguist.flat.FlatLinguist">
        <property name="logMath" value="logMath"/>
        <property name="grammar" value="${grammar}"/>
        <property name="acousticModel" value="acousticModel"/>
        <property name="wordInsertionProbability" value="${wordInsertionProbability}"/>
        <property name="silenceInsertionProbability" value="${silenceInsertionProbability}"/>
        <property name="languageWeight" value="${languageWeight}"/>
        <property name="unitManager" value="unitManager"/>
    </component>

    <!-- ******************************************************** -->
    <!-- The Grammar  configuration                               -->
    <!-- ******************************************************** -->
    <component name="forcedAligner" type="edu.cmu.sphinx.linguist.language.grammar.AlignerGrammar">
        <property name="dictionary" value="dictionary"/>
        <property name="addSilenceWords" value="true"/>
        <property name="addFillerWords" value="false"/>
        <property name="logMath" value="logMath"/>
    </component>

    <component name="ngramGrammar" type="edu.cmu.sphinx.linguist.language.grammar.LMGrammar">
        <property name="dictionary" value="dictionary"/>
        <property name="languageModel" value="ngram"/>
    </component>

    <component name="interpolatedLM" type="edu.cmu.sphinx.linguist.language.ngram.InterpolatedLanguageModel">
    	<property name="logMath" value="logMath"/>
    	<propertylist name="languageModels">
    		<item>ngram</item>
    		<item>ngram2</item>
    	</propertylist>
    	<propertylist name="languageModelWeights">
    		<item>1.0</item>
    		<item>0.0</item>
    	</propertylist>
    </component>

    <!-- ******************************************************** -->
    <!-- The acoustic model and unit manager configuration        -->
    <!-- ******************************************************** -->
    <component name="acousticModel" type="edu.cmu.sphinx.linguist.acoustic.tiedstate.TiedStateAcousticModel">
        <property name="loader" value="sphinx3Loader"/>
        <property name="unitManager" value="unitManager"/>
    </component>

    <component name="unitManager" type="edu.cmu.sphinx.linguist.acoustic.UnitManager"/>

    <!-- ******************************************************* -->
    <!--  monitors                                               -->
    <!-- ******************************************************* -->
    <component name="labelWriter" type="inpro.sphinx.instrumentation.LabelWriter">
        <property name="recognizer" value="${recognizer}"/>
        <property name="intermediateResults" value="true"/>
        <property name="finalResult" value="false"/>
        <property name="wordAlignment" value="true"/>
        <property name="phoneAlignment" value="false"/>
        <property name="step" value="${step}"/>
        <property name="fileOutput" value="false"/>
        <property name="fileBaseName" value=""/>
        <property name="nBest" value="1"/>
        <property name="fixedLag" value="0"/>
    </component>

<!--    <component name="newWordNotifierAgent" type="inpro.sphinx.instrumentation.NewWordNotifierAgent">
        <property name="recognizer" value="${recognizer}"/>
    </component> -->

    <component name="memoryTracker" type="edu.cmu.sphinx.instrumentation.MemoryTracker">
        <property name="recognizer" value="${recognizer}"/>
    </component>

<!--    <component name="confiDancer" type="inpro.sphinx.instrumentation.ConfiDancer">
        <property name="recognizer" value="${recognizer}"/>
        <property name="confidenceScorer" value="confidenceScorer"/>
    </component> -->

    <component name="speedTracker" type="edu.cmu.sphinx.instrumentation.SpeedTracker">
        <property name="recognizer" value="${recognizer}"/>
        <property name="frontend" value="${frontend}"/>
        <property name="showTimers" value="true"/>
        <property name="showResponseTime" value="true"/>
    </component>

    <!-- ******************************************************* -->
    <!--  Miscellaneous components                               -->
    <!-- ******************************************************* -->
    <component name="logMath" type="edu.cmu.sphinx.util.LogMath">
        <property name="logBase" value="1.0001"/>
        <property name="useAddTable" value="true"/>
    </component>

    <component name="confidenceScorer"
               type="edu.cmu.sphinx.result.SausageMaker">
        <property name="languageWeight" value="${languageWeight}"/>
    </component>


text:
#ifndef BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED
#define BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED

// Copyright Paul Mensonides 2003
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source: /cvsroot/boost/boost/boost/mpl/aux_/preprocessor/is_seq.hpp,v $
// $Date: 2004/09/02 15:40:56 $
// $Revision: 1.3 $

#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/arithmetic/dec.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/config/config.hpp>

// returns 1 if 'seq' is a PP-sequence, 0 otherwise:
//
//   BOOST_PP_ASSERT( BOOST_PP_NOT( BOOST_MPL_PP_IS_SEQ( int ) ) )
//   BOOST_PP_ASSERT( BOOST_MPL_PP_IS_SEQ( (int) ) )
//   BOOST_PP_ASSERT( BOOST_MPL_PP_IS_SEQ( (1)(2) ) )

#if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_BCC()

#   define BOOST_MPL_PP_IS_SEQ(seq) BOOST_PP_DEC( BOOST_PP_SEQ_SIZE( BOOST_MPL_PP_IS_SEQ_(seq) ) )
#   define BOOST_MPL_PP_IS_SEQ_(seq) BOOST_MPL_PP_IS_SEQ_SEQ_( BOOST_MPL_PP_IS_SEQ_SPLIT_ seq )
#   define BOOST_MPL_PP_IS_SEQ_SEQ_(x) (x)
#   define BOOST_MPL_PP_IS_SEQ_SPLIT_(unused) unused)((unused)

#else

#   if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
#       define BOOST_MPL_PP_IS_SEQ(seq) BOOST_MPL_PP_IS_SEQ_MWCC_((seq))
#       define BOOST_MPL_PP_IS_SEQ_MWCC_(args) BOOST_MPL_PP_IS_SEQ_ ## args
#   else
#       define BOOST_MPL_PP_IS_SEQ(seq) BOOST_MPL_PP_IS_SEQ_(seq)
#   endif

#   define BOOST_MPL_PP_IS_SEQ_(seq) BOOST_PP_CAT(BOOST_MPL_PP_IS_SEQ_, BOOST_MPL_PP_IS_SEQ_0 seq BOOST_PP_RPAREN())
#   define BOOST_MPL_PP_IS_SEQ_0(x) BOOST_MPL_PP_IS_SEQ_1(x
#   define BOOST_MPL_PP_IS_SEQ_ALWAYS_0(unused) 0
#   define BOOST_MPL_PP_IS_SEQ_BOOST_MPL_PP_IS_SEQ_0 BOOST_MPL_PP_IS_SEQ_ALWAYS_0(
#   define BOOST_MPL_PP_IS_SEQ_BOOST_MPL_PP_IS_SEQ_1(unused) 1

#endif

#endif // BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED


text:
interface color {}

interface blue extends color() { // error

}


text:
package com.plivo.api.models.conference;

import com.plivo.api.models.base.Deleter;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class ConferenceAllDeleter extends Deleter<Conference> {

  public ConferenceAllDeleter() {
    super("");
  }

  @Override
  protected Call<ResponseBody> obtainCall() {
    return client().getApiService().conferenceDeleteAll(client().getAuthId());
  }
}


text:
#define _GNU_SOURCE
#include <signal.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <numa.h>

#include "pfring.h"
#include "pfring_zc.h"
#include "pfring_mod_sysdig.h"

#include "zutils.c"

#define ALARM_SLEEP             1
#define MAX_CARD_SLOTS      32768
#define PREFETCH_BUFFERS        8
#define QUEUE_LEN            8192
#define POOL_SIZE              16
#define CACHE_LINE_LEN         64
#define MAX_NUM_APP	       32

pfring_zc_cluster *zc;
pfring_zc_worker *zw;
pfring_zc_queue **inzqs;
pfring_zc_queue **outzqs;
pfring_zc_multi_queue *outzmq; /* fanout */
pfring_zc_buffer_pool **pools;
pfring_zc_buffer_pool *wsp;

u_int32_t num_in_devices = 0;
char **in_devices = NULL;

u_int32_t num_out_devices = 0;
char **out_devices = NULL;

int cluster_id = -1;
int metadata_len = 0;
int bind_worker_core = -1;
struct timeval start_time;

u_int8_t do_shutdown = 0;

/* ******************************** */

void print_stats() {
  static u_int8_t print_all = 0;
  static struct timeval last_time;
  static unsigned long long last_tot_recv = 0, last_tot_sent = 0, last_tot_drop = 0;
  unsigned long long tot_recv = 0, tot_drop = 0, tot_sent = 0;
  struct timeval end_time;
  char buf1[64], buf2[64], buf3[64];
  pfring_zc_stat stats;
  char stats_buf[1024] = { '\0' };
  int i;
  u_int64_t tot_if_recv = 0, tot_if_drop = 0;

  if(start_time.tv_sec == 0)
    gettimeofday(&start_time, NULL);
  else
    print_all = 1;

  gettimeofday(&end_time, NULL);

  for(i = 0; i < num_in_devices; i++)
    if(pfring_zc_stats(inzqs[i], &stats) == 0)
      tot_recv += stats.recv, tot_drop += stats.drop;

  for(i = 0; i < num_out_devices; i++)
    if(pfring_zc_stats(outzqs[i], &stats) == 0)
      tot_sent += stats.sent;

  fprintf(stderr, "=========================\n"
          "Absolute Stats: Recv %s pkts (%s drops) - Forwarded %s pkts\n",
	  pfring_format_numbers((double)tot_recv, buf1, sizeof(buf1), 0),
	  pfring_format_numbers((double)tot_drop, buf2, sizeof(buf2), 0),
	  pfring_format_numbers((double)tot_sent, buf3, sizeof(buf3), 0)
	  );

  for(i = 0; i < num_in_devices; i++) {
    if(pfring_zc_stats(inzqs[i], &stats) == 0) {
      tot_if_recv += stats.recv, tot_if_drop += stats.drop;
      fprintf(stderr, "                %s RX %lu pkts Dropped %lu pkts (%.1f %%)\n",
	      in_devices[i],
	      (long unsigned int)stats.recv,
	      (long unsigned int)stats.drop,
	      stats.recv == 0 ? 0 : ((double)(stats.drop*100)/(double)(stats.recv + stats.drop)));
    }
  }
  snprintf(&stats_buf[strlen(stats_buf)], sizeof(stats_buf)-strlen(stats_buf),
	   "IFPackets:         %lu\n"
	   "tot_if_dropped:         %lu\n",
	   (long unsigned int)tot_if_recv,
	   (long unsigned int)tot_if_drop);

  pfring_zc_set_proc_stats(zc, stats_buf);

  if(print_all && last_time.tv_sec > 0) {
    double delta_msec = delta_time(&end_time, &last_time);
    unsigned long long diff_recv = tot_recv - last_tot_recv;
    unsigned long long diff_drop = tot_drop - last_tot_drop;
    unsigned long long diff_sent = tot_sent - last_tot_sent;

    fprintf(stderr, "Actual Stats: Recv %s pps (%s drops) - Forwarded %s pps\n",
	    pfring_format_numbers(((double)diff_recv/(double)(delta_msec/1000)),  buf1, sizeof(buf1), 1),
	    pfring_format_numbers(((double)diff_drop/(double)(delta_msec/1000)),  buf2, sizeof(buf2), 1),
	    pfring_format_numbers(((double)diff_sent/(double)(delta_msec/1000)),  buf3, sizeof(buf3), 1)
	    );
  }

  fprintf(stderr, "=========================\n\n");

  last_tot_recv = tot_recv, last_tot_drop = tot_drop, last_tot_sent = tot_sent;
  last_time.tv_sec = end_time.tv_sec, last_time.tv_usec = end_time.tv_usec;
}

/* ******************************** */

void sigproc(int sig) {
  static int called = 0;
  fprintf(stderr, "Leaving...\n");
  if(called) return; else called = 1;

  do_shutdown = 1;

  pfring_zc_kill_worker(zw);

  print_stats();
}

/* *************************************** */

void printHelp(void) {
  printf("zreplicator - (C) 2014 ntop.org\n");
  printf("Using PFRING_ZC v.%s\n", pfring_zc_version());
  printf("Read packets from multiple ingress devices and replicate it on multipe egress devices.\n\n");
  printf("Usage: zreplicator -i <device> -o <device> -c <cluster id> [-h] [-g <core id>] [-a]\n\n");
  printf("-h              Print this help\n");
  printf("-i <device>     Ingress devices (comma-separated list)\n");
  printf("-o <device>     Egress devices (comma-separated list)\n");
  printf("-c <cluster id> Cluster id\n");
  printf("-g <core id>    Bind this app to a core\n");
  printf("-a              Active packet wait\n");
  exit(-1);
}

/* *************************************** */

int main(int argc, char* argv[]) {
  char c;
  char *ingress_devices = NULL, *egress_devices = NULL, *dev;
  long i;
  int  wait_for_packet = 1;

  start_time.tv_sec = 0;

  while((c = getopt(argc,argv, "ac:g:hi:o:")) != '?') {
    if((c == 255) || (c == -1)) break;

    switch(c) {
    case 'h':
      printHelp();
      break;
    case 'a':
      wait_for_packet = 0;
      break;
    case 'c':
      cluster_id = atoi(optarg);
      break;
    case 'i':
      ingress_devices = strdup(optarg);
      break;
    case 'o':
      egress_devices = strdup(optarg);
      break;
    case 'g':
      bind_worker_core = atoi(optarg);
      break;
    }
  }

  if(cluster_id < 0) printHelp();

  dev = strtok(ingress_devices, ",");
  while(dev != NULL) {
    in_devices = realloc(in_devices, sizeof(char *) * (num_in_devices+1));
    in_devices[num_in_devices] = strdup(dev);
    num_in_devices++;
    dev = strtok(NULL, ",");
  }

  dev = strtok(egress_devices, ",");
  while(dev != NULL) {
    out_devices = realloc(out_devices, sizeof(char *) * (num_out_devices+1));
    out_devices[num_out_devices] = strdup(dev);
    num_out_devices++;
    dev = strtok(NULL, ",");
  }

  if((num_in_devices == 0) || (num_out_devices == 0)) printHelp();

  zc = pfring_zc_create_cluster(cluster_id,
				max_packet_len(in_devices[0]),
				metadata_len,
				((num_in_devices + num_out_devices) * MAX_CARD_SLOTS) + PREFETCH_BUFFERS,
				numa_node_of_cpu(bind_worker_core),
				NULL /* auto hugetlb mountpoint */);

  if(zc == NULL) {
    fprintf(stderr, "pfring_zc_create_cluster error [%s] Please check your hugetlb configuration\n",
	    strerror(errno));
    return -1;
  }

  inzqs  = calloc(num_in_devices, sizeof(pfring_zc_queue *));
  outzqs = calloc(num_out_devices,  sizeof(pfring_zc_queue *));

  for(i = 0; i < num_in_devices; i++) {
    inzqs[i] = pfring_zc_open_device(zc, in_devices[i], rx_only, 0);

    if(inzqs[i] == NULL) {
      fprintf(stderr, "[RX] pfring_zc_open_device error [%s] Please check that %s is up and not already used\n",
	      strerror(errno), in_devices[i]);
      return -1;
    }
  }

  for(i = 0; i < num_out_devices; i++) {
    outzqs[i] = pfring_zc_open_device(zc, out_devices[i], tx_only, 0);

    if(outzqs[i] == NULL) {
      fprintf(stderr, "[TX] pfring_zc_open_device error [%s] Please check that %s is up and not already used\n",
	      strerror(errno), out_devices[i]);
      return -1;
    }
  }

  signal(SIGINT,  sigproc);
  signal(SIGTERM, sigproc);
  signal(SIGINT,  sigproc);

  outzmq = pfring_zc_create_multi_queue(outzqs, num_out_devices);

  if(outzmq == NULL) {
    fprintf(stderr, "pfring_zc_create_multi_queue error [%s]\n", strerror(errno));
    return -1;
  }

  wsp = pfring_zc_create_buffer_pool(zc, PREFETCH_BUFFERS);

  if(wsp == NULL) {
    fprintf(stderr, "pfring_zc_create_buffer_pool error\n");
    return -1;
  }

  zw = pfring_zc_run_fanout(inzqs,
			    outzmq,
			    num_in_devices,
			    wsp,
			    round_robin_bursts_policy,
			    NULL /* idle callback */,
			    NULL /* fanout */,
			    NULL,
			    !wait_for_packet,
			    bind_worker_core);

  if(zw == NULL) {
    fprintf(stderr, "pfring_zc_run_fanout error [%s]\n", strerror(errno));
    return -1;
  }

  while(!do_shutdown) {
    sleep(ALARM_SLEEP);
    print_stats();
  }

  pfring_zc_destroy_cluster(zc);

  return 0;
}


text:
v0.9.3
===

- All xml attributes prefixed with 'dv_'

v0.9.2
===

- Add Travis Continuous Integration
- Added support back to Android 2.2 (API 8)
- Added new example charts to sample app
- Reverse primary and secondary color for drawing gradient

v0.9.1
===

Initial implementation


text:
export { GlobalHandlers } from './globalhandlers';
export { TryCatch } from './trycatch';
export { Breadcrumbs } from './breadcrumbs';
export { LinkedErrors } from './linkederrors';
export { UserAgent } from './useragent';
export { Dedupe } from './dedupe';


text:
#import "FBLikeDialogParams.h"

#import "FBError.h"

@implementation FBLikeDialogParams

#pragma mark - Object Lifecycle

- (void)dealloc
{
    [_objectID release];
    [super dealloc];
}

#pragma mark - Internal Methods

- (NSDictionary *)dictionaryMethodArgs
{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    NSString *objectID = self.objectID;
    if (objectID) {
        dictionary[@"object_id"] = objectID;
    }
    dictionary[@"object_type"] = NSStringFromFBLikeControlObjectType(self.objectType);
    return dictionary;
}

- (NSError *)validate
{
    if (!self.objectID) {
        return [NSError errorWithDomain:FacebookSDKDomain
                                   code:FBErrorDialog
                               userInfo:@{ FBErrorDialogReasonKey: FBErrorDialogInvalidLikeObjectID }];
    }
    return nil;
}

+ (NSString *)methodName {
    return @"like";
}

#pragma mark - NSCopying

- (instancetype)copyWithZone:(NSZone *)zone
{
    FBLikeDialogParams *copy = [super copyWithZone:zone];
    copy->_objectID = [_objectID copyWithZone:zone];
    copy->_objectType = _objectType;
    return copy;
}

@end


text:
<?php

/*
 * This file is part of the LightSAML-Core package.
 *
 * (c) Milos Tomic <tmilos@lightsaml.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace LightSaml\Resolver\Credential;

use LightSaml\Credential\CredentialInterface;
use LightSaml\Criteria\CriteriaSet;

class CredentialResolverQuery extends CriteriaSet
{
    /** @var CredentialResolverInterface */
    private $resolver;

    /** @var CredentialInterface[] */
    private $arrCredentials;

    public function __construct(CredentialResolverInterface $resolver)
    {
        $this->resolver = $resolver;
    }

    /**
     * @return CredentialResolverQuery
     */
    public function resolve()
    {
        $this->arrCredentials = $this->resolver->resolve($this);

        return $this;
    }

    /**
     * @return CredentialInterface|null
     */
    public function firstCredential()
    {
        return reset($this->arrCredentials) ?: null;
    }

    /**
     * @return CredentialInterface[]
     */
    public function allCredentials()
    {
        return $this->arrCredentials;
    }

    /**
     * @return CredentialInterface[]
     */
    public function getPublicKeys()
    {
        $result = [];
        foreach ($this->arrCredentials as $credential) {
            if ($credential instanceof CredentialInterface) {
                $publicKey = $credential->getPublicKey();
                if ($publicKey) {
                    $result[] = $credential;
                }
            } else {
                throw new \InvalidArgumentException('Expected CredentialInterface');
            }
        }

        return $result;
    }

    /**
     * @return CredentialInterface[]
     */
    public function getPrivateKeys()
    {
        $result = [];
        foreach ($this->arrCredentials as $credential) {
            if ($credential instanceof CredentialInterface) {
                $privateKey = $credential->getPrivateKey();
                if ($privateKey) {
                    $result[] = $credential;
                }
            } else {
                throw new \InvalidArgumentException('Expected CredentialInterface');
            }
        }

        return $result;
    }
}


text:
--TEST--
Test session_encode() function : variation
--SKIPIF--
<?php include('skipif.inc'); ?>
--INI--
session.serialize_handler=blah
--FILE--
<?php

ob_start();

/*
 * Prototype : string session_encode(void)
 * Description : Encodes the current session data as a string
 * Source code : ext/session/session.c
 */

echo "*** Testing session_encode() : variation ***\n";

var_dump(session_start());
$_SESSION["foo"] = 1234567890;
$encoded = session_encode();
var_dump(base64_encode($encoded));
var_dump(session_destroy());

echo "Done";
ob_end_flush();
?>
--EXPECTF--
*** Testing session_encode() : variation ***

Warning: session_start(): Cannot find serialization handler 'blah' - session startup failed in %s on line %d
bool(false)

Warning: session_encode(): Cannot encode non-existent session in %s on line %d
string(0) ""

Warning: session_destroy(): Trying to destroy uninitialized session in %s on line %d
bool(false)
Done


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>LUSE</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<link rel="stylesheet" href="luse.css" type="text/css"/>

A FUSE binding for Lua

home ·
download ·
installation ·
manual ·
examples

1 - About LUSE

LUSE is a Lua binding for FUSE, which is a library allowing creation filesystem drivers run in userspace. LUSE is a low level binding. FUSE itself it rather slow, so LUSE tries not to impede performance more than necessary. For that reason it is manipulating userdata and pointers directly rather than Lua strings, with the reduced safety implied.

LUSE tries to be complete, but is not supporting obsolete APIs. The binding is closely following the FUSE API, so in most case you can use FUSE documentation if the present page is not clear enough. The missing functions are missing because I've not used them yet. I can add them on request (a use case could be helpful for non-trivial ones).

LUSE module itself is very basic, so I developed several other modules to help the development of a complete filesystem.

errno contains many constants representing POSIX error numbers. It also have an accessor to query the errno variable (which contains the last error number).

userdata can create and manipulate untyped userdata, to be used as buffers for read and write commands of the filesystem.

posixio is not strictly necessary, but it is very useful to implement many types of filesystem, which redirect I/O request to another filesystem. It contains bindings to many file and directory manipulation functions. Here again the read and write functions manipulate untyped userdata to keep overhead minimal.

Support

All support is done through the LUSE users mailing list:

luse-users@lists.luaforge.net

Feel free to ask for further developments. I can't guarantee that I'll develop everything you ask, but I want my code to be as useful as possible, so I'll do my best to help you. You can also send me request or bug reports (for code and documentation) directly at jerome.vuarand@gmail.com.

To subscribe visit the following web page:

http://lists.luaforge.net/mailman/listinfo/luse-users

Credits

This module is written and maintained by Jérôme Vuarand. It is inspired by luafuse module by Gary Ng, but it has been rewritten completely from scratch.

This website, LUSE downloadable packages and LUSE mailing list are generously hosted by Luaforge.net. Consider making a donation.

LUSE is available under a MIT-style license.

2 - Download

LUSE is available on its Luaforge project page.

Latest version is 1.0.2.

3 - Installation

See README.txt inside the LUSE source package. Further installation instruction can be put here on request.

Last update: 2007-09-22 19:02:31-0400


text:
package com.bnsantos.fyber.robolectric;

import org.junit.runners.model.InitializationError;
import org.robolectric.RobolectricGradleTestRunner;

import rx.Scheduler;
import rx.plugins.RxJavaSchedulersHook;
import rx.plugins.RxJavaTestPlugins;
import rx.schedulers.Schedulers;

/**
 * Created by bruno on 22/11/15.
 */
public class RxJavaTestRunner extends RobolectricGradleTestRunner {
    public RxJavaTestRunner(Class<?> klass) throws InitializationError {
        super(klass);

        RxJavaTestPlugins.resetPlugins();
        RxJavaTestPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() {
            @Override
            public Scheduler getIOScheduler() {
                return Schedulers.immediate();
            }
        });
    }
}


text:
package config

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"

	"github.com/Symantec/Dominator/lib/log/testlogger"
)

const simpleValidConfigFile = `base:
    gen_cert_urls: "https://localhost:33443/"
`

const invalidConfigFileNoGenUrls = `base:
	    `

func createTempFileWithStringContent(prefix string, content string) (f *os.File, err error) {
	f, err = ioutil.TempFile("", prefix)
	if err != nil {
		return nil, err
	}

	if _, err = f.Write([]byte(content)); err != nil {
		os.Remove(f.Name())
		return nil, err
	}
	return f, nil
}

func TestLoadVerifyConfigFileSuccess(t *testing.T) {
	tmpfile, err := createTempFileWithStringContent("test_LoadVerifyConfig", simpleValidConfigFile)
	if err != nil {
		t.Fatal(err)
	}

	defer os.Remove(tmpfile.Name()) // clean up

	if err := tmpfile.Close(); err != nil {
		t.Fatal(err)
	}
	_, err = loadVerifyConfigFile(tmpfile.Name())

	if err != nil {
		t.Fatal(err)
	}
	// TODO: validate loaded file contents
}

func TestLoadVerifyConfigFileFailNotYAML(t *testing.T) {
	tmpfile, err := createTempFileWithStringContent("test_LoadVerifyConfigFail_", "Some random string")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(tmpfile.Name()) // clean up
	if err := tmpfile.Close(); err != nil {
		t.Fatal(err)
	}

	_, err = loadVerifyConfigFile(tmpfile.Name())
	if err == nil {
		t.Fatal("Should have failed not a YAML file")
	}
}

func TestLoadVerifyConfigFileFailNoGenCertUrls(t *testing.T) {
	tmpfile, err := createTempFileWithStringContent("test_LoadVerifyConfigFail_", invalidConfigFileNoGenUrls)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(tmpfile.Name()) // clean up
	if err := tmpfile.Close(); err != nil {
		t.Fatal(err)
	}

	_, err = loadVerifyConfigFile(tmpfile.Name())
	if err == nil {
		t.Fatal("Should have failed no genurls in config")
	}
}

func TestLoadVerifyConfigFileFailNoSuchFile(t *testing.T) {
	_, err := loadVerifyConfigFile("NonExistentFile")
	if err == nil {
		t.Fatal("Success on loading Nonexistent File!")
	}

}

func TestGetConfigFromHost(t *testing.T) {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%s", simpleValidConfigFile)
	}))
	defer ts.Close()
	tsURL := ts.URL
	hostname := strings.TrimPrefix(tsURL, "https://")

	tmpfile, err := ioutil.TempFile("", "test_getConfigFromHost_")
	if err != nil {
		t.Fatal(err)
	}

	defer os.Remove(tmpfile.Name()) // clean up

	err = GetConfigFromHost(
		tmpfile.Name(),
		hostname,
		ts.Client(),
		testlogger.New(t))
	if err != nil {
		t.Fatal(err)
	}

	//server.netClient = ts.Client()
	//server.staticConfig.OpenID.TokenURL = ts.URL
}


text:
package org.elasticsearch.river.arangodb.config;

import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeByteValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeDoubleValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeFloatValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeIntegerValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeLongValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeMapValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeShortValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeTimeValue;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Singleton;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.river.RiverSettings;

@Singleton
public class RiverSettingsWrapper {

	private final RiverSettings rs;

	@Inject
	public RiverSettingsWrapper(RiverSettings rs) {
		this.rs = rs;
	}

	public boolean getBool(String path) {
		return nodeBooleanValue(extract(path));
	}

	public boolean getBool(String path, boolean defaultValue) {
		return nodeBooleanValue(extract(path), defaultValue);
	}

	public byte getByte(String path) {
		return nodeByteValue(extract(path));
	}

	public byte getByte(String path, byte defaultValue) {
		return nodeByteValue(extract(path), defaultValue);
	}

	public double getDouble(String path) {
		return nodeDoubleValue(extract(path));
	}

	public double getDouble(String path, byte defaultValue) {
		return nodeDoubleValue(extract(path), defaultValue);
	}

	public float getFloat(String path) {
		return nodeFloatValue(extract(path));
	}

	public float getFloat(String path, byte defaultValue) {
		return nodeFloatValue(extract(path), defaultValue);
	}

	public int getInteger(String path) {
		return nodeIntegerValue(extract(path));
	}

	public int getInteger(String path, int defaultValue) {
		return nodeIntegerValue(extract(path), defaultValue);
	}

	public long getLong(String path) {
		return nodeLongValue(extract(path));
	}

	public long getLong(String path, long defaultValue) {
		return nodeLongValue(extract(path), defaultValue);
	}

	public short getShort(String path) {
		return nodeShortValue(extract(path));
	}

	public short getShort(String path, short defaultValue) {
		return nodeShortValue(extract(path), defaultValue);
	}

	public String getString(String path, String defaultValue) {
		return nodeStringValue(extract(path), defaultValue);
	}

	public TimeValue getTimeValue(String path) {
		return nodeTimeValue(extract(path));
	}

	public TimeValue getTimeValue(String path, TimeValue defaultValue) {
		return nodeTimeValue(extract(path), defaultValue);
	}

	public Map<String, Object> getMap(String path) {
		return getMap(path, Collections.<String, Object> emptyMap());
	}

	public Map<String, Object> getMap(String path, Map<String, Object> defaultValue) {
		Object value = extract(path);
		if (value == null) {
			return defaultValue;
		}
		return nodeMapValue(value, path);
	}

	public List<String> getList(String path) {
		return getList(path, Collections.<String> emptyList());
	}

	@SuppressWarnings("unchecked")
	public List<String> getList(String path, List<String> defaultValue) {
		Object value = extract(path);
		if (value == null) {
			return defaultValue;
		}
		return (List<String>) value;
	}

	public Object extract(String path) {
		return extractValue(path, rs.settings());
	}
}


text:
@implementation MainController

- (void)awakeFromNib
{
	[mainWindow makeKeyAndOrderFront:self];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}

- (void)windowWillClose:(NSNotification *)aNotification
{
	if ([[[aNotification object] frameAutosaveName] isEqualToString:@"mainWindow"])
		[NSApp terminate:self];
}

- (IBAction)showAboutBox:(id)sender
{
	if (!aboutController) {
		aboutController = [[AboutController alloc] init];
	}

	[[aboutController window] makeKeyAndOrderFront:self];
}

- (IBAction)showLicenseInfoWindow:(id)sender
{
	if (!infoController) {
		infoController = [[InfoController alloc] init];
	}
	[infoController showWindow:self];
}

- (IBAction)closeWindow:(id)sender
{
	[[NSApp keyWindow] orderOut:self];
}

- (BOOL)validateMenuItem:(NSMenuItem *)aMenuItem
{
	if ([[aMenuItem title] isEqualToString:@"Close"]) {
		if (![NSApp keyWindow])
			return NO;
	}

	return YES;
}

@end


text:
package xworker.app.monitor;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.xmeta.ActionContext;
import org.xmeta.Bindings;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.util.OgnlUtil;
import org.xmeta.util.UtilData;
import org.xmeta.util.UtilMap;

import ognl.OgnlException;
import xworker.app.monitor.res.MonitorContext;
import xworker.app.monitor.res.ResourceTask;
import xworker.dataObject.DataObject;
import xworker.dataObject.utils.DataObjectUtil;
import xworker.task.NameThreadFactory;

public class MonitorUtils {
	/** 定时任务的执行器 */
	private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(15, new NameThreadFactory("xworker-app-monitor"));
	/** 定期任务缓存 */
	private static Map<String, DataGraberScheduler> dataGrabers = new HashMap<String, DataGraberScheduler>();
	private static Map<String, DataMonitorScheduler> monitorGrabers = new HashMap<String, DataMonitorScheduler>();

	/** 放到资源里的一个键值,表示资源对应的任务数据对象 */
	public static final String resourceTaskKey = "__resource__task__key__";

	/**
	 * 执行一个监控命令。
	 *
	 * @param command
	 */
	public static void execute(Runnable command){
		scheduledExecutorService.execute(command);
	}

	public static void removeDataGraber(Thing thing){
		dataGrabers.remove(thing.getMetadata().getPath());
	}

	public static List<Thing> getDataGrabers(){
		List<Thing> list = new ArrayList<Thing>();
		for(String key : dataGrabers.keySet()){
			list.add(dataGrabers.get(key).thing);
		}

		return list;
	}

	public static List<Thing> getDataMonitors(){
		List<Thing> list = new ArrayList<Thing>();
		for(String key : monitorGrabers.keySet()){
			list.add(monitorGrabers.get(key).thing);
		}

		return list;
	}

	public static ScheduledExecutorService getScheduledExecutorService(){
		return scheduledExecutorService;
	}

	public static void putDataGraber(Thing thing, DataGraberScheduler scheduler){
		dataGrabers.put(thing.getMetadata().getPath(), scheduler);
	}

	public static DataGraberScheduler getDataGraber(Thing thing){
		return dataGrabers.get(thing.getMetadata().getPath());
	}

	public static void removeDataMonitor(Thing thing){
		monitorGrabers.remove(thing.getMetadata().getPath());
	}

	public static void putDataMonitor(Thing thing, DataMonitorScheduler scheduler){
		monitorGrabers.put(thing.getMetadata().getPath(), scheduler);
	}

	public static DataMonitorScheduler getDataMonitor(Thing thing){
		return monitorGrabers.get(thing.getMetadata().getPath());
	}

	/**
	 * 获取从当前起执行任务时应该延迟的时间。
	 *
	 * @param interval
	 * @param delay
	 * @return
	 */
	public static long getDelay(long delay, long interval){
		long current = System.currentTimeMillis();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			current = System.currentTimeMillis() - sf.parse(sf.format(new Date())).getTime();
		} catch (ParseException e) {
		}

		if(current >= delay){
			return current - delay;
		}else{
			long pastTime = delay - current;
			return interval - pastTime % interval;
		}
	}

	/**
	 * 返回当前的抓取时间,统一格式化为整点时间。
	 *
	 * @param delay
	 * @param interval
	 * @return
	 */
	public static Date getCurrentTime(long delay, long interval){
		long current = System.currentTimeMillis();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		long date = 0;
		try {
			date = sf.parse(sf.format(new Date())).getTime();
			current = System.currentTimeMillis() - date - delay;
		} catch (ParseException e) {
		}

		if(interval == 0) {
			interval = 60000;
		}
		return new Date(date + delay + (current / interval) * interval);
	}

	/**
	 * 执行下级资源监控任务。
	 *
	 * @param actionContext
	 * @throws OgnlException
	 */
	@SuppressWarnings("unchecked")
	public static void executeSubResTasks(DataObject resuourceItem, ActionContext actionContext) throws OgnlException{
		DataObject monitorTask = (DataObject) actionContext.get("monitorTask");
		MonitorContext monitorContext = (MonitorContext) actionContext.get("monitorContext");

		List<DataObject> subTasks = DataObjectUtil.query("xworker.app.monitor.dataobjects.ResMonitorTaskItems",
				UtilMap.toMap("parentId", monitorTask.get("id")), actionContext);
		for(DataObject subTask : subTasks){
			List<DataObject> resources = null;
			if(resuourceItem != null){
				resources = new ArrayList<DataObject>();
				resources.add(resuourceItem);
			}else{
				resources = DataObjectUtil.query("xworker.app.monitor.dataobjects.ResMonitorResItems",
						 UtilMap.toMap("taskId", subTask.get("id"), "status", 1), actionContext);
			}

			DataObject task = new DataObject("xworker.app.monitor.dataobjects.ResMonitorTasks");
			task.put("id", subTask.get("taskId"));
			task = task.load(actionContext);
			if(task != null){
				Bindings parentBindings = actionContext.peek();
				String preCondition = subTask.getString("preCondition");
				if(subTask.getBoolean("perRowExecute")){
					List<Map<String, Object>> vlist = (List<Map<String, Object>>) parentBindings.get("vlist");
					if(vlist != null){
						for(Map<String, Object> values : vlist){
							Bindings bindings = new Bindings();
							bindings.putAll(parentBindings);
							bindings.putAll(values);
							bindings.put("v", values);

							try{
								actionContext.push(bindings);
								if(preCondition == null || "".equals(preCondition)
										|| UtilData.getBoolean(OgnlUtil.getValue(preCondition, actionContext), false)){
									ResourceTask dbTask = new ResourceTask(monitorContext, actionContext, monitorContext.monitor, subTask, task, resources);
								    dbTask.paramBindings = bindings;
								    MonitorUtils.execute(dbTask);
								}
							}finally{
								actionContext.pop();
							}
						}
					}
				}else{
					if(preCondition == null || "".equals(preCondition)
							|| UtilData.getBoolean(OgnlUtil.getValue(preCondition, actionContext), false)){
						ResourceTask dbTask = new ResourceTask(monitorContext, actionContext, monitorContext.monitor, subTask, task, resources);
					    dbTask.paramBindings = parentBindings;
					    MonitorUtils.execute(dbTask);
					}
				}

			}
		}
	}

	/**
	 * 保存监控数据的一个公共方法。
	 *
	 * @param monitorContext 监控上下文,用于获取监控的定义和监控的起始时间等
	 * @param monitorTask 监控任务定义
	 * @param monitorTaskResource 监控任务对应的资源定义
	 * @param taskThing 监控任务事物
	 * @param resourceId 监控资源标识
	 * @param columnMappings 数据列的映射
	 * @param rowIdIndex 每行数据的标识列索引,在返回的二维表格数据中可以作为标识的列索引
	 * @param listDatas 要保存的数据,是二维表格数据
	 */
	public static void saveMonitorData(MonitorContext monitorContext, DataObject monitorTask,
			DataObject monitorTaskResource, Thing taskThing, Object resourceId,
			String[] columnMappings, int rowIdIndex, List<Map<String, Object>> listDatas){
		if(columnMappings != null){
			String[] dts = columnMappings;

			for(Map<String, Object> values : listDatas){
				for(int i=0; i<dts.length; i++){
					if(!"".equals(dts[i])){
						DataObject data = new DataObject("xworker.app.monitor.dataobjects.MonitorData");
						data.put("taskThingPath", taskThing.getMetadata().getPath());
						data.put("resourceId", resourceId);
						data.put("dataName", dts[i]);
						data.put("value", values.get("v" + (i + 1)));
						data.put("grabStartTime", monitorContext.getStartTime());
						data.put("grabEndTime", new Date());
						data.put("monitorId", monitorContext.monitor.get("id"));
						data.put("monitorTaskId", monitorTask.get("id"));
						data.put("monitorTaskResId", monitorTaskResource.get("id"));
						if(rowIdIndex > 0){
							data.put("dataId", values.get("v" + rowIdIndex));
						}

						MonitorDataSaveTask.addCreateData(data);
					}
				}
			}
		}
	}

	/**
	 * 处理字符串类型的数据方法,包含了分析数据为vlist和vmap,保存数据,执行子任务等功能。
	 *
	 * @param result 字符串表示的值
	 * @param dataNames 数据列的名字映射,要保存的数据在这里
	 * @param saveMontiorData 是否保存监控数据
	 * @param multiLine 是否是多行数据
	 * @param dataIdIndex 数据标识列的索引
	 *
	 * @param actionContext 动作上下文
	 * @throws OgnlException
	 */
	public static void handleStringResult(String result, String splitStr, String lineSplitStr, String dataNames, boolean saveMontiorData, boolean multiLine, int dataIdIndex, String resourceId, ActionContext actionContext) throws OgnlException{
		DataObject monitorTask = (DataObject) actionContext.get("monitorTask");
		DataObject monitorTaskResource = (DataObject) actionContext.get("monitorTaskResource");
		MonitorContext monitorContext = (MonitorContext) actionContext.get("monitorContext");
		Thing taskThing = (Thing) actionContext.get("taskThing");

		Map<String, Map<String, Object>> mapDatas = new HashMap<String, Map<String, Object>>();
		List<Map<String, Object>> listDatas = new ArrayList<Map<String, Object>>();
		actionContext.peek().put("vmap", mapDatas);
		actionContext.peek().put("vlist", listDatas);

		String[] columnMappings = null;
		if(dataNames != null && !"".equals(dataNames)){
			columnMappings = dataNames.split("[,]");
		}

		//转化数据到List和Map
		if(lineSplitStr == null || "".equals(lineSplitStr)){
			lineSplitStr = "\n";
		}

		if(result != null){
			String[] rows = null;
			if(multiLine){
				rows = result.split("[" + lineSplitStr + "]");
			}else{
				rows = new String[]{result};
			}

			int rowIndex = 1;
			for(String row : rows){
				String rs[] = row.split("[" + splitStr + "]");

				Map<String, Object> values = new HashMap<String, Object>();
				for(int i=0; i<rs.length; i++){
					Object value = rs[i].trim();
					try{
						//尝试转化为数字
						value = NumberFormat.getNumberInstance().parse(rs[i].trim());
					}catch(Exception e){
					}

					values.put("v" + (i + 1), value);
					if(columnMappings != null && columnMappings.length > i){
						String name = columnMappings[i];
						if(name != null && !"".equals(name)){
							values.put(name, value);
						}
					}

					actionContext.peek().put("v" + (i + 1), value);
				}

				listDatas.add(values);
				mapDatas.put("r" + rowIndex, values);
				if(dataIdIndex > 0 && dataIdIndex < rs.length){
					mapDatas.put(rs[dataIdIndex], values);
				}

				rowIndex++;
			}
		}

		//是否保存监控数据
		if(saveMontiorData){
			MonitorUtils.saveMonitorData(monitorContext, monitorTask, monitorTaskResource, taskThing,
					resourceId, columnMappings, dataIdIndex, listDatas);
		}

		//执行子任务
		if(monitorTask.getBoolean("childSameRes")){
			MonitorUtils.executeSubResTasks(monitorTaskResource, actionContext);
		}else{
			MonitorUtils.executeSubResTasks(null, actionContext);
		}
	}

	/**
	 * 通过资源数据对象装载资源。
	 *
	 * @param monitorTaskResource
	 * @param actionContext
	 * @return
	 */
	public static Object loadResource(DataObject monitorTaskResource, ActionContext actionContext){
		DataObject task = (DataObject) monitorTaskResource.get(MonitorUtils.resourceTaskKey);
		if(task != null){
			Thing taskThing = World.getInstance().getThing(task.getString("taskPath"));
			if(taskThing != null){
				return taskThing.doAction("loadResource", actionContext, UtilMap.toMap("resource", monitorTaskResource));
			}
		}

		return null;
	}
}