text:
package Paws::SES::DescribeActiveReceiptRuleSet;
  use Moose;

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeActiveReceiptRuleSet');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SES::DescribeActiveReceiptRuleSetResponse');
  class_has _result_key => (isa => 'Str', is => 'ro', default => 'DescribeActiveReceiptRuleSetResult');
1;

### main pod documentation begin ###

=head1 NAME

Paws::SES::DescribeActiveReceiptRuleSet - Arguments for method DescribeActiveReceiptRuleSet on Paws::SES

=head1 DESCRIPTION

This class represents the parameters used for calling the method DescribeActiveReceiptRuleSet on the
Amazon Simple Email Service service. Use the attributes of this class
as arguments to method DescribeActiveReceiptRuleSet.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeActiveReceiptRuleSet.

As an example:

  $service_obj->DescribeActiveReceiptRuleSet(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method DescribeActiveReceiptRuleSet in L<Paws::SES>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
namespace MOE.Common.Models.Repositories
{
    public class MeasuresDefaultsRepositoryFactory
    {
        private static IMeasuresDefaultsRepository measuresDefaultsRepository;

        public static IMeasuresDefaultsRepository Create()
        {
            if (measuresDefaultsRepository != null)
                return measuresDefaultsRepository;
            return new MeasuresDefaultsRepository();
        }

        public static IMeasuresDefaultsRepository Create(SPM context)
        {
            if (measuresDefaultsRepository != null)
                return measuresDefaultsRepository;
            return new MeasuresDefaultsRepository(context);
        }

        public static void SetMeasuresDefaultsRepository(IMeasuresDefaultsRepository newRepository)
        {
            measuresDefaultsRepository = newRepository;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using Crownwood.Magic.Collections;
using Crownwood.Magic.Menus;

namespace Crownwood.Magic.Collections
{
    public class MenuCommandCollection : CollectionWithEvents
    {
        // Instance fields
        protected string _extraText;
        protected Font _extraFont;
        protected Color _extraTextColor;
        protected Brush _extraTextBrush;
        protected Color _extraBackColor;
        protected Brush _extraBackBrush;
        protected bool _showInfrequent;

        public MenuCommandCollection()
        {
            // Define defaults for internal state
            _extraText = "";
            _extraFont = SystemInformation.MenuFont;
            _extraTextColor = SystemColors.ActiveCaptionText;
            _extraTextBrush = null;
            _extraBackColor = SystemColors.ActiveCaption;
            _extraBackBrush = null;
            _showInfrequent = false;
        }

        public MenuCommand Add(MenuCommand value)
        {
            // Use base class to process actual collection operation
            base.List.Add(value as object);

            return value;
        }

        public void AddRange(MenuCommand[] values)
        {
            // Use existing method to add each array entry
            foreach(MenuCommand page in values)
                Add(page);
        }

        public void Remove(MenuCommand value)
        {
            // Use base class to process actual collection operation
            base.List.Remove(value as object);
        }

        public void Insert(int index, MenuCommand value)
        {
            // Use base class to process actual collection operation
            base.List.Insert(index, value as object);
        }

        public bool Contains(MenuCommand value)
        {
            // Use base class to process actual collection operation
            return base.List.Contains(value as object);
        }

        public MenuCommand this[int index]
        {
            // Use base class to process actual collection operation
            get { return (base.List[index] as MenuCommand); }
        }

        public MenuCommand this[string text]
        {
            get
            {
                // Search for a MenuCommand with a matching title
                foreach(MenuCommand mc in base.List)
                    if (mc.Text == text)
                        return mc;

                return null;
            }
        }

        public int IndexOf(MenuCommand value)
        {
            // Find the 0 based index of the requested entry
            return base.List.IndexOf(value);
        }

        public bool VisibleItems()
        {
            foreach(MenuCommand mc in base.List)
            {
                // Is the item visible?
                if (mc.Visible)
                {
                    // And its not a separator...
                    if (mc.Text != "-")
                    {
                        // Then should return 'true' except when we are a sub menu item ourself
                        // in which case there might not be any visible children which means that
                        // this item would not be visible either.
                        if ((mc.MenuCommands.Count > 0) && (!mc.MenuCommands.VisibleItems()))
                            continue;

                        return true;
                    }
                }
            }

            return false;
        }

        public string ExtraText
        {
            get { return _extraText; }
            set { _extraText = value; }
        }

        public Font ExtraFont
        {
            get { return _extraFont; }
            set { _extraFont = value; }
        }

        public Color ExtraTextColor
        {
            get { return _extraTextColor; }
            set { _extraTextColor = value; }
        }

        public Brush ExtraTextBrush
        {
            get { return _extraTextBrush; }
            set { _extraTextBrush = value; }
        }

        public Color ExtraBackColor
        {
            get { return _extraBackColor; }
            set { _extraBackColor = value; }
        }

        public Brush ExtraBackBrush
        {
            get { return _extraBackBrush; }
            set { _extraBackBrush = value; }
        }

        public bool ShowInfrequent
        {
            get { return _showInfrequent; }
            set { _showInfrequent = value; }
        }
    }
}


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

<title>CCMBlockCipher (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.crypto.modes

Class CCMBlockCipher

java.lang.Object

org.bouncycastle.crypto.modes.CCMBlockCipher

All Implemented Interfaces:

AEADBlockCipher

public class CCMBlockCipher
extends java.lang.Object
implements AEADBlockCipher

Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
 NIST Special Publication 800-38C.

 Note: this mode is a packet mode - it needs all the data up front.

Constructor Summary

Constructors

Constructor and Description

CCMBlockCipher(BlockCipher c)

Basic constructor.

Method Summary

Methods

Modifier and Type
Method and Description

int
doFinal(byte[] out,
       int outOff)

Finish the operation either appending or verifying the MAC at the end of the data.

java.lang.String
getAlgorithmName()

Return the name of the algorithm.

byte[]
getMac()

Returns a byte array containing the mac calculated as part of the
 last encrypt or decrypt operation.

int
getOutputSize(int len)

return the size of the output buffer required for a processBytes plus a
 doFinal with an input of len bytes.

BlockCipher
getUnderlyingCipher()

return the underlying block cipher that we are wrapping.

int
getUpdateOutputSize(int len)

return the size of the output buffer required for a processBytes
 an input of len bytes.

void
init(boolean forEncryption,
    CipherParameters params)

initialise the underlying cipher.

void
processAADByte(byte in)

Add a single byte to the associated data check.

void
processAADBytes(byte[] in,
               int inOff,
               int len)

Add a sequence of bytes to the associated data check.

int
processByte(byte in,
           byte[] out,
           int outOff)

encrypt/decrypt a single byte.

int
processBytes(byte[] in,
            int inOff,
            int inLen,
            byte[] out,
            int outOff)

process a block of bytes from in putting the result into out.

byte[]
processPacket(byte[] in,
             int inOff,
             int inLen)

Process a packet of data for either CCM decryption or encryption.

int
processPacket(byte[] in,
             int inOff,
             int inLen,
             byte[] output,
             int outOff)

Process a packet of data for either CCM decryption or encryption.

void
reset()

Reset the cipher.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CCMBlockCipher

public CCMBlockCipher(BlockCipher c)

Basic constructor.

Parameters:

c - the block cipher to be used.

Method Detail

getUnderlyingCipher

public BlockCipher getUnderlyingCipher()

return the underlying block cipher that we are wrapping.

Specified by:

getUnderlyingCipher in interface AEADBlockCipher

Returns:

the underlying block cipher that we are wrapping.

init

public void init(boolean forEncryption,
        CipherParameters params)
          throws java.lang.IllegalArgumentException

Description copied from interface: AEADBlockCipher

initialise the underlying cipher. Parameter can either be an AEADParameters or a ParametersWithIV object.

Specified by:

init in interface AEADBlockCipher

Parameters:

forEncryption - true if we are setting up for encryption, false otherwise.

params - the necessary parameters for the underlying cipher to be initialised.

Throws:

java.lang.IllegalArgumentException - if the params argument is inappropriate.

getAlgorithmName

public java.lang.String getAlgorithmName()

Description copied from interface: AEADBlockCipher

Return the name of the algorithm.

Specified by:

getAlgorithmName in interface AEADBlockCipher

Returns:

the algorithm name.

processAADByte

public void processAADByte(byte in)

Description copied from interface: AEADBlockCipher

Add a single byte to the associated data check.

If the implementation supports it, this will be an online operation and will not retain the associated data.

Specified by:

processAADByte in interface AEADBlockCipher

Parameters:

in - the byte to be processed.

processAADBytes

public void processAADBytes(byte[] in,
                   int inOff,
                   int len)

Description copied from interface: AEADBlockCipher

Add a sequence of bytes to the associated data check.

If the implementation supports it, this will be an online operation and will not retain the associated data.

Specified by:

processAADBytes in interface AEADBlockCipher

Parameters:

in - the input byte array.

inOff - the offset into the in array where the data to be processed starts.

len - the number of bytes to be processed.

processByte

public int processByte(byte in,
              byte[] out,
              int outOff)
                throws DataLengthException,
                       java.lang.IllegalStateException

Description copied from interface: AEADBlockCipher

encrypt/decrypt a single byte.

Specified by:

processByte in interface AEADBlockCipher

Parameters:

in - the byte to be processed.

out - the output buffer the processed byte goes into.

outOff - the offset into the output byte array the processed data starts at.

Returns:

the number of bytes written to out.

Throws:

DataLengthException - if the output buffer is too small.

java.lang.IllegalStateException

processBytes

public int processBytes(byte[] in,
               int inOff,
               int inLen,
               byte[] out,
               int outOff)
                 throws DataLengthException,
                        java.lang.IllegalStateException

Description copied from interface: AEADBlockCipher

process a block of bytes from in putting the result into out.

Specified by:

processBytes in interface AEADBlockCipher

Parameters:

in - the input byte array.

inOff - the offset into the in array where the data to be processed starts.

inLen - the number of bytes to be processed.

out - the output buffer the processed bytes go into.

outOff - the offset into the output byte array the processed data starts at.

Returns:

the number of bytes written to out.

Throws:

DataLengthException - if the output buffer is too small.

java.lang.IllegalStateException

doFinal

public int doFinal(byte[] out,
          int outOff)
            throws java.lang.IllegalStateException,
                   InvalidCipherTextException

Description copied from interface: AEADBlockCipher

Finish the operation either appending or verifying the MAC at the end of the data.

Specified by:

doFinal in interface AEADBlockCipher

Parameters:

out - space for any resulting output data.

outOff - offset into out to start copying the data at.

Returns:

number of bytes written into out.

Throws:

java.lang.IllegalStateException - if the cipher is in an inappropriate state.

InvalidCipherTextException - if the MAC fails to match.

reset

public void reset()

Description copied from interface: AEADBlockCipher

Reset the cipher. After resetting the cipher is in the same state
 as it was after the last init (if there was one).

Specified by:

reset in interface AEADBlockCipher

getMac

public byte[] getMac()

Returns a byte array containing the mac calculated as part of the
 last encrypt or decrypt operation.

Specified by:

getMac in interface AEADBlockCipher

Returns:

the last mac calculated.

getUpdateOutputSize

public int getUpdateOutputSize(int len)

Description copied from interface: AEADBlockCipher

return the size of the output buffer required for a processBytes
 an input of len bytes.

 The returned size may be dependent on the initialisation of this cipher
 and may not be accurate once subsequent input data is processed - this method
 should be invoked immediately prior to input data being processed.

Specified by:

getUpdateOutputSize in interface AEADBlockCipher

Parameters:

len - the length of the input.

Returns:

the space required to accommodate a call to processBytes
 with len bytes of input.

getOutputSize

public int getOutputSize(int len)

Description copied from interface: AEADBlockCipher

return the size of the output buffer required for a processBytes plus a
 doFinal with an input of len bytes.

 The returned size may be dependent on the initialisation of this cipher
 and may not be accurate once subsequent input data is processed - this method
 should be invoked immediately prior to a call to final processing of input data
 and a call to AEADBlockCipher.doFinal(byte[], int).

Specified by:

getOutputSize in interface AEADBlockCipher

Parameters:

len - the length of the input.

Returns:

the space required to accommodate a call to processBytes and doFinal
 with len bytes of input.

processPacket

public byte[] processPacket(byte[] in,
                   int inOff,
                   int inLen)
                     throws java.lang.IllegalStateException,
                            InvalidCipherTextException

Process a packet of data for either CCM decryption or encryption.

Parameters:

in - data for processing.

inOff - offset at which data starts in the input array.

inLen - length of the data in the input array.

Returns:

a byte array containing the processed input..

Throws:

java.lang.IllegalStateException - if the cipher is not appropriately set up.

InvalidCipherTextException - if the input data is truncated or the mac check fails.

processPacket

public int processPacket(byte[] in,
                int inOff,
                int inLen,
                byte[] output,
                int outOff)
                  throws java.lang.IllegalStateException,
                         InvalidCipherTextException,
                         DataLengthException

Process a packet of data for either CCM decryption or encryption.

Parameters:

in - data for processing.

inOff - offset at which data starts in the input array.

inLen - length of the data in the input array.

output - output array.

outOff - offset into output array to start putting processed bytes.

Returns:

the number of bytes added to output.

Throws:

java.lang.IllegalStateException - if the cipher is not appropriately set up.

InvalidCipherTextException - if the input data is truncated or the mac check fails.

DataLengthException - if output buffer too short.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="lang:clipboard.copy" content="Copy to clipboard">
  <meta name="lang:clipboard.copied" content="Copied to clipboard">
  <meta name="lang:search.language" content="en">
  <meta name="lang:search.pipeline.stopwords" content="True">
  <meta name="lang:search.pipeline.trimmer" content="True">
  <meta name="lang:search.result.none" content="No matching documents">
  <meta name="lang:search.result.one" content="1 matching document">
  <meta name="lang:search.result.other" content="# matching documents">
  <meta name="lang:search.tokenizer" content="[\s\-]+">

    <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">

  <link rel="stylesheet" href="_static/stylesheets/application.css"/>
  <link rel="stylesheet" href="_static/stylesheets/application-palette.css"/>
  <link rel="stylesheet" href="_static/stylesheets/application-fixes.css"/>

  <link rel="stylesheet" href="_static/fonts/material-icons.css"/>

  <meta name="theme-color" content="#3f51b5">

    <title>Distributions — statsmodels</title>
  <link rel="icon" type="image/png" sizes="32x32" href="_static/icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="_static/icons/favicon-16x16.png">
  <link rel="manifest" href="_static/icons/site.webmanifest">
  <link rel="mask-icon" href="_static/icons/safari-pinned-tab.svg" color="#919191">
  <meta name="msapplication-TileColor" content="#2b5797">
  <meta name="msapplication-config" content="_static/icons/browserconfig.xml">
  <link rel="stylesheet" href="_static/stylesheets/examples.css">
  <link rel="stylesheet" href="_static/stylesheets/deprecation.css">
    <link rel="stylesheet" href="_static/material.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="_static/graphviz.css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="statsmodels.distributions.empirical_distribution.ECDF" href="generated/statsmodels.distributions.empirical_distribution.ECDF.html" />
    <link rel="prev" title="statsmodels.emplike.descriptive.DescStatMV.test_corr" href="generated/statsmodels.emplike.descriptive.DescStatMV.test_corr.html" />

  <svg class="md-svg">
    <defs data-children-count="0">

      <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>

    </defs>
  </svg>

  <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
  <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">

   Skip to content

          statsmodels v0.12.1
           Distributions

    <form class="md-search__form" action="search.html" method="GET" name="search">
      <input type="text" class="md-search__input" name="q" placeholder="Search"
             autocapitalize="off" autocomplete="off" spellcheck="false"
             data-md-component="query" data-md-state="active">

      <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">
        
      </button>
    </form>

            Type to start searching

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

User Guide

    statsmodels v0.12.1

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

      Installing statsmodels

      Getting started

      User Guide

      Background

      Regression and Linear Models

      Time Series Analysis

      Other Models

      Statistics and Tools

      Statistics stats

      Contingency tables

      Multiple Imputation with Chained Equations

      Empirical Likelihood emplike

    <input class="md-toggle md-nav__toggle" data-md-toggle="toc" type="checkbox" id="__toc">
     Distributions

      Distributions

    Contents

Distributions

Empirical Distributions

Distribution Extras

Univariate Distributions by non-linear Transformations

Show Source

      Graphics

      Input-Output iolib

      Tools

      Working with Large Data Sets

      Optimization

      Data Sets

      Sandbox

      Examples

      API Reference

      About statsmodels

      Developer Page

      Release Notes

    Contents

Distributions

Empirical Distributions

Distribution Extras

Univariate Distributions by non-linear Transformations

Show Source

Distributions¶

This section collects various additional functions and methods for statistical
distributions.

Empirical Distributions¶

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

ECDF(x[, side])

Return the Empirical CDF of an array as a step function.

StepFunction(x, y[, ival, sorted, side])

A basic step function.

monotone_fn_inverter(fn, x[, vectorized])

Given a monotone function fn (no checking is done to verify monotonicity) and a set of x values, return an linearly interpolated approximation to its inverse from its values on x.

Distribution Extras¶

Skew Distributions

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

SkewNorm_gen()

univariate Skew-Normal distribution of Azzalini

SkewNorm2_gen([momtype, a, b, xtol, …])

univariate Skew-Normal distribution of Azzalini

ACSkewT_gen()

univariate Skew-T distribution of Azzalini

skewnorm2

univariate Skew-Normal distribution of Azzalini

Distributions based on Gram-Charlier expansion

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

pdf_moments_st(cnt)

Return the Gaussian expanded pdf function given the list of central moments (first one is mean).

pdf_mvsk(mvsk)

Return the Gaussian expanded pdf function given the list of 1st, 2nd moment and skew and Fisher (excess) kurtosis.

pdf_moments(cnt)

Return the Gaussian expanded pdf function given the list of central moments (first one is mean).

NormExpan_gen(args, **kwds)

Gram-Charlier Expansion of Normal distribution

cdf of multivariate normal wrapper for scipy.stats

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

mvstdnormcdf(lower, upper, corrcoef, **kwds)

standardized multivariate normal cumulative distribution function

mvnormcdf(upper, mu, cov[, lower])

multivariate normal cumulative distribution function

Univariate Distributions by non-linear Transformations¶

Univariate distributions can be generated from a non-linear transformation of an
existing univariate distribution. Transf_gen is a class that can generate a new
distribution from a monotonic transformation, TransfTwo_gen can use hump-shaped
or u-shaped transformation, such as abs or square. The remaining objects are
special cases.

<colgroup>
<col style="width: 10%"/>
<col style="width: 90%"/>
</colgroup>

TransfTwo_gen(kls, func, funcinvplus, …)

Distribution based on a non-monotonic (u- or hump-shaped transformation)

Transf_gen(kls, func, funcinv, *args, **kwargs)

a class for non-linear monotonic transformation of a continuous random variable

ExpTransf_gen(kls, *args, **kwargs)

Distribution based on log/exp transformation

LogTransf_gen(kls, *args, **kwargs)

Distribution based on log/exp transformation

SquareFunc()

class to hold quadratic function with inverse function and derivative

absnormalg

Distribution based on a non-monotonic (u- or hump-shaped transformation)

invdnormalg

a class for non-linear monotonic transformation of a continuous random variable

loggammaexpg

univariate distribution of a non-linear monotonic transformation of a random variable

lognormalg

a class for non-linear monotonic transformation of a continuous random variable

negsquarenormalg

Distribution based on a non-monotonic (u- or hump-shaped transformation)

squarenormalg

Distribution based on a non-monotonic (u- or hump-shaped transformation)

squaretg

Distribution based on a non-monotonic (u- or hump-shaped transformation)

                   Previous  statsmodels.emplike.descriptive.DescStatMV.test_corr

  Next  statsmodels.distributions.empirical_distribution.ECDF

              © Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.

            Last updated on
              Oct 29, 2020.

            Created using
            Sphinx 3.2.1.
             and
            Material for
              Sphinx


text:
export const WEB_SOCKET_URL = 'http://socket.ricardolino.com.br/';

class WebSocketUtils {
    static onEvent (socket, event, callback) {
        if (!socket._callbacks[`$${event}`]) {
            socket.on(`${event}`, (data) => {
                callback(data);
            })
        }
    }
}

export default WebSocketUtils;


text:
require 'tempfile'

describe Dotum::Util::Path, '#write' do
  include_context 'path fixtures'

  let(:tempfile) { Tempfile.new('writer') }

  subject do
    described_class.new(tempfile.path)
  end

  it 'should write to a file' do
    subject.write('ohai')
    expect(subject.read).to eq('ohai')
  end

  it 'should not append to a file' do
    subject.write('one')
    subject.write('two')
    expect(subject.read).to eq('two')
  end

end


text:
<?php

namespace app\components;

use yii\web\Request;
use yii\web\UrlManager;
use yii\web\UrlRuleInterface;
use yii\base\Object;

class NewwsUrlRule extends Object implements UrlRuleInterface{

    public function createUrl($manager, $route, $params){
        if($route === 'newws/item-detail'){
            if(isset($params['title'])){
                return 'newws/' . $params['title'];
            }
        }
        return false;
    }

    public function parseRequest($manager, $request){
        $pathInfo = $request->getPathInfo();
        if (preg_match('%^([^\/]*)\/([^\/]*)$%', $pathInfo, $matches)) {
            if($matches[1] == 'newws'){
                $params = ['title' => $matches[2]];
                return ['newws/item-detail',$params];
            }else{
                return false;
            }
        }
        return false;
    }

}


text:
test_name 'C3491 - checkout as a group (https protocol)'

# Globals
repo_name = 'testrepo_group_checkout'
group = 'mygroup'

hosts.each do |host|
  ruby = (host.is_pe? && '/opt/puppet/bin/ruby') || 'ruby'
  tmpdir = host.tmpdir('vcsrepo')
  step 'setup - create repo' do
    git_pkg = 'git'
    if host['platform'] =~ /ubuntu-10/
      git_pkg = 'git-core'
    end
    install_package(host, git_pkg)
    my_root = File.expand_path(File.join(File.dirname(__FILE__), '../../../..'))
    scp_to(host, "#{my_root}/acceptance/files/create_git_repo.sh", tmpdir)
    on(host, "cd #{tmpdir} && ./create_git_repo.sh")
  end
  step 'setup - start https server' do
    https_daemon =<<-EOF
    require 'webrick'
    require 'webrick/https'
    server = WEBrick::HTTPServer.new(
    :Port               => 8443,
    :DocumentRoot       => "#{tmpdir}",
    :SSLEnable          => true,
    :SSLVerifyClient    => OpenSSL::SSL::VERIFY_NONE,
    :SSLCertificate     => OpenSSL::X509::Certificate.new(  File.open("#{tmpdir}/server.crt").read),
    :SSLPrivateKey      => OpenSSL::PKey::RSA.new(          File.open("#{tmpdir}/server.key").read),
    :SSLCertName        => [ [ "CN",WEBrick::Utils::getservername ] ])
    WEBrick::Daemon.start
    server.start
    EOF
    create_remote_file(host, '/tmp/https_daemon.rb', https_daemon)
    #on(host, "#{ruby} /tmp/https_daemon.rb")
  end

  step 'setup - create group' do
    apply_manifest_on(host, "group { '#{group}': ensure => present, }", :catch_failures => true)
  end

  teardown do
    on(host, "rm -fr #{tmpdir}")
    on(host, "ps ax | grep '#{ruby} /tmp/https_daemon.rb' | grep -v grep | awk '{print \"kill -9 \" $1}' | sh ; sleep 1")
    apply_manifest_on(host, "group { '#{group}': ensure => absent, }", :catch_failures => true)
  end

  step 'checkout as a group with puppet' do
    pp = <<-EOS
    vcsrepo { "#{tmpdir}/#{repo_name}":
      ensure => present,
      source => "https://github.com/johnduarte/testrepo.git",
      provider => git,
      group => '#{group}',
    }
    EOS

    apply_manifest_on(host, pp, :catch_failures => true)
    apply_manifest_on(host, pp, :catch_changes  => true)
  end

  step "verify git checkout is own by group #{group}" do
    on(host, "ls #{tmpdir}/#{repo_name}/.git/") do |res|
      fail_test('checkout not found') unless res.stdout.include? "HEAD"
    end

    on(host, "stat --format '%U:%G' #{tmpdir}/#{repo_name}/.git/HEAD") do |res|
      fail_test('checkout not owned by group') unless res.stdout.include? ":#{group}"
    end
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    tools:context="de.hpi.placerecognizer.MainActivity"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <de.hpi.placerecognizer.AutoFitTextureView
        android:id="@+id/texture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:srcCompat="@android:drawable/ic_menu_camera"
        app:backgroundTint="@android:color/holo_red_dark"
        android:layout_marginLeft="@dimen/fab_margin"
        android:layout_marginRight="@dimen/fab_margin"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="15dp" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/tts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:srcCompat="@android:drawable/ic_lock_silent_mode_off"
        app:backgroundTint="@android:color/holo_red_dark"
        android:layout_alignTop="@+id/camera"
        android:layout_toStartOf="@+id/camera"
        android:layout_marginEnd="33dp" />

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/tts"
        android:layout_alignParentStart="true"
        android:layout_marginStart="14dp"
        android:id="@+id/classDisplay"
        android:layout_alignBottom="@+id/texture" />

</RelativeLayout>


text:
{% macro member_badge(member, chairperson=False) -%}
  {%- if member.profile_pic_url %}

  {% else %}

No image available

  {% endif %}

{{ member.name }}

  {% if chairperson %}

Chairperson

  {% endif %}
  {% if member.party %}
    {{ member.party.name }}
  {% endif %}
{%- endmacro %}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="ukelonn.bundle">

    <!-- Copyright 2016-2022 Steinar Bang                                                -->
    <!--                                                                                -->
    <!-- Licensed under the Apache License, Version 2.0 (the "License");                 -->
    <!-- you may not use this file except in compliance with the License.                -->
    <!-- You may obtain a copy of the License at                                         -->
    <!--   http://www.apache.org/licenses/LICENSE-2.0                                    -->
    <!-- Unless required by applicable law or agreed to in writing,                      -->
    <!-- software distributed under the License is distributed on an "AS IS" BASIS,      -->
    <!-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.        -->
    <!-- See the License for the specific language governing permissions and limitations -->
    <!-- under the License.                                                              -->

    <feature name="ukelonn-web-security">
        <feature>http-whiteboard</feature>
        <feature>scr</feature>
        <feature>commons-beanutils</feature>
    </feature>
</features>


text:
package esutil

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"runtime"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/elastic/go-elasticsearch/v8/esapi"
)

// BulkIndexer represents a parallel, asynchronous, efficient indexer for Elasticsearch.
type BulkIndexer interface {
	// Add adds an item to the indexer. It returns an error when the item cannot be added.
	// Use the OnSuccess and OnFailure callbacks to get the operation result for the item.
	//
	// You must call the Close() method after you're done adding items.
	//
	// It is safe for concurrent use. When it's called from goroutines,
	// they must finish before the call to Close, eg. using sync.WaitGroup.
	Add(context.Context, BulkIndexerItem) error

	// Close waits until all added items are flushed and closes the indexer.
	Close(context.Context) error

	// Stats returns indexer statistics.
	Stats() BulkIndexerStats
}

// BulkIndexerConfig represents configuration of the indexer.
type BulkIndexerConfig struct {
	NumWorkers    int           // The number of workers. Defaults to runtime.NumCPU().
	FlushBytes    int           // The flush threshold in bytes. Defaults to 5MB.
	FlushInterval time.Duration // The flush threshold as duration. Defaults to 30sec.

	Client      *elasticsearch.Client   // The Elasticsearch client.
	Decoder     BulkResponseJSONDecoder // A custom JSON decoder.
	DebugLogger BulkIndexerDebugLogger  // An optional logger for debugging.

	OnError      func(context.Context, error)          // Called for indexer errors.
	OnFlushStart func(context.Context) context.Context // Called when the flush starts.
	OnFlushEnd   func(context.Context)                 // Called when the flush ends.

	// Parameters of the Bulk API.
	Index               string
	ErrorTrace          bool
	FilterPath          []string
	Header              http.Header
	Human               bool
	Pipeline            string
	Pretty              bool
	Refresh             string
	Routing             string
	Source              []string
	SourceExcludes      []string
	SourceIncludes      []string
	Timeout             time.Duration
	WaitForActiveShards string
}

// BulkIndexerStats represents the indexer statistics.
type BulkIndexerStats struct {
	NumAdded    uint64
	NumFlushed  uint64
	NumFailed   uint64
	NumIndexed  uint64
	NumCreated  uint64
	NumUpdated  uint64
	NumDeleted  uint64
	NumRequests uint64
}

// BulkIndexerItem represents an indexer item.
type BulkIndexerItem struct {
	Index           string
	Action          string
	DocumentID      string
	Routing         string
	Version         *int64
	VersionType     string
	Body            io.ReadSeeker
	RetryOnConflict *int
	meta            bytes.Buffer // Item metadata header
	payloadLength   int          // Item payload total length metadata+newline+body length

	OnSuccess func(context.Context, BulkIndexerItem, BulkIndexerResponseItem)        // Per item
	OnFailure func(context.Context, BulkIndexerItem, BulkIndexerResponseItem, error) // Per item
}

// marshallMeta format as JSON the item metadata.
func (item *BulkIndexerItem) marshallMeta() {
	var aux []byte
	item.meta.WriteRune('{')
	aux = strconv.AppendQuote(aux, item.Action)
	item.meta.Write(aux)
	aux = nil
	item.meta.WriteRune(':')
	item.meta.WriteRune('{')
	if item.DocumentID != "" {
		item.meta.WriteString(`"_id":`)
		aux = strconv.AppendQuote(aux, item.DocumentID)
		item.meta.Write(aux)
		aux = nil
	}

	if item.DocumentID != "" && item.Version != nil {
		item.meta.WriteRune(',')
		item.meta.WriteString(`"version":`)
		item.meta.WriteString(strconv.FormatInt(*item.Version, 10))
	}

	if item.DocumentID != "" && item.VersionType != "" {
		item.meta.WriteRune(',')
		item.meta.WriteString(`"version_type":`)
		aux = strconv.AppendQuote(aux, item.VersionType)
		item.meta.Write(aux)
		aux = nil
	}

	if item.Routing != "" {
		if item.DocumentID != "" {
			item.meta.WriteRune(',')
		}
		item.meta.WriteString(`"routing":`)
		aux = strconv.AppendQuote(aux, item.Routing)
		item.meta.Write(aux)
		aux = nil
	}
	if item.Index != "" {
		if item.DocumentID != "" || item.Routing != "" {
			item.meta.WriteRune(',')
		}
		item.meta.WriteString(`"_index":`)
		aux = strconv.AppendQuote(aux, item.Index)
		item.meta.Write(aux)
		aux = nil
	}
	if item.RetryOnConflict != nil && item.Action == "update" {
		if item.DocumentID != "" || item.Routing != "" || item.Index != "" {
			item.meta.WriteString(",")
		}
		item.meta.WriteString(`"retry_on_conflict":`)
		aux = strconv.AppendInt(aux, int64(*item.RetryOnConflict), 10)
		item.meta.Write(aux)
		aux = nil
	}
	item.meta.WriteRune('}')
	item.meta.WriteRune('}')
	item.meta.WriteRune('\n')
}

// computeLength calculate the size of the body and the metadata.
func (item *BulkIndexerItem) computeLength() error {
	if item.Body != nil {
		var buf bytes.Buffer
		_, err := io.Copy(&buf, item.Body)
		if err != nil {
			return err
		}

		_, err = item.Body.Seek(0, io.SeekStart)
		if err != nil {
			return err
		}
		item.payloadLength = buf.Len()
		return nil
	}
	item.payloadLength += len(item.meta.Bytes())
	// Add two bytes to account for newlines.
	item.payloadLength += 2

	return nil
}

// BulkIndexerResponse represents the Elasticsearch response.
type BulkIndexerResponse struct {
	Took      int                                  `json:"took"`
	HasErrors bool                                 `json:"errors"`
	Items     []map[string]BulkIndexerResponseItem `json:"items,omitempty"`
}

// BulkIndexerResponseItem represents the Elasticsearch response item.
type BulkIndexerResponseItem struct {
	Index      string `json:"_index"`
	DocumentID string `json:"_id"`
	Version    int64  `json:"_version"`
	Result     string `json:"result"`
	Status     int    `json:"status"`
	SeqNo      int64  `json:"_seq_no"`
	PrimTerm   int64  `json:"_primary_term"`

	Shards struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Failed     int `json:"failed"`
	} `json:"_shards"`

	Error struct {
		Type   string `json:"type"`
		Reason string `json:"reason"`
		Cause  struct {
			Type   string `json:"type"`
			Reason string `json:"reason"`
		} `json:"caused_by"`
	} `json:"error,omitempty"`
}

// BulkResponseJSONDecoder defines the interface for custom JSON decoders.
type BulkResponseJSONDecoder interface {
	UnmarshalFromReader(io.Reader, *BulkIndexerResponse) error
}

// BulkIndexerDebugLogger defines the interface for a debugging logger.
type BulkIndexerDebugLogger interface {
	Printf(string, ...interface{})
}

type bulkIndexer struct {
	wg      sync.WaitGroup
	queue   chan BulkIndexerItem
	workers []*worker
	ticker  *time.Ticker
	done    chan bool
	stats   *bulkIndexerStats

	config BulkIndexerConfig
}

type bulkIndexerStats struct {
	numAdded    uint64
	numFlushed  uint64
	numFailed   uint64
	numIndexed  uint64
	numCreated  uint64
	numUpdated  uint64
	numDeleted  uint64
	numRequests uint64
}

// NewBulkIndexer creates a new bulk indexer.
func NewBulkIndexer(cfg BulkIndexerConfig) (BulkIndexer, error) {
	if cfg.Client == nil {
		cfg.Client, _ = elasticsearch.NewDefaultClient()
	}

	if cfg.Decoder == nil {
		cfg.Decoder = defaultJSONDecoder{}
	}

	if cfg.NumWorkers == 0 {
		cfg.NumWorkers = runtime.NumCPU()
	}

	if cfg.FlushBytes == 0 {
		cfg.FlushBytes = 5e+6
	}

	if cfg.FlushInterval == 0 {
		cfg.FlushInterval = 30 * time.Second
	}

	bi := bulkIndexer{
		config: cfg,
		done:   make(chan bool),
		stats:  &bulkIndexerStats{},
	}

	bi.init()

	return &bi, nil
}

// Add adds an item to the indexer.
//
// Adding an item after a call to Close() will panic.
func (bi *bulkIndexer) Add(ctx context.Context, item BulkIndexerItem) error {
	atomic.AddUint64(&bi.stats.numAdded, 1)

	// Serialize metadata to JSON
	item.marshallMeta()
	// Compute length for body & metadata
	if err := item.computeLength(); err != nil {
		return err
	}

	select {
	case <-ctx.Done():
		if bi.config.OnError != nil {
			bi.config.OnError(ctx, ctx.Err())
		}
		return ctx.Err()
	case bi.queue <- item:
	}

	return nil
}

// Close stops the periodic flush, closes the indexer queue channel,
// notifies the done channel and calls flush on all writers.
func (bi *bulkIndexer) Close(ctx context.Context) error {
	bi.ticker.Stop()
	close(bi.queue)
	bi.done <- true

	select {
	case <-ctx.Done():
		if bi.config.OnError != nil {
			bi.config.OnError(ctx, ctx.Err())
		}
		return ctx.Err()
	default:
		bi.wg.Wait()
	}

	for _, w := range bi.workers {
		w.mu.Lock()
		if w.buf.Len() > 0 {
			if err := w.flush(ctx); err != nil {
				w.mu.Unlock()
				if bi.config.OnError != nil {
					bi.config.OnError(ctx, err)
				}
				continue
			}
		}
		w.mu.Unlock()
	}
	return nil
}

// Stats returns indexer statistics.
func (bi *bulkIndexer) Stats() BulkIndexerStats {
	return BulkIndexerStats{
		NumAdded:    atomic.LoadUint64(&bi.stats.numAdded),
		NumFlushed:  atomic.LoadUint64(&bi.stats.numFlushed),
		NumFailed:   atomic.LoadUint64(&bi.stats.numFailed),
		NumIndexed:  atomic.LoadUint64(&bi.stats.numIndexed),
		NumCreated:  atomic.LoadUint64(&bi.stats.numCreated),
		NumUpdated:  atomic.LoadUint64(&bi.stats.numUpdated),
		NumDeleted:  atomic.LoadUint64(&bi.stats.numDeleted),
		NumRequests: atomic.LoadUint64(&bi.stats.numRequests),
	}
}

// init initializes the bulk indexer.
func (bi *bulkIndexer) init() {
	bi.queue = make(chan BulkIndexerItem, bi.config.NumWorkers)

	for i := 1; i <= bi.config.NumWorkers; i++ {
		w := worker{
			id:  i,
			ch:  bi.queue,
			bi:  bi,
			buf: bytes.NewBuffer(make([]byte, 0, bi.config.FlushBytes)),
			aux: make([]byte, 0, 512)}
		w.run()
		bi.workers = append(bi.workers, &w)
	}
	bi.wg.Add(bi.config.NumWorkers)

	bi.ticker = time.NewTicker(bi.config.FlushInterval)
	go func() {
		ctx := context.Background()
		for {
			select {
			case <-bi.done:
				return
			case <-bi.ticker.C:
				if bi.config.DebugLogger != nil {
					bi.config.DebugLogger.Printf("[indexer] Auto-flushing workers after %s\n", bi.config.FlushInterval)
				}
				for _, w := range bi.workers {
					w.mu.Lock()
					if w.buf.Len() > 0 {
						if err := w.flush(ctx); err != nil {
							w.mu.Unlock()
							if bi.config.OnError != nil {
								bi.config.OnError(ctx, err)
							}
							continue
						}
					}
					w.mu.Unlock()
				}
			}
		}
	}()
}

// worker represents an indexer worker.
type worker struct {
	id    int
	ch    <-chan BulkIndexerItem
	mu    sync.Mutex
	bi    *bulkIndexer
	buf   *bytes.Buffer
	aux   []byte
	items []BulkIndexerItem
}

// run launches the worker in a goroutine.
func (w *worker) run() {
	go func() {
		ctx := context.Background()

		if w.bi.config.DebugLogger != nil {
			w.bi.config.DebugLogger.Printf("[worker-%03d] Started\n", w.id)
		}
		defer w.bi.wg.Done()

		for item := range w.ch {
			w.mu.Lock()

			if w.bi.config.DebugLogger != nil {
				w.bi.config.DebugLogger.Printf("[worker-%03d] Received item [%s:%s]\n", w.id, item.Action, item.DocumentID)
			}

			oversizePayload := w.bi.config.FlushBytes <= item.payloadLength
			if !oversizePayload && w.buf.Len() > 0 && w.buf.Len()+item.payloadLength >= w.bi.config.FlushBytes {
				if err := w.flush(ctx); err != nil {
					w.mu.Unlock()
					if w.bi.config.OnError != nil {
						w.bi.config.OnError(ctx, err)
					}
					continue
				}
			}

			if err := w.writeMeta(&item); err != nil {
				if item.OnFailure != nil {
					item.OnFailure(ctx, item, BulkIndexerResponseItem{}, err)
				}
				atomic.AddUint64(&w.bi.stats.numFailed, 1)
				w.mu.Unlock()
				continue
			}

			if err := w.writeBody(&item); err != nil {
				if item.OnFailure != nil {
					item.OnFailure(ctx, item, BulkIndexerResponseItem{}, err)
				}
				atomic.AddUint64(&w.bi.stats.numFailed, 1)
				w.mu.Unlock()
				continue
			}

			w.items = append(w.items, item)
			// Should the item payload exceed the configured FlushBytes flush happens instantly.
			if oversizePayload {
				if w.bi.config.DebugLogger != nil {
					w.bi.config.DebugLogger.Printf("[worker-%03d] Oversize Payload in item [%s:%s]\n", w.id, item.Action, item.DocumentID)
				}
				if err := w.flush(ctx); err != nil {
					w.mu.Unlock()
					if w.bi.config.OnError != nil {
						w.bi.config.OnError(ctx, err)
					}
					continue
				}
			}
			w.mu.Unlock()
		}
	}()
}

// writeMeta writes the item metadata to the buffer; it must be called under a lock.
func (w *worker) writeMeta(item *BulkIndexerItem) error {
	if _, err := w.buf.Write(item.meta.Bytes()); err != nil {
		return err
	}
	return nil
}

// writeBody writes the item body to the buffer; it must be called under a lock.
func (w *worker) writeBody(item *BulkIndexerItem) error {
	if item.Body != nil {
		if _, err := w.buf.ReadFrom(item.Body); err != nil {
			if w.bi.config.OnError != nil {
				w.bi.config.OnError(context.Background(), err)
			}
			return err
		}
		item.Body.Seek(0, io.SeekStart)
		w.buf.WriteRune('\n')
	}
	return nil
}

// flush writes out the worker buffer; it must be called under a lock.
func (w *worker) flush(ctx context.Context) error {
	if w.bi.config.OnFlushStart != nil {
		ctx = w.bi.config.OnFlushStart(ctx)
	}

	if w.bi.config.OnFlushEnd != nil {
		defer func() { w.bi.config.OnFlushEnd(ctx) }()
	}

	if w.buf.Len() < 1 {
		if w.bi.config.DebugLogger != nil {
			w.bi.config.DebugLogger.Printf("[worker-%03d] Flush: Buffer empty\n", w.id)
		}
		return nil
	}

	var (
		err error
		blk BulkIndexerResponse
	)

	defer func() {
		w.items = nil
		if w.buf.Cap() > w.bi.config.FlushBytes {
			w.buf = bytes.NewBuffer(make([]byte, 0, w.bi.config.FlushBytes))
		} else {
			w.buf.Reset()
		}
	}()

	if w.bi.config.DebugLogger != nil {
		w.bi.config.DebugLogger.Printf("[worker-%03d] Flush: %s\n", w.id, w.buf.String())
	}

	atomic.AddUint64(&w.bi.stats.numRequests, 1)
	req := esapi.BulkRequest{
		Index: w.bi.config.Index,
		Body:  w.buf,

		Pipeline:            w.bi.config.Pipeline,
		Refresh:             w.bi.config.Refresh,
		Routing:             w.bi.config.Routing,
		Source:              w.bi.config.Source,
		SourceExcludes:      w.bi.config.SourceExcludes,
		SourceIncludes:      w.bi.config.SourceIncludes,
		Timeout:             w.bi.config.Timeout,
		WaitForActiveShards: w.bi.config.WaitForActiveShards,

		Pretty:     w.bi.config.Pretty,
		Human:      w.bi.config.Human,
		ErrorTrace: w.bi.config.ErrorTrace,
		FilterPath: w.bi.config.FilterPath,
		Header:     w.bi.config.Header.Clone(),
	}

	// Add Header and MetaHeader to config if not already set
	if req.Header == nil {
		req.Header = http.Header{}
	}
	req.Header.Set(elasticsearch.HeaderClientMeta, "h=bp")

	res, err := req.Do(ctx, w.bi.config.Client)
	if err != nil {
		atomic.AddUint64(&w.bi.stats.numFailed, uint64(len(w.items)))
		if w.bi.config.OnError != nil {
			w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err))
		}
		return fmt.Errorf("flush: %s", err)
	}
	if res.Body != nil {
		defer res.Body.Close()
	}
	if res.IsError() {
		atomic.AddUint64(&w.bi.stats.numFailed, uint64(len(w.items)))
		// TODO(karmi): Wrap error (include response struct)
		if w.bi.config.OnError != nil {
			w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err))
		}
		return fmt.Errorf("flush: %s", res.String())
	}

	if err := w.bi.config.Decoder.UnmarshalFromReader(res.Body, &blk); err != nil {
		// TODO(karmi): Wrap error (include response struct)
		if w.bi.config.OnError != nil {
			w.bi.config.OnError(ctx, fmt.Errorf("flush: %s", err))
		}
		return fmt.Errorf("flush: error parsing response body: %s", err)
	}

	for i, blkItem := range blk.Items {
		var (
			item BulkIndexerItem
			info BulkIndexerResponseItem
			op   string
		)

		item = w.items[i]
		// The Elasticsearch bulk response contains an array of maps like this:
		//   [ { "index": { ... } }, { "create": { ... } }, ... ]
		// We range over the map, to set the first key and value as "op" and "info".
		for k, v := range blkItem {
			op = k
			info = v
		}
		if info.Error.Type != "" || info.Status > 201 {
			atomic.AddUint64(&w.bi.stats.numFailed, 1)
			if item.OnFailure != nil {
				item.OnFailure(ctx, item, info, nil)
			}
		} else {
			atomic.AddUint64(&w.bi.stats.numFlushed, 1)

			switch op {
			case "index":
				atomic.AddUint64(&w.bi.stats.numIndexed, 1)
			case "create":
				atomic.AddUint64(&w.bi.stats.numCreated, 1)
			case "delete":
				atomic.AddUint64(&w.bi.stats.numDeleted, 1)
			case "update":
				atomic.AddUint64(&w.bi.stats.numUpdated, 1)
			}

			if item.OnSuccess != nil {
				item.OnSuccess(ctx, item, info)
			}
		}
	}

	return err
}

type defaultJSONDecoder struct{}

func (d defaultJSONDecoder) UnmarshalFromReader(r io.Reader, blk *BulkIndexerResponse) error {
	return json.NewDecoder(r).Decode(blk)
}


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

<title>Uses of Interface org.apache.cassandra.service.CASRequest (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.cassandra.service.CASRequest

Packages that use CASRequest

Package
Description

org.apache.cassandra.cql3.statements

org.apache.cassandra.service

Uses of CASRequest in org.apache.cassandra.cql3.statements

Classes in org.apache.cassandra.cql3.statements that implement CASRequest

Modifier and Type
Class and Description

class
CQL3CasRequest

Processed CAS conditions and update on potentially multiple rows of the same partition.

Uses of CASRequest in org.apache.cassandra.service

Methods in org.apache.cassandra.service with parameters of type CASRequest

Modifier and Type
Method and Description

static ColumnFamily
StorageProxy.cas(java.lang.String keyspaceName,
   java.lang.String cfName,
   java.nio.ByteBuffer key,
   CASRequest request,
   ConsistencyLevel consistencyForPaxos,
   ConsistencyLevel consistencyForCommit,
   ClientState state)

Apply @param updates if and only if the current values in the row for @param key
 match the provided @param conditions.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
package org.onvif.ver10.schema;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;

/**
 *
Java class for MoveOptions20 complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MoveOptions20">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Absolute" type="{http://www.onvif.org/ver10/schema}AbsoluteFocusOptions" minOccurs="0"/>
 *         <element name="Relative" type="{http://www.onvif.org/ver10/schema}RelativeFocusOptions20" minOccurs="0"/>
 *         <element name="Continuous" type="{http://www.onvif.org/ver10/schema}ContinuousFocusOptions" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MoveOptions20", propOrder = {
    "absolute",
    "relative",
    "continuous"
})
public class MoveOptions20 {

    @XmlElement(name = "Absolute")
    protected AbsoluteFocusOptions absolute;
    @XmlElement(name = "Relative")
    protected RelativeFocusOptions20 relative;
    @XmlElement(name = "Continuous")
    protected ContinuousFocusOptions continuous;

    /**
     * Gets the value of the absolute property.
     *
     * @return
     *     possible object is
     *     {@link AbsoluteFocusOptions }
     *
     */
    public AbsoluteFocusOptions getAbsolute() {
        return absolute;
    }

    /**
     * Sets the value of the absolute property.
     *
     * @param value
     *     allowed object is
     *     {@link AbsoluteFocusOptions }
     *
     */
    public void setAbsolute(AbsoluteFocusOptions value) {
        this.absolute = value;
    }

    /**
     * Gets the value of the relative property.
     *
     * @return
     *     possible object is
     *     {@link RelativeFocusOptions20 }
     *
     */
    public RelativeFocusOptions20 getRelative() {
        return relative;
    }

    /**
     * Sets the value of the relative property.
     *
     * @param value
     *     allowed object is
     *     {@link RelativeFocusOptions20 }
     *
     */
    public void setRelative(RelativeFocusOptions20 value) {
        this.relative = value;
    }

    /**
     * Gets the value of the continuous property.
     *
     * @return
     *     possible object is
     *     {@link ContinuousFocusOptions }
     *
     */
    public ContinuousFocusOptions getContinuous() {
        return continuous;
    }

    /**
     * Sets the value of the continuous property.
     *
     * @param value
     *     allowed object is
     *     {@link ContinuousFocusOptions }
     *
     */
    public void setContinuous(ContinuousFocusOptions value) {
        this.continuous = value;
    }

    /**
     * Generates a String representation of the contents of this type.
     * This is an extension method, produced by the 'ts' xjc plugin
     *
     */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
    }

}


text:
"""View helpers."""
import sys
import collections
import json

import contracts
from bson.objectid import ObjectId
from bson.dbref import DBRef
from flask.views import View as BaseView, http_method_funcs
from flask import request, abort, g, current_app, session

from werkzeug import http, Response
from werkzeug.wrappers import BaseResponse
from werkzeug.exceptions import HTTPException, BadRequest

def authorize(token):
    """
    Authorizes the token and returns the object meant to be stored into g.user.

    Returns None if authorization failed, else the user object.

    You must monkey patch this method to make use of the View.
    """
    raise NotImplementedError()

FLASK_BABEL_USED = False
try:
    import speaklater
    FLASK_BABEL_USED = True
except ImportError:
    pass

def convert_mongo_document_to_api_dict(obj):
    """Converts a mongo document object to the api dict that can be used for json conversion"""
    dict_ = obj.to_mongo()
    dict_.update({'id': str(dict_['_id'])})
    result = dict_.copy()  # cannot change a dict while iterating
    for k, _ in dict_.iteritems():
        if any((k.startswith('_'), k.startswith('password'))):
            del result[k]

    # next make sure we have all the fields:
    missing_fields = set(obj._fields.keys()) - set(result.keys())
    for field in missing_fields:
        result[field] = None
    return result

def _json_handler(obj):
    """Handles objects that are not JSON serializable by default."""

    # lazy gettext strings must be cast to unicode before they can be serialized
    if FLASK_BABEL_USED and isinstance(obj, speaklater._LazyString):
        return unicode(obj)

    # dates have isoformat() and should be returned as such, without microseconds and using a space as seperator
    if hasattr(obj, 'isoformat'):
        return obj.replace(microsecond=0).isoformat(' ')

    # mongo ObjectIds are cast to strings
    elif type(obj) == ObjectId:
        return str(obj)

    # mongo db references are handled as object ids.
    elif type(obj) == DBRef:
        return str(obj.id)

    # all mongo documents have to_mongo() and are returned by invoking that
    elif hasattr(obj, 'to_mongo'):
        return convert_mongo_document_to_api_dict(obj)
    elif isinstance(obj, collections.Iterable):
        return map(_json_handler, obj)
    else:
        raise TypeError('Object of type %s with value of %s '
                        'is not JSON serializable' % (type(obj), repr(obj)))

def json_dumps(obj):
    """Dump object to json with a custom json handler."""
    return json.dumps(obj, default=_json_handler)

ENCODERS = {'application/json': json_dumps,  # most API users
            'text/html': str,  # browser, coming from redirect from OAuth
            }

class ViewType(type):
    """View meta class."""
    def __new__(cls, name, bases, attrs):
        """Ensure that created class will have `methods` attribute which is a list of supported HTTP methods for
        creating view class."""
        rv = type.__new__(cls, name, bases, attrs)
        if 'methods' not in attrs:
            methods = set(rv.methods or [])
            for key in attrs:
                if key in http_method_funcs:
                    methods.add(key.upper())
            # if we have no method at all in there we don't want to
            # add a method list.  (This is for instance the case for
            # the baseclass or another subclass of a base method view
            # that does not introduce new methods).
            if methods:
                rv.methods = sorted(methods)
        return rv

class View(BaseView):
    """View class."""
    __metaclass__ = ViewType

    def dispatch_request(self, **kwargs):

        method_name = request.method.lower()

        # import this here to be sure of correct settings
        # and the existance of a request (to use current_app)
        from pltk.flask_utils.limit import inject_x_rate_headers

        # only check rate limits when not debugging
        if current_app.debug:
            # mimick class RateLimit
            g._view_rate_limit = type('object',
                                      (),
                                      dict(send_x_headers=True,
                                           remaining=sys.maxint,
                                           limit=sys.maxint,
                                           reset=sys.maxint,
                                           ),
                                      )

        else:
            # import this here to be sure of correct settings
            # and the existance of a request (to use current_app)
            from pltk.flask_utils.limit import(
                RateLimit,
                on_limit_reached)

            key = 'rate-limit/%s/%s/%s/' % (
                request.endpoint,
                method_name,
                request.remote_addr)

            limit = g.redis.get_config('DEFAULT_RATE_LIMIT')
            per = g.redis.get_config('DEFAULT_RATE_PER')
            exp = g.redis.get_config('DEFAULT_RATE_EXP_WINDOW')

            config_key = '%s.%s' % (request.endpoint, method_name)

            custom_rate_limit = g.redis.get_config('CUSTOM_RATE_LIMIT')

            if config_key in custom_rate_limit:
                limit, per, exp = custom_rate_limit[config_key]

            rlimit = RateLimit(g.redis, key, limit, per, True, exp)

            g._view_rate_limit = rlimit

            if rlimit.over_limit:
                return on_limit_reached(rlimit)

        meth = getattr(self, method_name)

        # require auth by default
        needs_auth = getattr(meth, 'needs_auth', True)
        # session_token might be provided in the header...
        session_token = request.headers.get('Authorization')
        # ...as a querystring parameter instead...
        if not session_token:
            session_token = request.args.get('session_token', None)
        # ...or in the browser session (in a cookie)
        if not session_token:
            session_token = session.get('session_token', None)
        if needs_auth and not session_token:
            abort(401, 'Unauthorized access')
        if session_token:
            g.user = authorize(session_token)
        else:
            g.user = None

        if needs_auth and g.user is None:
            abort(403, 'Authentication token is invalid')

        encoder, self.encoding = get_encoder()

        if request.method == 'GET':
            # .update(request.args) will have lists of values
            kwargs.update((k, v) for k, v in request.args.iteritems())
        else:
            # FIXME: only supports application/json content type right now. In
            # case of need, upgrade to DECODERS or rely on Werkzeug's ability
            # to decode content types
            # This method will never raise ValueError exception since this
            # exception will be catched before
            try:
                kwargs.update(request.json or {})
            except (BadRequest, ValueError):
                kwargs.update({})

        # FIX unicode dictionary keys to strings for older pythons
        if sys.version_info < (2, 7):  # pragma: no cover
            kwargs = self.dict_keys_to_string(kwargs)

        try:
            try:
                result = meth(**kwargs)
            except (contracts.ContractException) as e:
                abort(400, str(e))
        except HTTPException as e:
            result = Response({"code": e.code, "error": unicode(e.description)}, e.code, mimetype=self.encoding)

        if isinstance(result, BaseResponse):
            response = result
        else:
            if not isinstance(result, basestring):
                result = encoder(result)
            response = Response(result, 200, mimetype=self.encoding)

        return inject_x_rate_headers(response)

    def dict_keys_to_string(self, kwargs):
        """Convert passed dict keys to strings.

        ..warning:: On failure returns the passed dictionary.

        :param dict kwargs: a dictionary whose keys will be replaced
                            to strings.

        :return: A new dict where keys are replaced to strings.

        """
        try:
            skwargs = dict()
            for k, v in kwargs.iteritems():
                skwargs[str(k)] = v
            return skwargs
        except:
            return kwargs

    def get_ok_message(self):
        """Generate OK message."""
        return {'message': 'ok'}

def get_encoder(default='application/json'):
    """Get the encoder from the headers."""
    try:
        accept = request.headers['Accept']
    except KeyError:
        return ENCODERS[default], default
    try:
        for encoding, _ in http.parse_accept_header(accept):
            if encoding == '*/*':
                return ENCODERS[default], default
            elif encoding in ENCODERS:
                return ENCODERS[encoding], encoding
    except TypeError:
        # The encoder doesn't exist
        pass
    abort(400, 'Unsupported return encoding')

def public(func):
    """Do not require authentication on given view method."""
    msg = "*Does not require authentication*\n"
    doc = func.__doc__
    prefix = doc[:len(doc) - len(doc.lstrip())]
    func.__doc__ = prefix + msg + doc
    func.needs_auth = False
    return func


text:
var videoChatCtrl = require('../controller');
var express = require('express');
var router = express.Router();

router.put('/searchForMatch', videoChatCtrl.searchForMatch);
router.put('/twilioToken', videoChatCtrl.getToken);
router.put('/getMatchInfo', videoChatCtrl.getMatchInfo);

// router.put('/stats', videoChatCtrl.stats);
// router.post('/login', videoChatCtrl.login);

module.exports = router;


text:
<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Admin\BaseController;
use App\Models\Help;

class HelpController extends BaseController
{
	public function newEntity(array $attributes = [])
	{
		// TODO: Implement newEntity() method.
		return new Help($attributes);
	}

	/**
	* Display a listing of the resource.
	*
	* @return  \Illuminate\Http\Response
	*/
	public function index()
	{
		//
		return view('admin.help.index');
	}

	/**
	* Show the form for creating a new resource.
	*
	* @return  \Illuminate\Http\Response
	*/
	public function create()
	{
		return view('admin.help.create');
	}

	/**
	* Display the specified resource.
	*
	* @param    int  $id
	* @return  \Illuminate\Http\Response
	*/
	public function edit($id)
	{
		$entity = Help::find($id);
		return view('admin.help.edit', ['entity' => $entity]);
	}

	/**
	* Display the specified resource.
	*
	* @param    int  $id
	* @return  \Illuminate\Http\Response
	*/
	public function show($id)
	{
		$entity = Help::find($id);
		return view('admin.help.show', ['entity' => $entity]);
	}

	/**
	* @param  Request $request
	* @param  array $searchCols
	* @param  array $with
	* @param  null $conditionCall
	* @param  bool $all_columns
	* @return  \Illuminate\Http\JsonResponse
	*/
	public function pagination(Request $request, $searchCols = [], $with=[], $conditionCall = null, $dataHandleCall = null, $all_columns = false){
		$searchCols = ["content","name"];
		return parent::pagination($request, $searchCols,$with,function($query){
            $query->orderBy('sort','asc');
        });
	}

	public function store(Request $request, $only = [], $extraFields = [], $redirect_url = null)
    {
        $redirect_url = url('/admin/help');
        return parent::store($request, $only, $extraFields, $redirect_url); // TODO: Change the autogenerated stub
    }

    public function update(Request $request, $id, $only = [], $extraFields = [], $redirect_url = null)
    {
        $redirect_url = url('/admin/help');
        return parent::update($request, $id, $only, $extraFields, $redirect_url); // TODO: Change the autogenerated stub
    }

}


text:
<?php

defined('COT_CODE') or die('Wrong URL');

// Requirements
global $R, $L;
require_once cot_incfile('users', 'module');
require_once cot_langfile('comments', 'plug');
require_once cot_incfile('comments', 'plug', 'resources');
require_once cot_incfile('forms');

// Table names
cot::$db->registerTable('com');
cot_extrafields_register_table('com');

/**
 * Returns number of comments for item
 *
 * @param string $ext_name Target extension name
 * @param string $code Item code
 * @param array $row Database row entry (optional)
 * @return int
 * @global CotDB $db
 */
function cot_comments_count($ext_name, $code, $row = array())
{
	global $db, $db_com;
	static $com_cache = array();

	if (isset($com_cache[$ext_name][$code]))
	{
		return $com_cache[$ext_name][$code];
	}

	$cnt = 0;
	if (isset($row['com_count']))
	{
		$cnt = (int) $row['com_count'];
		$com_cache[$ext_name][$code] = $cnt;
	}
	else
	{
		$comments_join_columns = '';
		$comments_join_tables = '';
		$comments_join_where = '';
		/* == Hook == */
		foreach (cot_getextplugins('comments.count.query') as $pl)
		{
			include $pl;
		}
		/* ===== */
		$sql = $db->query("SELECT COUNT(*) $comments_join_columns
			FROM $db_com $comments_join_tables
			WHERE com_area = ? AND com_code = ? $comments_join_where",
			array($ext_name, $code));
		if ($sql->rowCount() == 1)
		{
			$cnt = (int) $sql->fetchColumn();
			$com_cache[$ext_name][$code] = $cnt;
		}
	}

	return $cnt;
}

/**
 * Generates comments display for a given item
 *
 * @param string $ext_name Module or plugin code
 * @param string $code Item identifier
 * @param string $cat Item category code (optional)
 * @param bool $force_admin Enforces user to be administrator of comments for this item.
 *	E.g. to moderate his wall even if he is not a moderator
 * @return string Rendered HTML output for comments
 * @global CotDB $db
 */
function cot_comments_display($ext_name, $code, $cat = '', $force_admin = false)
{
	global $db, $db_com, $db_users, $cfg, $usr, $L, $sys, $R, $env, $pg, $cot_extrafields, $cache, $structure;

	// Check permissions and enablement
	list($auth_read, $auth_write, $auth_admin) = cot_auth('plug', 'comments');

	if ($auth_read && $auth_write && $force_admin)
	{
		$auth_admin = true;
		$_SESSION['cot_comments_force_admin'][$ext_name][$code] = true;
	}

	$enabled = cot_comments_enabled($ext_name, $cat, $code);

	if (!$auth_read || !$enabled && !$auth_admin)
	{
		return '';
	}

	// Get the URL and parameters
	$link_area = $env['ext'];
	$link_params = $_GET;
	if (defined('COT_PLUG'))
	{
		$link_area = 'plug';
		$link_params['e'] = $env['ext'];
	}
	if (isset($_GET['rwr']))
	{
		unset($link_params['rwr'], $link_params['e']);
	}

    $cot_com_back = array($link_area, $link_params);
	$_SESSION['cot_com_back'][$ext_name][$cat][$code] = $cot_com_back;

	$d_var = 'dcm';
	list($pg, $d, $durl) = cot_import_pagenav($d_var, $cfg['plugin']['comments']['maxcommentsperpage']);
	$d = empty($d) ? 0 : (int) $d;

	if ($auth_write && $enabled)
	{
		require_once cot_incfile('forms');
	}

	$t = new XTemplate(cot_tplfile('comments', 'plug'));

	/* == Hook == */
	foreach (cot_getextplugins('comments.main') as $pl)
	{
		include $pl;
	}
	/* ===== */
    $editor = ($cfg['plugin']['comments']['markup']) ? 'input_textarea_minieditor' : '';
	$t->assign(array(
		'COMMENTS_CODE' => $code,
		'COMMENTS_FORM_SEND' => cot_url('plug', "e=comments&a=send&area=$ext_name&cat=$cat&item=$code"),
		'COMMENTS_FORM_AUTHOR' => ($usr['id'] > 0) ? $usr['name'] : cot_inputbox('text', 'rname'),
		'COMMENTS_FORM_AUTHORID' => $usr['id'],
		'COMMENTS_FORM_TEXT' => $auth_write && $enabled ? cot_textarea('rtext', $rtext, 7, 120, '', $editor).cot_inputbox('hidden', 'cb', base64_encode(serialize($cot_com_back)))
			: '',
		'COMMENTS_DISPLAY' => $cfg['plugin']['comments']['expand_comments'] ? '' : 'none'
	));

	if ($auth_write && $enabled)
	{
		// Extra fields
		foreach ($cot_extrafields[$db_com] as $exfld)
		{
			$uname = strtoupper($exfld['field_name']);
			$exfld_val = cot_build_extrafields('rcomments' . $exfld['field_name'], $exfld, $rcomments[$exfld['field_name']]);
			$exfld_title = isset($L['comments_' . $exfld['field_name'] . '_title']) ? $L['comments_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
			$t->assign(array(
				'COMMENTS_FORM_' . $uname => $exfld_val,
				'COMMENTS_FORM_' . $uname . '_TITLE' => $exfld_title,
				'COMMENTS_FORM_EXTRAFLD' => $exfld_val,
				'COMMENTS_FORM_EXTRAFLD_TITLE' => $exfld_title
				));
			$t->parse('COMMENTS.COMMENTS_NEWCOMMENT.EXTRAFLD');
		}

		$allowed_time = cot_build_timegap($sys['now'] - $cfg['plugin']['comments']['time'] * 60,
			$sys['now']);
		$com_hint = cot_rc('com_edithint', array('time' => $allowed_time));

		/* == Hook == */
		foreach (cot_getextplugins('comments.newcomment.tags') as $pl)
		{
			include $pl;
		}
		/* ===== */

		$usr['id'] == 0 && $t->parse('COMMENTS.COMMENTS_NEWCOMMENT.GUEST');
		if ($usr['id'] == 0 && cot_check_messages() && $cache)
		{
			if($ext_name == 'page' && $cfg['cache_page'])
			{
				$cache->page->clear('page/' . str_replace('.', '/', $structure['page'][$cat]['path']));
				$cfg['cache_page'] = false;
			}
		}
		cot_display_messages($t, 'COMMENTS.COMMENTS_NEWCOMMENT');
		$t->assign('COMMENTS_FORM_HINT', $com_hint);
		$t->parse('COMMENTS.COMMENTS_NEWCOMMENT');
	}
	else
	{
		$warning = $enabled ? $L['com_regonly'] : $L['com_closed'];
		$t->assign('COMMENTS_CLOSED', $warning);
		$t->parse('COMMENTS.COMMENTS_CLOSED');
	}

	$order = $cfg['plugin']['comments']['order'] == 'Chronological' ? 'ASC' : 'DESC';
	$comments_order = "com_id $order";

	/* == Hook == */
	foreach (cot_getextplugins('comments.query') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$sql = $db->query("SELECT c.*, u.* $comments_join_columns
		FROM $db_com AS c LEFT JOIN $db_users AS u ON u.user_id = c.com_authorid $comments_join_tables
		WHERE com_area = ? AND com_code = ? $comments_join_where ORDER BY $comments_order LIMIT ?, ?",
		array($ext_name, $code, (int) $d, (int) $cfg['plugin']['comments']['maxcommentsperpage']));
	if ($sql->rowCount() > 0 && $enabled)
	{
		$i = $d;
		$kk = 0;
		$totalitems = cot_comments_count($ext_name, $code);
		/* === Hook - Part1 : Set === */
		$extp = cot_getextplugins('comments.loop');
		/* ===== */

		foreach ($sql->fetchAll() as $row)
		{
			$i++;
			$kk++;
			$com_admin = ($auth_admin) ? cot_rc('comments_code_admin', array(
					'ipsearch' => cot_build_ipsearch($row['com_authorip']),
					'delete_url' => cot_confirm_url(cot_url('plug', 'e=comments&a=delete&cat='.$cat.'&id='.$row['com_id'].'&'.cot_xg()), 'comments', 'comments_confirm_delete')
				)) : '';

			$com_text = cot_parse($row['com_text'], $cfg['plugin']['comments']['markup']);

			$time_limit = ($sys['now'] < ($row['com_date'] + $cfg['plugin']['comments']['time'] * 60)) ? TRUE
				: FALSE;
            $usr['isowner_com'] = $time_limit && ( ($usr['id'] > 0 && $row['com_authorid'] == $usr['id'] )
                || ($usr['id'] == 0 && !empty($_SESSION['cot_comments_edit'][$row['com_id']]) && $usr['ip'] == $row['com_authorip']) );
			$com_gup = $sys['now'] - ($row['com_date'] + $cfg['plugin']['comments']['time'] * 60);
			$allowed_time = ($usr['isowner_com'] && !$usr['isadmin']) ? ' - '
				. cot_build_timegap($sys['now'] + $com_gup, $sys['now']) . $L['plu_comgup'] : '';
			$com_edit = ($auth_admin || $usr['isowner_com']) ? cot_rc('comments_code_edit', array(
					'edit_url' => cot_url('plug', 'e=comments&m=edit&cat='.$cat.'&id='.$row['com_id']),
					'allowed_time' => $allowed_time
				)) : '';

            if($row['com_area'] == 'page'){
                if($usr['id'] == 0 && $usr['isowner_com'] && $cfg['cache_page']) $cfg['cache_page'] = $cfg['cache_index'] = false;
            }
			$t->assign(array(
				'COMMENTS_ROW_ID' => $row['com_id'],
				'COMMENTS_ROW_ORDER' => $cfg['plugin']['comments']['order'] == 'Recent' ? $totalitems - $i + 1 : $i,
				'COMMENTS_ROW_URL' => cot_url($link_area, $link_params, '#c'.$row['com_id']),
				'COMMENTS_ROW_AUTHOR' => cot_build_user($row['com_authorid'], htmlspecialchars($row['com_author'])),
				'COMMENTS_ROW_AUTHORID' => $row['com_authorid'],
				'COMMENTS_ROW_TEXT' => $com_text,
				'COMMENTS_ROW_DATE' => cot_date('datetime_medium', $row['com_date']),
				'COMMENTS_ROW_DATE_STAMP' => $row['com_date'],
				'COMMENTS_ROW_ADMIN' => $com_admin,
				'COMMENTS_ROW_EDIT' => $com_edit,
				'COMMENTS_ROW_ODDEVEN' => cot_build_oddeven($kk),
				'COMMENTS_ROW_NUM' => $kk
			));

				// Extrafields
			if (isset($cot_extrafields[$db_com]))
			{
				foreach ($cot_extrafields[$db_com] as $exfld)
				{
					$tag = mb_strtoupper($exfld['field_name']);
					$t->assign(array(
						'COMMENTS_ROW_' . $tag . '_TITLE' => isset($L['comments_' . $exfld['field_name'] . '_title']) ? $L['comments_' . $exfld['field_name'] . '_title'] : $exfld['field_description'],
						'COMMENTS_ROW_' . $tag => cot_build_extrafields_data('comments', $exfld, $row['com_'.$exfld['field_name']]),
						'COMMENTS_ROW_' . $tag . '_VALUE' => $row['com_'.$exfld['field_name']]
					));
				}
			}

			$t->assign(cot_generate_usertags($row, 'COMMENTS_ROW_AUTHOR_', htmlspecialchars($row['com_author'])));

			/* === Hook - Part2 : Include === */
			foreach ($extp as $pl)
			{
				include $pl;
			}
			/* ===== */

			$t->parse('COMMENTS.COMMENTS_ROW');
		}

		$pagenav = cot_pagenav($link_area, $link_params, $d, $totalitems,
			$cfg['plugin']['comments']['maxcommentsperpage'], $d_var, '#comments',
			$cfg['jquery'] && $cfg['ajax_enabled'], 'comments', 'plug', "e=comments&area=$ext_name&cat=$cat&item=$code");
		$t->assign(array(
			'COMMENTS_PAGES_INFO' => cot_rc('comments_code_pages_info', array(
					'totalitems' => $totalitems,
					'onpage' => $i - $d
				)),
			'COMMENTS_PAGES_TOTALITEMS' => $totalitems,
			'COMMENTS_PAGES_PAGESPREV' => $pagenav['prev'],
			'COMMENTS_PAGES_PAGNAV' => $pagenav['main'],
			'COMMENTS_PAGES_PAGESNEXT' => $pagenav['next']
		));
		$t->parse('COMMENTS.PAGNAVIGATOR');

	}
	elseif (!$sql->rowCount() && $enabled)
	{
		$t->assign(array(
			'COMMENTS_EMPTYTEXT' => $L['com_nocommentsyet'],
		));
		$t->parse('COMMENTS.COMMENTS_EMPTY');
	}

	/* == Hook == */
	foreach (cot_getextplugins('comments.tags') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$t->parse('COMMENTS');
	$res_display = $t->text('COMMENTS');

	return $res_display;
}

/**
 * Checks if comments are enabled for specific extension and category
 *
 * @param string $ext_name Extension name
 * @param string $cat Category name or empty if checking the entire area
 * @param string $item Item code, not yet supported
 * @return bool
 */
function cot_comments_enabled($ext_name, $cat = '', $item = '')
{
	global $cfg, $cot_modules;
	if (isset($cfg[$ext_name]['cat_'.$cat]['enable_comments'])
		|| isset($cfg[$ext_name]['enable_comments'])
		|| isset($cfg['plugin'][$ext_name]['enable_comments'])
		|| isset($cfg[$ext_name]['cat___default']['enable_comments']))
	{
		if (isset($cot_modules[$ext_name]))
		{
			if (isset($cfg[$ext_name]['cat_'.$cat]['enable_comments']))
			{
				return $cfg[$ext_name]['cat_'.$cat]['enable_comments'];
			}
			else
			{
				return isset($cfg[$ext_name]['cat___default']['enable_comments'])
					? $cfg[$ext_name]['cat___default']['enable_comments']
					: $cfg[$ext_name]['enable_comments'];
			}
		}
		else
		{
			return (bool) $cfg['plugin'][$ext_name]['enable_comments'];
		}
	}
	return true;
}

/**
 * Generates comments display for a given item
 *
 * @param string $link_area Target URL area for cot_url()
 * @param string $link_params Target URL params for cot_url()
 * @param string $ext_name Module or plugin code
 * @param string $code Item identifier
 * @param string $cat Item category code (optional)
 * @param array $row Database row entry (optional)
 * @return string Rendered HTML output for comments
 * @see cot_comments_count()
 * @global CotDB $db
 */
function cot_comments_link($link_area, $link_params, $ext_name, $code, $cat = '', $row = array())
{
	global $cfg, $db, $R, $L, $db_com;

	if (!cot_comments_enabled($ext_name, $cat, $code))
	{
		return '';
	}

	$res = cot_rc('comments_link', array(
		'url' => cot_url($link_area, $link_params, '#comments'),
		'count' => $cfg['plugin']['comments']['countcomments'] ? cot_comments_count($ext_name, $code, $row) : ''
	));
	return $res;
}

/**
 * New comments count for admin page
 *
 * @param string $timeback Datetime to count from
 * @return int
 * @global CotDB $db
 */
function cot_comments_newcount($timeback)
{
	global $db, $db_com;

	$sql = $db->query("SELECT COUNT(*) FROM $db_com WHERE com_date > ?", array($timeback));
	$newcomments = $sql->fetchColumn();
	return $newcomments;
}

/**
 * Removes comments associated with an item
 *
 * @param string $area Item area code
 * @param string $code Item identifier
 * @global CotDB $db
 */
function cot_comments_remove($area, $code)
{
	global $db, $db_com;

	$db->delete($db_com, 'com_area = ? AND com_code = ?', array($area, $code));
}


text:
package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"knative.dev/pkg/apis"
	duckv1 "knative.dev/pkg/apis/duck/v1"
	"knative.dev/pkg/kmeta"
)

// +genclient
// +genclient:nonNamespaced
// +genreconciler:krshapedlogic=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Domain is a cluster-scoped resource to configure a proxy pool for a given Route.
type Domain struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// Spec is the desired state of the Domain.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
	// +optional
	Spec DomainSpec `json:"spec,omitempty"`

	// Status is the current state of the Domain.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
	// +optional
	Status DomainStatus `json:"status,omitempty"`
}

// Verify that Domain adheres to the appropriate interfaces.
var (
	// Check that Doimain may be validated and defaulted.
	_ apis.Validatable = (*Domain)(nil)
	_ apis.Defaultable = (*Domain)(nil)

	// Check that we can create OwnerReferences to a Domain.
	_ kmeta.OwnerRefable = (*Domain)(nil)

	// Check that the type conforms to the duck Knative Resource shape.
	_ duckv1.KRShaped = (*Domain)(nil)
)

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// DomainList is a collection of Domain objects.
type DomainList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object metadata.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is the list of Domain objects.
	Items []Domain `json:"items"`
}

// DomainSpec describes the Ingress the user wishes to exist.
//
// In general this follows the same shape as K8s Ingress.
// Some notable differences:
// - Backends now can have namespace:
// - Traffic can be split across multiple backends.
// - Timeout & Retry can be configured.
// - Headers can be appended.
// DomainSpec contains the specification of the Domain CRD.
type DomainSpec struct {
	// IngressClass tells what Ingress class annotation to use for Routes associated
	// with this Realm.
	IngressClass string `json:"ingressClass"`

	// Suffix specifies the domain suffix to be used. This field replaces the
	// existing config-domain ConfigMap.  Internal Domains can omit this, in
	// which case we will default to the cluster suffix.
	// +optional
	Suffix string `json:"suffix,omitempty"`

	// LoadBalancers provide addresses (IP addresses, domains) of the load balancers
	// associated with this Domain.  This is used in automatic DNS provisioning like
	// configuration of magic DNS or creating ExternalName services for cluster-local
	// access.
	LoadBalancers []LoadBalancerIngressSpec `json:"loadBalancers"`

	// Configs contains additional pieces of information to configure ingress proxies.
	// +optional
	Configs []IngressConfig `json:"configs,omitempty"`
}

// IngressConfig allows KIngress implementations to add additional information needed
// for configuring the proxies associated with this Domain.
// For examples, in our Istio-based Ingress this will contains all references of
// Istio Gateways associated with this Domain. This could be a reference of a ConfigMap
// owned by the implementation as well.
type IngressConfig struct {
	// Name of the Kingress implementation resource
	// +optional
	Name string `json:"name,omitempty"`
	// Namespace of the Kingress implementation resource
	// +optional
	Namespace string `json:"namespace,omitempty"`
	// Type of the Kingress implementation resource
	// +optional
	Type string `json:"type,omitempty"`
}

// LoadBalancerIngressSpec represents the spec of a load-balancer ingress point:
// traffic intended for the service should be sent to an ingress point.
type LoadBalancerIngressSpec struct {
	// IP is set for load-balancer ingress points that are IP based
	// (typically GCE or OpenStack load-balancers)
	// +optional
	IP string `json:"ip,omitempty"`

	// Domain is set for load-balancer ingress points that are DNS based
	// (typically AWS load-balancers)
	// +optional
	Domain string `json:"domain,omitempty"`

	// DomainInternal is set if there is a cluster-local DNS name to access the Ingress.
	//
	// NOTE: This differs from K8s Ingress, since we also desire to have a cluster-local
	//       DNS name to allow routing in case of not having a mesh.
	//
	// +optional
	DomainInternal string `json:"domainInternal,omitempty"`

	// MeshOnly is set if the Ingress is only load-balanced through a Service mesh.
	// +optional
	MeshOnly bool `json:"meshOnly,omitempty"`
}

// DomainStatus will reflect Ready=True if the implementation accepts the Domain data
// as valid.
type DomainStatus struct {
	duckv1.Status `json:",inline"`
}

// GetStatus retrieves the status of the Domain. Implements the KRShaped interface.
func (d *Domain) GetStatus() *duckv1.Status {
	return &d.Status.Status
}


text:
export * from './config';

export * from './base.model';
export * from './affinity-group.model';
export * from './async-job.model';
export * from './capabilities.model';
export * from './color.model';
export * from './disk-offering.model';
export * from './nic.model';
export * from './os-type.model';
export * from './resource-limit.model';
export * from './service-offering.model';
export * from './snapshot.model';
export * from './ssh-keypair.model';
export * from './tag.model';
export * from './volume.model';
export * from './zone.model';
export * from './hypervisor.model';
export * from './role.model';
export * from './domain.model';
export * from './account.model';
export * from './configuration.model';
export * from './action.model';
export * from './grouping.model';
export * from './user.model';


text:
require 'rest-client'

module YhsdPrivateApp

  class HTTP

    class << self

      public

      attr_accessor :access_token

      def get(url, opts = {})
        req_headers = {}

        if opts[:headers].is_a?(Hash)
          req_headers.merge!(opts[:headers])
        end
        begin
          response = RestClient.get(url, req_headers)
          return response.code.to_i, response.body, response.raw_headers
        rescue Exception => e
          return e.http_code.to_i, e.response, {}
        end
      end

      def post(url, req_body = nil, opts = {})
        req_headers = {}

        if opts[:headers].is_a?(Hash)
          req_headers.merge!(opts[:headers])
        end

        begin
          response = RestClient.post(url, req_body, req_headers)
          return response.code.to_i, response.body, response.raw_headers
        rescue Exception => e
          return e.http_code.to_i, e.response, {}
        end
      end

      def put(url, req_body = nil, opts = {})
        req_headers = {}

        if opts[:headers].is_a?(Hash)
          req_headers.merge!(opts[:headers])
        end
        begin
          response = RestClient.put(url, req_body, req_headers)
          return response.code.to_i, response.body, response.raw_headers
        rescue Exception => e
          return e.http_code.to_i, e.response, {}
        end
      end

      def delete(url, opts = {})
        req_headers = {}

        if opts[:headers].is_a?(Hash)
          req_headers.merge!(opts[:headers])
        end
        begin
          response = RestClient.delete(url, req_headers)
          return response.code.to_i, response.body, response.raw_headers
        rescue Exception => e
          return e.http_code.to_i, e.response, {}
        end
      end

      def api_get(url)
        validate_access_token

        opts = {:headers => {
          "X-API-ACCESS-TOKEN" => @access_token
        }}

        get(url, opts)
      end

      def api_delete(url)
        validate_access_token

        opts = {:headers => {
          "X-API-ACCESS-TOKEN" => @access_token
        }}

        delete(url, opts)
      end

      def api_post(url, req_body)
        validate_access_token

        opts = {:headers => {
          "X-API-ACCESS-TOKEN" => @access_token,
          :content_type => :json,
          :accept => :json
        }}

        post(url, req_body.to_json, opts)
      end

      def api_put(url, req_body)
        validate_access_token

        opts = {:headers => {
          "X-API-ACCESS-TOKEN" => @access_token,
          :content_type => :json,
          :accept => :json
        }}

        put(url, req_body.to_json, opts)
      end

      def validate_access_token
        raise MissingAccessToken if @access_token.to_s.empty?
      end
    end

  end

end


text:
package org.clafer.ast;

import org.clafer.common.Check;

/**
 *
 * @author jimmy
 */
public class AstSetTest implements AstBoolExpr {

    private final AstSetExpr left;
    private final Op op;
    private final AstSetExpr right;

    AstSetTest(AstSetExpr left, Op op, AstSetExpr right) {
        this.left = Check.notNull(left);
        this.op = Check.notNull(op);
        this.right = Check.notNull(right);
    }

    public Op getOp() {
        return op;
    }

    public AstSetExpr getLeft() {
        return left;
    }

    public AstSetExpr getRight() {
        return right;
    }

    @Override
    public <A, B> B accept(AstExprVisitor<A, B> visitor, A a) {
        return visitor.visit(this, a);
    }

    @Override
    public String toString() {
        return left + " " + op.getSyntax() + " " + right;
    }

    public static enum Op {

        Equal("="),
        NotEqual("!=");
        private final String syntax;

        private Op(String syntax) {
            this.syntax = syntax;
        }

        public Op negate() {
            switch (this) {
                case Equal:
                    return NotEqual;
                case NotEqual:
                    return Equal;
                default:
                    throw new IllegalStateException();
            }
        }

        public String getSyntax() {
            return syntax;
        }
    }
}


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

using System;
using System.Globalization;
using java = biz.ritter.javapi;

namespace biz.ritter.javapi.util
{
    /**
     * This class represents a currency as identified in the ISO 4217 currency
     * codes.
     */
    public sealed class Currency : java.io.Serializable {

        private static readonly long serialVersionUID = -158308464356906721L;

        private RegionInfo region;

        /**
         * @param currencyCode
         */
        private Currency(RegionInfo region) {
            this.region = region;
        }

        /**
         * Returns the {@code Currency} instance for this currency code.
         *

         *
         * @param currencyCode
         *            the currency code.
         * @return the {@code Currency} instance for this currency code.
         *
         * @throws IllegalArgumentException
         *             if the currency code is not a supported ISO 4217 currency
         *             code.
         */
        public static Currency getInstance(String currencyCode) {
            foreach (Locale l in Locale.getAvailableLocales())
            {
                RegionInfo rc = new RegionInfo(l.getCountry());
                if (currencyCode.equals(rc.ISOCurrencySymbol))
                {
                    return new Currency(rc);
                }
            }
            throw new java.lang.IllegalArgumentException("currency code is not a supported ISO 4217 currency code");
        }

        /**
         * Returns the {@code Currency} instance for this {@code Locale}'s country.
         *
         * @param locale
         *            the {@code Locale} of a country.
         * @return the {@code Currency} used in the country defined by the locale parameter.
         *
         * @throws IllegalArgumentException
         *             if the locale's country is not a supported ISO 3166 Country.
         */
        public static Currency getInstance(Locale locale) {
            try
            {
                if (null == locale) throw new java.lang.NullPointerException();
                System.Globalization.RegionInfo ri = new System.Globalization.RegionInfo(locale.getCountry());
                String currencyCode = ri.ISOCurrencySymbol;

                return getInstance(currencyCode);
            }
            catch (ArgumentException ae)
            {
                throw new java.lang.IllegalArgumentException(ae.Message);
            }
        }

        /**
         * Returns this {@code Currency}'s ISO 4217 currency code.
         *
         * @return this {@code Currency}'s ISO 4217 currency code.
         */
        public String getCurrencyCode() {
            return region.ISOCurrencySymbol;
        }

        /**
         * Returns the symbol for this currency in the default locale. For instance,
         * if the default locale is the US, the symbol of the US dollar is "$". For
         * other locales it may be "US$". If no symbol can be determined, the ISO
         * 4217 currency code of the US dollar is returned.
         *
         * @return the symbol for this {@code Currency} in the default {@code Locale}.
         */
        public String getSymbol() {
            return getSymbol(Locale.getDefault());
        }

        /**
         * Returns the symbol for this currency in the given {@code Locale}.
         *

         * If the locale doesn't have any countries (e.g.
         * {@code Locale.JAPANESE, new Locale("en","")}), then the ISO
         * 4217 currency code is returned.
         *

         * First the locale's resource bundle is checked, if the locale has the same currency,
         * the CurrencySymbol in this locale bundle is returned.
         *

         * Then a currency bundle for this locale is searched.
         *

         * If a currency bundle for this locale does not exist, or there is no
         * symbol for this currency in this bundle, then the
         * ISO 4217 currency code is returned.
         *

         *
         * @param locale
         *            the locale for which the currency symbol should be returned.
         * @return the representation of this {@code Currency}'s symbol in the specified
         *         locale.
         */
        public String getSymbol(Locale locale) {
            if (null == locale) throw new java.lang.NullPointerException();
            if ("".equals(locale.getCountry())) { //$NON-NLS-1$
                return this.region.ISOCurrencySymbol;
            }
            return locale.delegateInstance.NumberFormat.CurrencySymbol;
        }

        /**
         * Returns the default number of fraction digits for this currency. For
         * instance, the default number of fraction digits for the US dollar is 2.
         * For the Japanese Yen the number is 0. In the case of pseudo-currencies,
         * such as IMF Special Drawing Rights, -1 is returned.
         *
         * @return the default number of fraction digits for this currency.
         */
        public int getDefaultFractionDigits() {
            Locale l = new Locale(this.region.Name);
            return l.delegateInstance.NumberFormat.NumberDecimalDigits;
        }

        /**
         * Returns ISO 4217 currency code.
         *
         * @return ISO 4217 currency code.
         */

        public override String ToString() {
            return region.ISOCurrencySymbol;
        }

        private Object readResolve() {
            return getInstance(this.region.ISOCurrencySymbol);
        }
    }
}