text:
'use strict'

/**
 * @fileoverview Warn if promise is checked for truthiness inside an `if` condition
 * @author Alexander Afanasyev
 */

var methodNames = [
  'isDisplayed',
  'isPresent',
  'isElementPresent',
  'isSelected',
  'isEnabled'
]

module.exports = {
  meta: {
    schema: []
  },

  create: function (context) {
    // --------------------------------------------------------------------------
    // Helpers
    // --------------------------------------------------------------------------

    /**
     * Checks if a node has a promise method called.
     * @param {ASTNode} node The AST node to check, expecting CallExpression.
     * @returns {Bool} method name, false if no promise truthiness check found.
     * @private
     */
    function hasPromiseMethod (node) {
      if (node.type === 'CallExpression' && node.callee) {
        var property = node.callee.property
        if (property && methodNames.indexOf(property.name) >= 0) {
          return property.name
        }
      }
      return false
    }
    /**
     * Checks if a node has a promise checked for truthiness.
     * @param {ASTNode} node The AST node to check.
     * @param {boolean} inBooleanPosition `false` if checking branch of a condition.
     *  `true` in all other cases
     * @returns {Bool} method name, false if no promise truthiness check found.
     * @private
     */
    function hasPromise (node, inBooleanPosition) {
      switch (node.type) {
        case 'CallExpression':
          return hasPromiseMethod(node)

        case 'UnaryExpression':
          return hasPromise(node.argument, true)

        case 'BinaryExpression':
          return hasPromise(node.left, false) || hasPromise(node.right, false)

        case 'LogicalExpression':
          var leftHasPromise = hasPromise(node.left, inBooleanPosition)
          var rightHasPromise = hasPromise(node.right, inBooleanPosition)

          return leftHasPromise || rightHasPromise

        case 'AssignmentExpression':
          return (node.operator === '=') && hasPromise(node.right, inBooleanPosition)

        case 'SequenceExpression':
          return hasPromise(node.expressions[node.expressions.length - 1], inBooleanPosition)
      }
      return false
    }

    return {
      IfStatement: function (node) {
        if (node.test) {
          var result = hasPromise(node.test, true)
          if (result) {
            context.report({
              node: node,
              message: 'Unexpected "' + result + '()" inside if condition'
            })
          }
        }
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
title:  Misjonsfortelling
date:  03/09/2021
---

#### Dilemmaet

_En irakisk familie_

Far lærte om Jesus i Irak. Han ble medlem av Adventistkirken, men ikke mor. Det ble farlige tider i Irak, og far tok med mor og de to døtrene sine og flyktet til USA.

Etter et år i Michigan flyttet de til California. Far klarte ikke vintrene i Michigan. Kulden ga ham smerter i gamle krigssår.

I California sendte de jentene på offentlig skole, men far ba om at de måtte få gå på en adventistskole. Han hadde ikke penger å betale med, men ba likevel. En dag besøkte far et suppekjøkken. Der kom han i prat med en av de frivillige som viste seg å være adventistpastor. Han fortalte også at det var en adventistmenighet som drev suppekjøkkenet, og de hadde også menighetsskole.

Far fortalte den gode nyheten til mor da han kom hjem. De hadde begynt å spare penger til studier så de kunne forsørge familien bedre. Men nå ville de heller betale for jentenes skolegang.

Far kom til menighetsskolen med mor og jentene på ni og elleve år. De strålte over hele ansiktet der de satt på rektors kontor og ville vite hva de nå skulle gjøre.

Rektoren og pastoren, som også satt der, så på hverandre. Familiens glade ansikter rev i hjerterøttene. Mor og fars sparepenger var ikke nok.

"Vi vil gjerne ha jentene her," sa rektor. "Men det er ikke nok til skolepengene." Rektor så på pastoren igjen. Hun så hans medfølelse og fortsatte: "Vi skriver inn jentene," sa hun. "Vi setter vår lit til at Gud vil skaffe midlene."

Alle seks knelte. "Gud, vi trenger din hjelp," ba pastoren. "Vi ber deg skaffe midlene til jentenes skolegang."

Da familien hadde gått, ringte telefonen. Det var lederen for flyktningavdelingen i divisjonen. Hun ringte for å si at hun hadde midler til skolepenger for flyktningbarn som ville gå på skolen. Pengene kom fra adventister verden over som hadde gitt et 13. sabbats offer i 2011.

Rektor trodde nesten ikke sine egne ører. Hun ringte far og sa at jentenes skolepenger var ordnet. "Jeg visste at Gud ville høre våre bønner," sa far.

En del av offeret dette kvartalet går igjen til å hjelpe flyktninger i Den nordamerikanske divisjon. Måtte Gud bruke dine gaver til å høre slike bønner som dette. Tenk å få møte noen i himmelen som fikk lære mer om Gud og valgte å tjene ham fordi du ga.

Misjonsnytt avslører ikke familiens identitet av hensyn til deres sikkerhet. Du finner bilder på Facebook: bit.ly/fb-mq.


text: Animation By Swift


text:
package org.apache.pig.builtin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pig.EvalFunc;
import org.apache.pig.FuncSpec;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.joda.time.DateTime;

/**
 *

 * ToMilliSeconds converts the DateTime to the number of milliseconds that have passed
 * since January 1, 1970 00:00:00.000 GMT.
 *

 *

 *
Jodatime: http://joda-time.sourceforge.net/

 *
ISO8601 Date Format: http://en.wikipedia.org/wiki/ISO_8601

 *
Unix Time: http://en.wikipedia.org/wiki/Unix_time

 *

 *

 *

 * Example usage:
 *
 * ISOin = LOAD 'test.tsv' USING PigStorage('\t') AS (dt:datetime, dt2:datetime);
 *
 * DESCRIBE ISOin;
 * ISOin: {dt: datetime,dt2: datetime}
 *
 * DUMP ISOin;
 *
 * (2009-01-07T01:07:01.000Z,2008-02-01T00:00:00.000Z)
 * (2008-02-06T02:06:02.000Z,2008-02-01T00:00:00.000Z)
 * (2007-03-05T03:05:03.000Z,2008-02-01T00:00:00.000Z)
 * ...
 *
 * toMilliSeconds = FOREACH ISOin GENERATE ToMilliSeconds(dt) AS unixTime:long;
 *
 * DESCRIBE toMilliSeconds;
 * toMilliSeconds: {unixTime: long}
 *
 * DUMP toMilliSeconds;
 *
 * (1231290421000L)
 * (1202263562000L)
 * (1173063903000L)
 * ...
 *

 */
public class ToMilliSeconds extends EvalFunc<Long> {

    @Override
    public Long exec(Tuple input) throws IOException
    {
        if (input == null || input.size() < 1 || input.get(0) == null) {
            return null;
        }

        DateTime result = (DateTime) input.get(0);

        return result.getMillis();
    }

    @Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input), DataType.LONG));
    }

    @Override
    public List<FuncSpec> getArgToFuncMapping() throws FrontendException {
        List<FuncSpec> funcList = new ArrayList<FuncSpec>();
        funcList.add(new FuncSpec(this.getClass().getName(), new Schema(new Schema.FieldSchema(null, DataType.DATETIME))));

        return funcList;
    }
}


text:
package com.domnian.mcutils.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ConfigNode {

    String value();
}


text:
package uk.ac.imperial.doc.pctmc.expressions;

public interface IPopulationVisitor {
	public void visit(PopulationExpression e);
}


text:
"""
  A docstring with a wrong indentation.
  Docstring should have consistent indentations.
"""

class foo:
    '''The opening/closing of docstring should be on a line by themselves'''

    def a(self):
       """
         A docstring with a wrong indentation.
         """
       pass

    def b(self, argument1):
        """
        This docstring should contain epytext markups of argument1.
        """
        pass

    def c(self, argument1):
        """
        This docstring should contain a @param markup of argument1.

        @type argument1: C{str}
        """
        pass

    def d(self, _argument1):
        """
        This docstring should contain a @type markup of _argument1.

        @param _argument1: a argument
        """
        pass

    def e(self):
        """
        This docstring should contain a @return and @rtype markup.
        """
        return 1

    def f(self):
        """
        This docstring should contain a @return markup.

        @rtype: C{int}
        """
        return 1

    def g(self):
        """
        This docstring should contain a @rtype markup.

        @return: just return 1
        """
        return 1

    def h(self, a):
        """
        There should be a blank line before epytext markups
        @param a: a argument
        @type a: C{int}
        @return: return a
        @rtype: C{int}
        """
        return a

    def i(self):
        '''
            A docstring begins with single quotes,
            and have wrong indentation.
        '''
        pass

    def aCrazyMethod(this, self):
        """
        This is an example method using 'this' as a replacement of 'self'.
        This docstring should contain epytext for the parameter 'self'.
        By the way, this example will cause a fatal error E0213 in pylint.
        """
        pass

    def l(self):
        # Missing docstring.
        pass

    def m(self):
        """
        """
        # Empty docstring.
        pass

    @property
    def goodGetterBadSetter(self):
        """
        Getter properties used to check for invalid setter docstring.
        """
        return True

    @goodGetterBadSetter.setter
    def goodGetterBadSetter(self, val):
        """
        Setter properties docstring exception is only for arguments
        named `value`.
        """

def moduleLevelFunctionWithoutDocstring():
    pass


text:
shadowing a global function with a local version
--FILE--
<?php

namespace {
    require 'includes/global_bar.php';
    require 'includes/foo_bar.php';
}

namespace {
    var_dump(bar());
}

namespace {
    use function foo\bar;
    var_dump(bar());
    echo "Done\n";
}

?>
--EXPECT--
string(10) "global bar"
string(9) "local bar"
Done


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

namespace Mosa.TinyCPUSimulator.x86.Emulate
{
	public class PowerUp : BaseSimDevice
	{
		public readonly uint VectorReset = 0xFFFFFFF0;
		public readonly string VectorCall = "System.Void Default::StartUp()";

		public PowerUp(SimCPU simCPU)
			: base(simCPU)
		{
		}

		public override void Initialize()
		{
			var x86 = simCPU as CPUx86;

			simCPU.AddMemory(0x00000000, 0x000A0000, 1); // First 640kb
			simCPU.AddMemory(VectorReset, 0x0000000F, 2); // Vector Reset

			simCPU.AddInstruction(VectorReset, new SimInstruction(Opcode.Call, 32, SimOperand.CreateLabel(32, VectorCall), 4));
		}

		public override void Reset()
		{
			var x86 = simCPU as CPUx86;

			// Start of stack
			x86.ESP.Value = 0x00080000;
			x86.EBP.Value = x86.ESP.Value;

			// Start EIP
			x86.EIP.Value = VectorReset;
		}
	}
}


text:
from natural.constant import _, _multi
import datetime

# Wed, 02 Oct 2002 08:00:00 EST
# Wed, 02 Oct 2002 13:00:00 GMT
# Wed, 02 Oct 2002 15:00:00 +0200
RFC2822_DATETIME_FORMAT = '%a, %d %b %Y %T %z'
# Wed, 02 Oct 02 08:00:00 EST
# Wed, 02 Oct 02 13:00:00 GMT
# Wed, 02 Oct 02 15:00:00 +0200
RFC822_DATETIME_FORMAT  = '%a, %d %b %y %T %z'
# 2012-06-13T15:24:17
ISO8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
# Wed, 02 Oct 2002
RFC2822_DATE_FORMAT     = '%a, %d %b %Y'
# Wed, 02 Oct 02
RFC2822_DATE_FORMAT     = '%a, %d %b %y'
# 2012-06-13
ISO8601_DATE_FORMAT     = '%Y-%m-%d'

def _to_datetime(t):
    '''
    Internal function that tries whatever to convert ``t`` into a
    :class:`datetime.datetime` object.
    '''

    if isinstance(t, float) or \
        isinstance(t, int) or \
        isinstance(t, long):
        return datetime.datetime.fromtimestamp(float(t))

    elif isinstance(t, basestring):
        for format in (
            RFC2822_DATETIME_FORMAT,
            RFC822_DATETIME_FORMAT,
            ISO8601_DATETIME_FORMAT,
            ):
            try:
                return datetime.datetime.strptime(t, format)
            except ValueError:
                pass

        raise ValueError('Format not supported')

    elif isinstance(t, datetime.datetime):
        return t

    elif isinstance(t, datetime.date):
        return datetime.datetime.combine(t, datetime.time(0, 0))

    else:
        raise TypeError

def _to_date(t):
    '''
    Internal function that tries whatever to convert ``t`` into a
    :class:`datetime.date` object.
    '''

    if isinstance(t, float) or \
        isinstance(t, int) or \
        isinstance(t, long):
        return datetime.date.fromtimestamp(float(t))

    elif isinstance(t, basestring):
        for format in (
            RFC2822_DATE_FORMAT,
            RFC822_DATE_FORMAT,
            ISO8601_DATE_FORMAT,
            ):
            try:
                return datetime.datetime.strptime(t, format).date()
            except ValueError:
                pass

        raise ValueError('Format not supported')

    elif isinstance(t, datetime.datetime):
        return t.date()

    elif isinstance(t, datetime.date):
        return t

    else:
        raise TypeError

def delta(t1, t2, words=True):
    '''
    Calculates the estimated delta between two time objects in human-readable
    format. Used internally by the :func:`day` and :func:`duration` functions.

    :param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
               object
    :param t2: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
               object
    '''

    t1 = _to_datetime(t1)
    t2 = _to_datetime(t2)
    diff = t1 - t2

    if diff.days == 0:
        if diff.seconds < 10 and words:
            return (
                _(u'just now'),
                0,
            )

        elif diff.seconds < 60:
            return (
                _multi(
                    _(u'%d second'),
                    _(u'%d seconds'),
                diff.seconds) % (diff.seconds,),
                0,
            )
        elif diff.seconds < 120 and words:
            return (
                _(u'a minute'),
                0,
            )

        elif diff.seconds < 3600:
            minutes, seconds = divmod(diff.seconds, 60)
            return (
                _multi(
                    _(u'%d minute'),
                    _(u'%d minutes'),
                minutes) % (minutes,),
                seconds,
            )
        elif diff.seconds < 7200 and words:
            return (
                _(u'an hour'),
                0,
            )

        elif diff.seconds < 86400:
            hours, seconds = divmod(diff.seconds, 3600)
            return (
                _multi(
                    _(u'%d hour'),
                    _(u'%d hours'),
                hours) % (hours,),
                seconds,
            )

    elif diff.days == 1 and words:
        return (
            _(u'yesterday'),
            0,
        )

    elif diff.days < 7:
        return (
            _multi(
                _(u'%d day'),
                _(u'%d days'),
            diff.days) % (diff.days,),
            diff.seconds,
        )

    elif diff.days < 31:
        weeks, days = divmod(diff.days, 7)
        seconds = days * 86400 + diff.seconds
        return (
            _multi(
                _(u'%d week'),
                _(u'%d weeks'),
            weeks) % (weeks,),
            seconds,
        )

    elif diff.days < 365:
        months, days = divmod(diff.days, 30)
        seconds = days * 86400 + diff.seconds
        return (
            _multi(
                _(u'%d month'),
                _(u'%d months'),
            months) % (months,),
            seconds,
        )

    else:
        years, days = divmod(diff.days, 365)
        seconds = days * 86400 + diff.seconds
        return (
            _multi(
                _(u'%d year'),
                _(u'%d years'),
            years) % (years,),
            seconds,
        )

def day(t, now=None, format='%B %d'):
    '''
    Date delta compared to ``t``. You can override ``now`` to specify what date
    to compare to.

    You can override the date format by supplying a ``format`` parameter.

    :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
              object
    :param now: default ``None``, optionally a :class:`datetime.datetime`
                object
    :param format: default ``'%B %d'``
    '''
    t1 = _to_date(t)
    t2 = _to_date(now or datetime.datetime.now())
    diff = max(t1, t2) - min(t1, t2)

    if diff.days == 0:
        return _(u'today')
    elif diff.days == 1:
        if t1 < t2:
            return _(u'yesterday')
        else:
            return _(u'tomorrow')
    elif diff.days == 7:
        if t1 < t2:
            return _(u'last week')
        else:
            return _(u'next week')
    else:
        return t1.strftime(format)

def duration(t, now=None, precision=1, pad=u', ', words=None, plain=False):
    '''
    Time delta compared to ``t``. You can override ``now`` to specify what time
    to compare to.

    :param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
              object
    :param now: default ``None``, optionally a :class:`datetime.datetime`
                object
    :param precision: default ``1``, number of fragments to return
    :param words: default ``None``, allow words like "yesterday", if set to
                  ``None`` this will be enabled if ``precision`` is set to
                  ``1``
    '''

    if words is None:
        words = precision == 1

    t1 = _to_datetime(t)
    t2 = _to_datetime(now or datetime.datetime.now())

    if not plain:
        if t1 < t2:
            format = _(u'%s ago')
        else:
            format = _(u'%s from now')
    else: format = _(u'%s')

    result, remains = delta(max(t1, t2), min(t1, t2), words=words)
    if result in (_(u'just now'), _(u'yesterday')):
        return result
    elif precision > 1 and remains:
        t3 = t2 - datetime.timedelta(seconds=remains)
        return pad.join([
            result,
            duration(t3, t2, precision - 1, pad, words=False),
        ])
    else:
        return format % (result,)

def compress(t, sign=False, pad=u''):
    '''
    Convert the input to compressed format, works with a
    :class:`datetime.timedelta` object or a number that represents the number
    of seconds you want to compress.  If you supply a timestamp or a
    :class:`datetime.datetime` object, it will give the delta relative to the
    current time.

    You can enable showing a sign in front of the compressed format with the
    ``sign`` parameter, the default is not to show signs.

    Optionally, you can chose to pad the output. If you wish your values to be
    separated by spaces, set ``pad`` to ``' '``.

    :param t: seconds or :class:`datetime.timedelta` object
    :param sign: default ``False``
    :param pad: default ``u''``
    '''

    if isinstance(t, datetime.timedelta):
        seconds = t.seconds + (t.days * 86400)
    elif isinstance(t, float) or isinstance(t, int) or isinstance(t, long):
        seconds = long(t)
    else:
        return compress(datetime.datetime.now() - _to_datetime(t), sign, pad)

    parts = []
    if sign:
        parts.append(u'-' if d.days < 0 else u'+')

    weeks, seconds   = divmod(seconds, 604800)
    days, seconds    = divmod(seconds, 86400)
    hours, seconds   = divmod(seconds, 3600)
    minutes, seconds = divmod(seconds, 60)

    if weeks:
        parts.append(_(u'%dw') % (weeks,))
    if days:
        parts.append(_(u'%dd') % (days,))
    if hours:
        parts.append(_(u'%dh') % (hours,))
    if minutes:
        parts.append(_(u'%dm') % (minutes,))
    if seconds:
        parts.append(_(u'%ds') % (seconds,))

    return pad.join(parts)


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

using GroupControl.Model;

namespace GroupControl.IBLL
{
    public interface IAutoServiceInfoBLL : IBaseBLL<AutoServiceInfo, AutoServiceInfoViewModel>
    {
        /// <summary>
        /// 添加任务关联多个或者一个设备
        /// </summary>
        /// <param name="viewModel"></param>
        int AddFriendTask(AutoServiceInfoViewModel viewModel);

        /// <summary>
        /// 获取当前任务相关连的设备
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        IList<AutoServiceToDevice> GetTaskAboutDeviceList(AutoServiceInfoViewModel viewModel);

        /// <summary>
        /// /获取跟任务列表相关的分组列表
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>

        IList<AutoServiceInfoViewModel> GetTaskListWithGroupInfo(AutoServiceInfoViewModel viewModel);
    }
}


text:
namespace Ploeh.AutoFixtureDocumentationTest.Array
{
    public class MyClassA
    {
        public MyClassB[] Items;
        public MyClassC C;
        public MyClassD D;
    }
}


text:
var ProLog = require('../lib/prolog').ProLog;
var $ = require('chalk');
var util = require('util');

// Instantiate logger with custom options.
var log = new ProLog({
  // Custom formatting function (fancy padding).
  format: function(data) {
    var pad = data.indent === 0 ? '' :
      $.gray('├' + Array(data.indent * 2).join('─') + ' ');
    return data.message.split('\n').map(function(line) {
      return util.format(data.format, pad, line);
    }).join('\n');
  },
  // Custom logging levels and format strings.
  levels: {
    log: {priority: 1, format: 'log' + ' %s' + '%s'},
    info: {priority: 2, format: $.cyan('inf') + ' %s' + $.cyan('%s')},
    success: {priority: 3, format: $.green('yay') + ' %s' + $.green('%s')},
    error: {priority: 4, format: $.bgRed.white('wtf') + ' %s' + $.red('%s')},
  },
});

// You can log a single string.
log.log('This is a test log message.');
log.info('This is a test info message.');
log.error(new Error('This is a test error message.').stack);
log.success('This is a test success message.');

// Or anything you'd send to console.log, really.
log.log('Testing log %s: %d, %j.', 'A', 1, {a: 1});
log.log([['This', 'array', 'will', 'be'], ['logged', 'over'], ['multiple', 'lines.']]);
log.info('Testing info %s: %d, %j.', 'A', 2, {b: 2});
log.error('Testing error %s: %d, %j.', 'A', 5, {e: 5});
log.success('Testing success %s: %d, %j.', 'A', 6, {e: 6});

// You can group messages as well.
log.group();
log.log('This log message should be indented once.');
log.group();
log.info('This info message should be indented twice.');
log.groupEnd();
log.error('This error message should be indented once.');
log.groupEnd();
log.success('This success message should not be indented.');


text:
using System;
using JetBrains.Annotations;
using Txt.Core;

namespace Txt.ABNF
{
    public class Alternation : Element
    {
        /// <summary>
        /// </summary>
        /// <param name="alternation"></param>
        /// <exception cref="ArgumentNullException">The value of <paramref name="alternation" /> is a null reference.</exception>
        public Alternation([NotNull] Alternation alternation)
            : base(alternation)
        {
            Ordinal = alternation.Ordinal;
            Element = alternation.Element;
        }

        /// <summary>
        /// </summary>
        /// <param name="sequence">The text in the Alternationon.</param>
        /// <param name="alternative">The matched Alternation.</param>
        /// <param name="context">An object that describes the current element's context.</param>
        /// <param name="ordinal">The ordinal position of the matching Alternation.</param>
        /// <exception cref="ArgumentNullException">The value of <paramref name="alternative" /> is a null reference.</exception>
        public Alternation(
            [NotNull] string sequence,
            [NotNull] Element alternative,
            [NotNull] ITextContext context,
            int ordinal)
            : base(sequence, new[] { alternative }, context)
        {
            Element = alternative;
            Ordinal = ordinal;
        }

        [NotNull]
        public Element Element { get; }

        public int Ordinal { get; }
    }
}


text:
package com.intellij.java.refactoring;

import com.intellij.JavaTestUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import com.intellij.refactoring.MultiFileTestCase;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesProcessor;
import com.intellij.refactoring.move.moveClassesOrPackages.MultipleRootsMoveDestination;
import com.intellij.testFramework.PsiTestUtil;
import org.jetbrains.annotations.NotNull;

/**
 *  @author dsl
 */
public class MovePackageMultirootTest extends MultiFileTestCase {

  @Override
  protected String getTestDataPath() {
    return JavaTestUtil.getJavaTestDataPath();
  }

  @NotNull
  @Override
  protected String getTestRoot() {
    return "/refactoring/movePackageMultiroot/";
  }

  public void testMovePackage() {
    doTest(createAction(new String[]{"pack1"}, "target"));
  }

  private PerformAction createAction(final String[] packageNames, final String targetPackageName) {
    return (rootDir, rootAfter) -> {
      final PsiManager manager = PsiManager.getInstance(myProject);
      PsiPackage[] sourcePackages = new PsiPackage[packageNames.length];
      for (int i = 0; i < packageNames.length; i++) {
        String packageName = packageNames[i];
        sourcePackages[i] = JavaPsiFacade.getInstance(manager.getProject()).findPackage(packageName);
        assertNotNull(sourcePackages[i]);
      }
      PsiPackage targetPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(targetPackageName);
      assertNotNull(targetPackage);
      new MoveClassesOrPackagesProcessor(myProject, sourcePackages,
                                         new MultipleRootsMoveDestination(new PackageWrapper(targetPackage)),
                                         true, true, null).run();
      FileDocumentManager.getInstance().saveAllDocuments();
    };
  }

  @Override
  protected void prepareProject(VirtualFile rootDir) {
    PsiTestUtil.addContentRoot(myModule, rootDir);
    final VirtualFile[] children = rootDir.getChildren();
    for (VirtualFile child : children) {
      if (child.getName().startsWith("src")) {
        PsiTestUtil.addSourceRoot(myModule, child);
      }
    }
  }
}


text:
<?php

namespace Amadeus\Client\Struct\Pnr\AddMultiElements;

/**
 * TravelProduct
 *
 * @package Amadeus\Client\Struct\Pnr\AddMultiElements
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class TravelProduct
{
    /**
     * date and time details
     *
     * @var Product
     */
    public $product;

    /**
     * boardpoint details
     *
     * @var BoardOffPointDetail
     */
    public $boardpointDetail;

    /**
     * offpoint details
     *
     * @var BoardOffPointDetail
     */
    public $offpointDetail;

    /**
     * airline or system code
     *
     * @var Company
     */
    public $company;

    /**
     * product details - number and class
     *
     * @var ProductDetails
     */
    public $productDetails;

    /**
     * Product type details. Here: availability context.
     *
     * @var FlightTypeDetails
     */
    public $flightTypeDetails;

    /**
     * B Boarding pass may not be issued until
     * N No action required
     * NB No a boarding pass may not be issued
     * P01 Explosion indicator for SSR input
     * P02 Validated indicator of Frequent Flyer SSR
     * Y Yes a boarding pass may be issued
     *
     * @var
     */
    public $processingIndicator;

    /**
     * TravelProduct constructor.
     *
     * @param \DateTime|null $date
     * @param string|null $departureCode
     * @param string|null $company
     */
    public function __construct($date = null, $departureCode = null, $company = null)
    {
        if ($date instanceof \DateTime) {
            $this->product = new Product($date);
        }

        if (!empty($departureCode)) {
            $this->boardpointDetail = new BoardOffPointDetail($departureCode);
        }

        if (!empty($company)) {
            $this->company = new Company($company);
        }
    }
}


text:
require 'vk/api/responses'

module Vk
  module API
    class Stats < Vk::Schema::Namespace
      module Responses
        # @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        class GetPostReachResponse < Vk::Schema::Response
          # @return [Array] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
          attribute :response, API::Types::Coercible::Array.member(API::Stats::WallpostStat).optional.default(nil)
        end
      end
    end
  end
end


text:
package org.renjin.primitives;

import org.renjin.eval.Context;
import org.renjin.eval.EvalException;
import org.renjin.primitives.annotations.processor.ArgumentException;
import org.renjin.primitives.annotations.processor.ArgumentIterator;
import org.renjin.primitives.annotations.processor.WrapperRuntime;
import org.renjin.primitives.random.RNG;
import org.renjin.sexp.BuiltinFunction;
import org.renjin.sexp.DoubleVector;
import org.renjin.sexp.Environment;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.IntVector;
import org.renjin.sexp.LogicalVector;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;

public class R$primitive$rmultinom
    extends BuiltinFunction
{

    public R$primitive$rmultinom() {
        super("rmultinom");
    }

    public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) {
        try {
            ArgumentIterator argIt = new ArgumentIterator(context, environment, args);
            SEXP s0 = argIt.evalNext();
            SEXP s1 = argIt.evalNext();
            SEXP s2 = argIt.evalNext();
            if (!argIt.hasNext()) {
                return this.doApply(context, environment, s0, s1, s2);
            }
            throw new EvalException("rmultinom: too many arguments, expected at most 3.");
        } catch (ArgumentException e) {
            throw new EvalException(context, "Invalid argument: %s. Expected:\n\trmultinom(integer(1), integer(1), DoubleVector)", e.getMessage());
        } catch (EvalException e) {
            e.initContext(context);
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new EvalException(e);
        }
    }

    public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
        try {
            if ((args.length) == 3) {
                return doApply(context, environment, args[ 0 ], args[ 1 ], args[ 2 ]);
            }
        } catch (EvalException e) {
            e.initContext(context);
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new EvalException(e);
        }
        throw new EvalException("rmultinom: max arity is 3");
    }

    public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
        return R$primitive$rmultinom.doApply(context, environment, call, argNames, args);
    }

    public static SEXP doApply(Context context, Environment environment, SEXP arg0, SEXP arg1, SEXP arg2)
        throws Exception
    {
        if (((((arg0 instanceof IntVector)||(arg0 instanceof DoubleVector))||(arg0 instanceof LogicalVector))&&(((arg1 instanceof IntVector)||(arg1 instanceof DoubleVector))||(arg1 instanceof LogicalVector)))&&(arg2 instanceof DoubleVector)) {
            return RNG.rmultinom(context, WrapperRuntime.convertToInt(arg0), WrapperRuntime.convertToInt(arg1), ((DoubleVector) arg2));
        } else {
            throw new EvalException(String.format("Invalid argument:\n\trmultinom(%s, %s, %s)\n\tExpected:\n\trmultinom(integer(1), integer(1), DoubleVector)", arg0 .getTypeName(), arg1 .getTypeName(), arg2 .getTypeName()));
        }
    }

}


text:
WaveVideo Provider
Make your own videos and host them with Wave.video.
Build your entire video funnel. Sign up now...

## Implementation Details

- Provider
Name: WaveVideo
- Documentation: NONE
- HTTPS support: NO
- Fake Response: YES
- Oembed Params: maxwidth , maxheight
- Supported Hosts: watch.wave.video , embed.wave.video
- Responsive response: NO
- Collections: DefaultProviderCollection


text:
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import AboutUs, Gallery
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from blog.views import Notice

# Create your views here.
def our_hotel(request):
    ourhotels = AboutUs.objects.filter(category="Hotel")
    ourservice = AboutUs.objects.filter(category="Service")
    location = AboutUs.objects.filter(category="Location")
    questions = AboutUs.objects.filter(category="FAQ")
    return render(request, 'hotel/our_hotel.html', {'ourhotels': ourhotels, 'questions': questions, 'ourservice': ourservice, 'location': location})

def public(request):
	images = Gallery.objects.all()
	notices = Notice.objects.filter(privacy="Public").filter(published_date__lte=timezone.now()).order_by('-published_date')[:3]
	return render(request, 'hotel/home.html', {'images': images, 'notices': notices})

def gallery(request):
	images = Gallery.objects.all()
	return render(request, 'hotel/hotel_gallery.html', {'images': images})

def rooms(request):
 	hotel = Gallery.objects.filter(category="Hotel")
 	return render(request, 'hotel/rooms.html', {'hotel': hotel})


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Zusätzliche Nutzungsbedingungen für Google Chrome und Chrome OS</title>

 Zusätzliche Nutzungsbedingungen für Google Chrome und Chrome OS

 Letzte Änderung: 1. Januar 2021

 Wenn Sie Chrome oder Chrome OS nutzen, stimmen Sie damit den Nutzungsbedingungen von Google unter https://policies.google.com/terms sowie diesen zusätzlichen Nutzungsbedingungen für Google Chrome und Chrome OS zu.

 Diese zusätzlichen Nutzungsbedingungen für Google Chrome und Chrome OS gelten für die ausführbare Codeversion von Chrome und Chrome OS. Der größte Teil des Quellcodes von Chrome ist im Rahmen von Open-Source-Softwarelizenzvereinbarungen auf https://code.google.com/chromium/terms.html kostenlos erhältlich.

 Die Nutzung bestimmter Komponenten von Chrome und Chrome OS unterliegt den folgenden Bedingungen:

   AVC

  DIESES PRODUKT IST IM RAHMEN DER AVC-PATENT-PORTFOLIO-LIZENZ FÜR DIE PERSÖNLICHE NUTZUNG DURCH EINEN VERBRAUCHER ODER ANDERE VERGÜTUNGSFREIE VERWENDUNGSZWECKE LIZENZIERT, BEI DENEN MIT DIESEM PRODUKT (i) VIDEO ENTSPRECHEND DEM AVC-STANDARD ("AVC-VIDEO") CODIERT WIRD UND/ODER (ii) AVC-VIDEO DECODIERT WIRD, DAS VON EINEM VERBRAUCHER IM RAHMEN EINER PERSÖNLICHEN AKTIVITÄT CODIERT WURDE UND/ODER DAS VON EINEM ENTSPRECHEND LIZENZIERTEN VIDEOANBIETER BEREITGESTELLT WURDE. FÜR JEDWEDE ANDERE NUTZUNG WIRD KEINE LIZENZ GEWÄHRT BZW. IMPLIZIERT. WEITERE INFORMATIONEN ERHALTEN SIE BEI MPEG LA, L.L.C. UNTER HTTP://WWW.MPEGLA.COM.

 Darüber hinaus unterliegt die Nutzung bestimmter Komponenten von Chrome OS den folgenden Bedingungen:

   MPEG-4

  DIESES PRODUKT IST IM RAHMEN DER MPEG-4 VISUAL-PATENT-PORTFOLIO-LIZENZ FÜR DIE PERSÖNLICHE UND NICHT KOMMERZIELLE NUTZUNG DURCH EINEN VERBRAUCHER LIZENZIERT, DER MIT DIESEM PRODUKT (i) VIDEOMATERIAL ENTSPRECHEND DEM MPEG-4 VISUAL-STANDARD ("MPEG-4-VIDEO") CODIEREN UND/ODER (ii) MPEG-4-VIDEO DECODIEREN DARF, DAS VON EINEM VERBRAUCHER IM RAHMEN EINER PERSÖNLICHEN UND NICHT KOMMERZIELLEN AKTIVITÄT CODIERT WURDE UND/ODER VON EINEM DURCH MPEG LA ENTSPRECHEND LIZENZIERTEN VIDEOANBIETER BEREITGESTELLT WURDE. FÜR JEDWEDE ANDERE NUTZUNG WIRD KEINE LIZENZ GEWÄHRT BZW. IMPLIZIERT. WEITERE INFORMATIONEN, U. A. ZUR WERBEBEZOGENEN, INTERNEN UND KOMMERZIELLEN NUTZUNG SOWIE ZUR LIZENZIERUNG, ERHALTEN SIE BEI MPEG LA, LLC UNTER HTTP://WWW.MPEGLA.COM.


text:
<?php

// Call Zend_LoaderTest::main() if this source file is executed directly.
if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Zend_LoaderTest::main');
}

/**
 * Test helper
 */
require_once dirname(__FILE__) . '/../TestHelper.php';

/**
 * Zend_Loader
 */
require_once 'Zend/Loader.php';

/**
 * Zend_Loader_Autoloader
 */
require_once 'Zend/Loader/Autoloader.php';

/**
 * @category   Zend
 * @package    Zend_Loader
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Loader
 */
class Zend_LoaderTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        require_once "PHPUnit/TextUI/TestRunner.php";

        $suite  = new PHPUnit_Framework_TestSuite("Zend_LoaderTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function setUp()
    {
        // Store original autoloaders
        $this->loaders = spl_autoload_functions();
        if (!is_array($this->loaders)) {
            // spl_autoload_functions does not return empty array when no
            // autoloaders registered...
            $this->loaders = array();
        }

        // Store original include_path
        $this->includePath = get_include_path();

        $this->error = null;
        $this->errorHandler = null;
        Zend_Loader_Autoloader::resetInstance();
    }

    public function tearDown()
    {
        if ($this->errorHandler !== null) {
            restore_error_handler();
        }

        // Restore original autoloaders
        $loaders = spl_autoload_functions();
        if (is_array($loaders)) {
            foreach ($loaders as $loader) {
                spl_autoload_unregister($loader);
            }
        }

        if (is_array($this->loaders)) {
            foreach ($this->loaders as $loader) {
                spl_autoload_register($loader);
            }
        }

        // Retore original include_path
        set_include_path($this->includePath);

        // Reset autoloader instance so it doesn't affect other tests
        Zend_Loader_Autoloader::resetInstance();
    }

    public function setErrorHandler()
    {
        set_error_handler(array($this, 'handleErrors'), E_USER_NOTICE);
        $this->errorHandler = true;
    }

    public function handleErrors($errno, $errstr)
    {
        $this->error = $errstr;
    }

    /**
     * Tests that a class can be loaded from a well-formed PHP file
     */
    public function testLoaderClassValid()
    {
        $dir = implode(array(dirname(__FILE__), '_files', '_testDir1'), DIRECTORY_SEPARATOR);

        Zend_Loader::loadClass('Class1', $dir);
    }

    public function testLoaderInterfaceViaLoadClass()
    {
        try {
            Zend_Loader::loadClass('Zend_Controller_Dispatcher_Interface');
        } catch (Zend_Exception $e) {
            $this->fail('Loading interfaces should not fail');
        }
    }

    public function testLoaderLoadClassWithDotDir()
    {
        $dirs = array('.');
        try {
            Zend_Loader::loadClass('Zend_Version', $dirs);
        } catch (Zend_Exception $e) {
            $this->fail('Loading from dot should not fail');
        }
    }

    /**
     * Tests that an exception is thrown when a file is loaded but the
     * class is not found within the file
     */
    public function testLoaderClassNonexistent()
    {
        $dir = implode(array(dirname(__FILE__), '_files', '_testDir1'), DIRECTORY_SEPARATOR);

        try {
            Zend_Loader::loadClass('ClassNonexistent', $dir);
            $this->fail('Zend_Exception was expected but never thrown.');
        } catch (Zend_Exception $e) {
            $this->assertRegExp('/file(.*)does not exist or class(.*)not found/i', $e->getMessage());
        }
    }

    /**
     * Tests that an exception is thrown if the $dirs argument is
     * not a string or an array.
     */
    public function testLoaderInvalidDirs()
    {
        try {
            Zend_Loader::loadClass('Zend_Invalid_Dirs', new stdClass());
            $this->fail('Zend_Exception was expected but never thrown.');
        } catch (Zend_Exception $e) {
            $this->assertEquals('Directory argument must be a string or an array', $e->getMessage());
        }
    }

    /**
     * Tests that a class can be loaded from the search directories.
     */
    public function testLoaderClassSearchDirs()
    {
        $dirs = array();
        foreach (array('_testDir1', '_testDir2') as $dir) {
            $dirs[] = implode(array(dirname(__FILE__), '_files', $dir), DIRECTORY_SEPARATOR);
        }

        // throws exception on failure
        Zend_Loader::loadClass('Class1', $dirs);
        Zend_Loader::loadClass('Class2', $dirs);
    }

    /**
     * Tests that a class locatedin a subdirectory can be loaded from the search directories
     */
    public function testLoaderClassSearchSubDirs()
    {
        $dirs = array();
        foreach (array('_testDir1', '_testDir2') as $dir) {
            $dirs[] = implode(array(dirname(__FILE__), '_files', $dir), DIRECTORY_SEPARATOR);
        }

        // throws exception on failure
        Zend_Loader::loadClass('Class1_Subclass2', $dirs);
    }

    /**
     * Tests that the security filter catches illegal characters.
     */
    public function testLoaderClassIllegalFilename()
    {
        try {
            Zend_Loader::loadClass('/path/:to/@danger');
            $this->fail('Zend_Exception was expected but never thrown.');
        } catch (Zend_Exception $e) {
            $this->assertRegExp('/security(.*)filename/i', $e->getMessage());
        }
    }

    /**
     * Tests that loadFile() finds a file in the include_path when $dirs is null
     */
    public function testLoaderFileIncludePathEmptyDirs()
    {
        $saveIncludePath = get_include_path();
        set_include_path(implode(array($saveIncludePath, implode(array(dirname(__FILE__), '_files', '_testDir1'), DIRECTORY_SEPARATOR)), PATH_SEPARATOR));

        $this->assertTrue(Zend_Loader::loadFile('Class3.php', null));

        set_include_path($saveIncludePath);
    }

    /**
     * Tests that loadFile() finds a file in the include_path when $dirs is non-null
     * This was not working vis-a-vis ZF-1174
     */
    public function testLoaderFileIncludePathNonEmptyDirs()
    {
        $saveIncludePath = get_include_path();
        set_include_path(implode(array($saveIncludePath, implode(array(dirname(__FILE__), '_files', '_testDir1'), DIRECTORY_SEPARATOR)), PATH_SEPARATOR));

        $this->assertTrue(Zend_Loader::loadFile('Class4.php', implode(PATH_SEPARATOR, array('foo', 'bar'))));

        set_include_path($saveIncludePath);
    }

    /**
     * Tests that isReadable works
     */
    public function testLoaderIsReadable()
    {
        $this->assertTrue(Zend_Loader::isReadable(__FILE__));
        $this->assertFalse(Zend_Loader::isReadable(__FILE__ . '.foobaar'));

        // test that a file in include_path gets loaded, see ZF-2985
        $this->assertTrue(Zend_Loader::isReadable('Zend/Controller/Front.php'), get_include_path());
    }

    /**
     * Tests that autoload works for valid classes and interfaces
     */
    public function testLoaderAutoloadLoadsValidClasses()
    {
        $this->setErrorHandler();
        $this->assertEquals('Zend_Db_Profiler_Exception', Zend_Loader::autoload('Zend_Db_Profiler_Exception'));
        $this->assertContains('deprecated', $this->error);
        $this->error = null;
        $this->assertEquals('Zend_Auth_Storage_Interface', Zend_Loader::autoload('Zend_Auth_Storage_Interface'));
        $this->assertContains('deprecated', $this->error);
    }

    /**
     * Tests that autoload returns false on invalid classes
     */
    public function testLoaderAutoloadFailsOnInvalidClasses()
    {
        $this->setErrorHandler();
        $this->assertFalse(Zend_Loader::autoload('Zend_FooBar_Magic_Abstract'));
        $this->assertContains('deprecated', $this->error);
    }

    public function testLoaderRegisterAutoloadRegisters()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload not installed on this PHP installation");
        }

        $this->setErrorHandler();
        Zend_Loader::registerAutoload();
        $this->assertContains('deprecated', $this->error);

        $autoloaders = spl_autoload_functions();
        $found       = false;
        foreach($autoloaders as $function) {
            if (is_array($function)) {
                $class = $function[0];
                if ($class == 'Zend_Loader_Autoloader') {
                    $found = true;
                    spl_autoload_unregister($function);
                    break;
                }
            }
        }
        $this->assertTrue($found, "Failed to register Zend_Loader_Autoloader with spl_autoload");
    }

    public function testLoaderRegisterAutoloadExtendedClassNeedsAutoloadMethod()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload not installed on this PHP installation");
        }

        $this->setErrorHandler();
        Zend_Loader::registerAutoload('Zend_Loader_MyLoader');
        $this->assertContains('deprecated', $this->error);

        $autoloaders = spl_autoload_functions();
        $expected    = array('Zend_Loader_MyLoader', 'autoload');
        $found       = false;
        foreach ($autoloaders as $function) {
            if ($expected == $function) {
                $found = true;
                break;
            }
        }
        $this->assertFalse($found, "Failed to register Zend_Loader_MyLoader::autoload() with spl_autoload");

        spl_autoload_unregister($expected);
    }

    public function testLoaderRegisterAutoloadExtendedClassWithAutoloadMethod()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload not installed on this PHP installation");
        }

        $this->setErrorHandler();
        Zend_Loader::registerAutoload('Zend_Loader_MyOverloader');
        $this->assertContains('deprecated', $this->error);

        $autoloaders = spl_autoload_functions();
        $found       = false;
        foreach ($autoloaders as $function) {
            if (is_array($function)) {
                $class = $function[0];
                if ($class == 'Zend_Loader_Autoloader') {
                    $found = true;
                    break;
                }
            }
        }
        $this->assertTrue($found, "Failed to register Zend_Loader_Autoloader with spl_autoload");

        $autoloaders = Zend_Loader_Autoloader::getInstance()->getAutoloaders();
        $found       = false;
        $expected    = array('Zend_Loader_MyOverloader', 'autoload');
        $this->assertTrue(in_array($expected, $autoloaders, true), 'Failed to register My_Loader_MyOverloader with Zend_Loader_Autoloader: ' . var_export($autoloaders, 1));

        // try to instantiate a class that is known not to be loaded
        $obj = new Zend_Loader_AutoloadableClass();

        // now it should be loaded
        $this->assertTrue(class_exists('Zend_Loader_AutoloadableClass'),
            'Expected Zend_Loader_AutoloadableClass to be loaded');

        // and we verify it is the correct type
        $this->assertType('Zend_Loader_AutoloadableClass', $obj,
            'Expected to instantiate Zend_Loader_AutoloadableClass, got '.get_class($obj));

        spl_autoload_unregister($function);
    }

    public function testLoaderRegisterAutoloadFailsWithoutSplAutoload()
    {
        if (function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload() is installed on this PHP installation; cannot test for failure");
        }

        try {
            Zend_Loader::registerAutoload();
            $this->fail('registerAutoload should fail without spl_autoload');
        } catch (Zend_Exception $e) {
        }
    }

    public function testLoaderRegisterAutoloadInvalidClass()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload() not installed on this PHP installation");
        }

        $this->setErrorHandler();
        try {
            Zend_Loader::registerAutoload('stdClass');
            $this->fail('registerAutoload should fail without spl_autoload');
        } catch (Zend_Exception $e) {
            $this->assertEquals('The class "stdClass" does not have an autoload() method', $e->getMessage());
            $this->assertContains('deprecated', $this->error);
        }
    }

    public function testLoaderUnregisterAutoload()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload() not installed on this PHP installation");
        }

        $this->setErrorHandler();
        Zend_Loader::registerAutoload('Zend_Loader_MyOverloader');
        $this->assertContains('deprecated', $this->error);

        $expected    = array('Zend_Loader_MyOverloader', 'autoload');
        $autoloaders = Zend_Loader_Autoloader::getInstance()->getAutoloaders();
        $this->assertTrue(in_array($expected, $autoloaders, true), 'Failed to register autoloader');

        Zend_Loader::registerAutoload('Zend_Loader_MyOverloader', false);
        $autoloaders = Zend_Loader_Autoloader::getInstance()->getAutoloaders();
        $this->assertFalse(in_array($expected, $autoloaders, true), 'Failed to unregister autoloader');

        foreach (spl_autoload_functions() as $function) {
            if (is_array($function)) {
                $class = $function[0];
                if ($class == 'Zend_Loader_Autoloader') {
                    spl_autoload_unregister($function);
                    break;
                }
            }
        }
    }

    /**
     * @group ZF-6605
     */
    public function testRegisterAutoloadShouldEnableZendLoaderAutoloaderAsFallbackAutoloader()
    {
        if (!function_exists('spl_autoload_register')) {
            $this->markTestSkipped("spl_autoload() not installed on this PHP installation");
        }

        $this->setErrorHandler();
        Zend_Loader::registerAutoload();
        $this->assertContains('deprecated', $this->error);

        $autoloader = Zend_Loader_Autoloader::getInstance();
        $this->assertTrue($autoloader->isFallbackAutoloader());

        foreach (spl_autoload_functions() as $function) {
            if (is_array($function)) {
                $class = $function[0];
                if ($class == 'Zend_Loader_Autoloader') {
                    spl_autoload_unregister($function);
                    break;
                }
            }
        }
    }

    /**
     * @group ZF-8200
     */
    public function testLoadClassShouldAllowLoadingPhpNamespacedClasses()
    {
        if (version_compare(PHP_VERSION, '5.3.0') < 0) {
            $this->markTestSkipped('PHP < 5.3.0 does not support namespaces');
        }
        Zend_Loader::loadClass('\Zfns\Foo', array(dirname(__FILE__) . '/Loader/_files'));
    }

    /**
     * @group ZF-7271
     * @group ZF-8913
     */
    public function testIsReadableShouldHonorStreamDefinitions()
    {
        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
            $this->markTestSkipped();
        }

        $pharFile = dirname(__FILE__) . '/Loader/_files/Zend_LoaderTest.phar';
        $phar     = new Phar($pharFile, 0, 'zlt.phar');
        $incPath = 'phar://zlt.phar'
                 . PATH_SEPARATOR . $this->includePath;
        set_include_path($incPath);
        $this->assertTrue(Zend_Loader::isReadable('User.php'));
        unset($phar);
    }

    /**
     * @group ZF-8913
     */
    public function testIsReadableShouldNotLockWhenTestingForNonExistantFileInPhar()
    {
        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
            $this->markTestSkipped();
        }

        $pharFile = dirname(__FILE__) . '/Loader/_files/Zend_LoaderTest.phar';
        $phar     = new Phar($pharFile, 0, 'zlt.phar');
        $incPath = 'phar://zlt.phar'
                 . PATH_SEPARATOR . $this->includePath;
        set_include_path($incPath);
        $this->assertFalse(Zend_Loader::isReadable('does-not-exist'));
        unset($phar);
    }

    /**
     * @group ZF-7271
     */
    public function testExplodeIncludePathProperlyIdentifiesStreamSchemes()
    {
        if (PATH_SEPARATOR != ':') {
            $this->markTestSkipped();
        }
        $path = 'phar://zlt.phar:/var/www:.:filter://[a-z]:glob://*';
        $paths = Zend_Loader::explodeIncludePath($path);
        $this->assertSame(array(
            'phar://zlt.phar',
            '/var/www',
            '.',
            'filter://[a-z]',
            'glob://*',
        ), $paths);
    }

    /**
     * @group ZF-9100
     */
    public function testIsReadableShouldReturnTrueForAbsolutePaths()
    {
        set_include_path(dirname(__FILE__) . '../../');
        $path = dirname(__FILE__);
        $this->assertTrue(Zend_Loader::isReadable($path));
    }

    /**
     * @group ZF-9263
     * @group ZF-9166
     * @group ZF-9306
     */
    public function testIsReadableShouldFailEarlyWhenProvidedInvalidWindowsAbsolutePath()
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') {
            $this->markTestSkipped('Windows-only test');
        }
        $path = 'C:/this/file/should/not/exist.php';
        $this->assertFalse(Zend_Loader::isReadable($path));
    }

    /**
     * In order to play nice with spl_autoload, an autoload callback should
     * *not* emit errors (exceptions are okay). ZF-2923 requests that this
     * behavior be applied, which counters the previous request in ZF-2463.
     *
     * As it is, the new behavior *will* hide parse and other errors. However,
     * a fatal error *will* be raised in such situations, which is as
     * appropriate or more appropriate than raising an exception.
     *
     * NOTE: Removed from test suite, as autoload functionality in Zend_Loader
     * is now deprecated.
     *
     * @see    http://framework.zend.com/issues/browse/ZF-2463
     * @group  ZF-2923
     * @return void
    public function testLoaderAutoloadShouldHideParseError()
    {
        if (isset($_SERVER['OS'])  &&  strstr($_SERVER['OS'], 'Win')) {
            $this->markTestSkipped(__METHOD__ . ' does not work on Windows');
        }
        $command = 'php -d include_path='
            . escapeshellarg(get_include_path())
            . ' Zend/Loader/AutoloadDoesNotHideParseError.php 2>&1';
        $output = shell_exec($command);
        $this->assertTrue(empty($output));
    }
     */
}

// Call Zend_LoaderTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD === 'Zend_LoaderTest::main') {
    Zend_LoaderTest::main();
}


text:
<#
.SYNOPSIS
  Name: Get-NspTlsReport.ps1
  Create report for in- and outbound E-Mails which did not use TLS.
  Requires NSP version 13.0.19147.917 or later.

.DESCRIPTION
  This script can be used to generate a report about E-Mails which where send or received without TLS
  It is possible to send the report via E-Mail and to filter the results for a specific time duration.
  This script only uses the NoSpamProxy Powershell Cmdlets to generate the report file.

.PARAMETER FromDate
  Mandatory if you like to use a timespan.
  Specifies the start date for the E-Mail filter.
  Please use ISO 8601 date format: "YYYY-MM-DD hh:mm:ss"
  E.g.:
  	"2018-11-16 08:00" or "2018-11-16 20:00:00"

.PARAMETER NoTime
  Mandatory if you do not like to specify a time value in any kind of way.
  No value needs to be passed here <NoTime> is just a single switch.

.PARAMETER NspRule
  Specify a rule name which is defined in NSP as E-Mail filter.

.PARAMETER NumberOfDays
  Mandatory if you like to use a number of days for filtering.
  Specifies the number of days for which th E-Mails should be filtered.

.PARAMETER NumberOfHoursToReport
  Mandatory if you like to use a number of hours for filtering.
  Specifies the number of hours for which th E-Mails should be filtered.

.PARAMETER ReportFileName
  Default: TLSReport
	Sets the reports file name. No file extension required.

.PARAMETER ReportInterval
  Mandatory if you like to use a predifined timespan.
  Specifies a predifined timespan.
	Possible values are:
	daily, monthly, weekly
	The report will start at 00:00:00 o'clock and ends at 23:59:59 o'clock.
	The script call must be a day after the desired report end day.

.PARAMETER ReportRecipient
  Specifies the E-Mail recipient. It is possible to pass a comma seperated list to address multiple recipients.
  E.g.: alice@example.com,bob@example.com

.PARAMETER ReportRecipientCSV
  Set a filepath to an CSV file containing a list of report E-Mail recipient. Be aware about the needed CSV format, please watch the provided example.

.PARAMETER ReportSender
  Default: NoSpamProxy Report Sender <nospamproxy@example.com>
  Sets the report E-Mail sender address.

.PARAMETER ReportSubject
  Default: NSP TLS Report
  Sets the report E-Mail subject.

.PARAMETER SmtpHost
  Specifies the SMTP host which should be used to send the report E-Mail.
  It is possible to use a FQDN or IP address.

.PARAMETER Status
  Specifies a filter to get only E-Mails which are matching the defined state.
  Possible values are:
  None | Success | DispatcherError | TemporarilyBlocked | PermanentlyBlocked | PartialSuccess | DeliveryPending | Suppressed | DuplicateDrop | PutOnHold | All

.PARAMETER TenantPrimaryDomain
  Used to login into the desired NoSpamProxy tenant to run this script on.
  Only required if NoSpamProxy v14 is used in provider mode.

.PARAMETER ToDate
  Optional if you like to use a timespan.
  Specifies the end date for the E-Mail filter.
  Please use ISO 8601 date format: "YYYY-MM-DD hh:mm:ss"
  E.g.:
  	"2018-11-16 08:00" or "2018-11-16 20:00:00"

.OUTPUTS
  Report is stored under %TEMP%\TLSReport.html unless a custom <ReportFileName> parameter is given.

.NOTES
  Version:        1.0.5
  Author:         Jan Jaeschke
  Creation Date:  2022-06-07
  Purpose/Change: added v14 support

.LINK
  https://www.nospamproxy.de
  https://github.com/noSpamProxy

.EXAMPLE
  .\Get-NspTlsReport.ps1 -NoTime -Status "Success" -ReportFileName "Example-Report" -ReportRecipient alice@example.com -ReportSender "NoSpamProxy Report Sender <nospamproxy@example.com>" -ReportSubject "Example Report" -SmtpHost mail.example.com

.EXAMPLE
  .\Get-NspTlsReport.ps1 -FromDate: "2018-10-14 08:00" -ToDate: "2018-10-14 20:00" -NoMail
  It is mandatory to specify <FromDate>. Instead <ToDate> is optional.
  These parameters can be combined with all other parameters except <NumberOfDaysToReport> and <NumberOfHoursToRepor>.

.EXAMPLE
  .\Get-NspTlsReport.ps1 -NumberOfDaysToReport 7 -NoMail
  You can combine <NumberOfDaysToReport> with all other parameters except <FromDate>, <ToDate> and <NumberOfHoursToRepor>.

.EXAMPLE
  .\Get-NspTlsReport.ps1 -NumberOfHoursToReport 12 -NoMail
  You can combine <NumberOfHoursToReport> with all other parameters except <FromDate>, <ToDate> and <NumberOfDaysToReport>.

.EXAMPLE
	.\Get-NspTlsReport.ps1 -ReportInterval weekly -NoMail
	You can combine <ReportInterval> with all other parameters except <FromDate>, <ToDate>, <NumberOfDaysToReport> and <NumberOfHoursToReport>.

.EXAMPLE
  .\Get-NspTlsReport.ps1 -NoTime -NoMail -NspRule "All other inbound mails"

.EXAMPLE
  .\Get-NspTlsReport.ps1 -NoTime -SmtpHost mail.example.com -ReportRecipientCSV "C:\Users\example\Documents\email-report.csv"
  The CSV have to contain the header "Email" else the mail addresses cannot be read from the file.
  It is possible to combine <ReportRecipientCSV> with <ReportRecipient>.
  E.g: email-report.csv
  User,Email
  user1,user1@example.com
  user2,user2@example.com
#>
param (
# userParams are used for filtering
	# set start date for filtering
	[Parameter(Mandatory=$true, ParameterSetName="dateSpanSet")][ValidatePattern("^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])\s(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])?$")][string] $FromDate,
	# set end date for filtering
	[Parameter(Mandatory=$false, ParameterSetName="dateSpanSet")][ValidatePattern("^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])\s(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])?$")][string] $ToDate,
	# set number of days for filtering
	[Parameter(Mandatory=$true, ParameterSetName="numberOfDaysSet")][ValidatePattern("[0-9]+")][string] $NumberOfDaysToReport,
	# set number of hours for filtering
	[Parameter(Mandatory=$true, ParameterSetName="numberOfHoursSet")][int] $NumberOfHoursToReport,
	# set reporting intervall
	[Parameter(Mandatory=$true, ParameterSetName="reportIntervalSet")][ValidateSet('daily','weekly','monthly')][string] $ReportInterval,
	# if set not time duration have to be set the E-Mail of the last few hours will be filtered
	[Parameter(Mandatory=$true, ParameterSetName="noTimeSet")][switch] $NoTime, # no userParam just here for better Get-Help output
	# set E-Mail status which will be filtered
	[Parameter(Mandatory=$false)][string] $Status = "Success",
	# set NSP Rule for filtering
	[Parameter(Mandatory=$false)][string] $NspRule,
	# additional params are used for additional actions
	# generate the report but do not send an E-Mail
	[Parameter(Mandatory=$false)][switch]$NoMail,
	# change report filename
	[Parameter(Mandatory=$false)][string] $ReportFileName = "TLSReport" ,
	# set report recipient only valid E-Mail addresses are allowed
	[Parameter(Mandatory=$false)][ValidatePattern("^<?[a-zA-Z0-9.!£#$%&'^_`{}~-]+?<?[a-zA-Z0-9.!£#$%&'^_`{}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*>?$")][string[]] $ReportRecipient,
	# set path to csv file containing report recipient E-Mail addresses
	[Parameter(Mandatory=$false)][string] $ReportRecipientCSV,
	# set report sender address only a valid E-Mail addresse is allowed
	[Parameter(Mandatory=$false)][ValidatePattern("^<?[a-zA-Z0-9.!£#$%&'^_`{}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*>?$")][string] $ReportSender = "NoSpamProxy Report Sender <nospamproxy@example.com>",
	# change report E-Mail subject
	[Parameter(Mandatory=$false)][string] $ReportSubject = "NSP TLS Report",
	# set used SMTP host for sending report E-Mail only a valid  IP address or FQDN is allowed
	[Parameter(Mandatory=$false)][ValidatePattern("^(((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(((?!-)[a-zA-Z0-9-]{0,62}[a-zA-Z0-9]\.)+[a-zA-Z]{2,63}))$")][string] $SmtpHost,
	# only needed for v14 with enabled provider mode
	[Parameter(Mandatory=$false)][string] $TenantPrimaryDomain
)

#-------------------Functions----------------------
# process actual MessageTracks - compare Mail From and add htmlContent
function processMessageTracks($tmpMessageTracks, $messageDirection){
	$returnValues = @{}
	$returnValues.sendersWithoutTLS = @()
	foreach($messageTrack in $tmpMessageTracks){
		if($messageDirection -eq "FromExternal"){
			$tls = ($messageTrack.SenderConnectionSecurity)
		}else{
			$tls = ($messageTrack.DeliveryAttempts | Where-Object {$_.Status -eq "Success"}).ConnectionSecurity
		}
		if($null -eq $tls){
			# number of the successfull send/received messages without
			$returnValues.numberOfMessagesWithoutTls = $returnValues.numberOfMessagesWithoutTls+1
			if($messageDirection -eq "FromExternal"){
				$sender = ($messagetrack.Addresses|Where-Object{[string]$_.AddressType -eq "Sender"}).Address
			}else{
				$sender = ($messagetrack.Addresses|Where-Object{[string]$_.AddressType -eq "Recipient"}).Address
			}

			if($null -eq $sender){
				continue
			}else{
				$returnValues.sendersWithoutTLS += "$sender
"
			}
		}
	}
	$returnValues.sendersWithoutTLS = $returnValues.sendersWithoutTLS | Get-Unique
	return $returnValues
}
# get data from message tracks and call the processing
# input the desired direction of messages
function getData($messageDirection){
	$returnValues = @{}

	# number of messages which will be skipped by Get-NspMessageTrack, will increase by 100 at each call
	$skipMessageTracks = 0
	while($getMessageTracks -eq $true){
		if($skipMessageTracks -eq 0){
			$messageTracks = Get-NSPMessageTrack @cleanedParams -WithOperations -WithDeliveryAttempts -WithTlsSettings -WithActions -WithAddresses -Directions $messageDirection -First 100
			# number of messages which where send/received successfully
			$returnValues.numberOfMessages += $messageTracks.Count
		}else{
			$messageTracks = Get-NSPMessageTrack @cleanedParams -WithOperations -WithDeliveryAttempts -WithTlsSettings -WithActions -WithAddresses -Directions $messageDirection -First 100 -Skip $skipMessageTracks
			# number of messages which where send/received successfully
			$returnValues.numberOfMessages += $messageTracks.Count
		}
		$processResult = processMessageTracks $messageTracks $messageDirection
		$returnValues.numberOfMessagesWithoutTls += $processResult.numberOfMessagesWithoutTls
		$returnValues.sendersWithoutTLS += $processResult.sendersWithoutTLS
		# exit condition
		if($messageTracks){
			$skipMessageTracks = $skipMessageTracks+100
			Write-Host $skipMessageTracks
		}else{
			$getMessageTracks = $false
			break
		}
	}
	return $returnValues
}
# generate HMTL report
function createHTML($resultFromExternal, $percentFromExternal, $resultFromLocal, $percentFromLocal) {
	$htmlOut =
"

		<title>Auswertung der TLS-Sicherheit</title>

Auswertung der TLS-Sicherheit

		Anzahl aller eingehenden Verbindungen: $($resultFromExternal.numberOfMessages)

		Davon waren unverschlüsselt: $($resultFromExternal.numberOfMessagesWithoutTls) ($percentFromExternal%)

		Anzahl aller ausgehenden Verbindungen: $($resultFromLocal.numberOfMessages)

		Davon waren unverschlüsselt: $($resultFromLocal.numberOfMessagesWithoutTls) ($percentFromLocal%)

		Adressen, die unverschlüsselt geschickt haben:

		$($($resultFromExternal.sendersWithoutTLS) | Out-String)

		Adressen, an die unverschlüsselt geschickt wurde:

		$($($resultFromLocal.sendersWithoutTLS) | Out-String)

"
	$htmlOut | Out-File "$reportFile"
}
# send report E-Mail
function sendMail($ReportRecipient, $ReportRecipientCSV){
	if ($ReportRecipient -and $ReportRecipientCSV){
		$recipientCSV = Import-Csv $ReportRecipientCSV
		$mailRecipient = @($ReportRecipient;$recipientCSV.Email)
	}
	elseif($ReportRecipient){
		$mailRecipient = $ReportRecipient
	}
	elseif($ReportRecipientCSV){
		$csv = Import-Csv $ReportRecipientCSV
		$mailRecipient = $csv.Email
	}
	if ($SmtpHost -and $mailRecipient){
		Send-MailMessage -SmtpServer $SmtpHost -From $ReportSender -To $mailRecipient -Subject $ReportSubject -Body "Im Anhang dieser E-Mail finden Sie einen automatisch genrerierten Bericht vom NoSpamProxy" -Attachments $reportFile
	}
}

#-------------------Variables----------------------
$fileDate = Get-Date -UFormat "%Y-%m-%d"
if ($NumberOfHoursToReport){
	$FromDate = (Get-Date).AddHours(-$NumberOfHoursToReport)
}
if ($ReportInterval){
	# equals the day where the script runs
	$reportEndDay = (Get-Date -Date ((Get-Date).AddDays(-1)) -UFormat "%Y-%m-%d")
	switch ($ReportInterval){
		'daily'{
			$reportStartDay = $reportEndDay
		}
		'weekly'{
			$reportStartDay = (Get-Date -Date ((Get-Date).AddDays(-7)) -UFormat "%Y-%m-%d")
		}
		'monthly'{
			$reportStartDay = (Get-Date -Date ((Get-Date).AddMonths((-1))) -UFormat "%Y-%m-%d")
		}
	}
	$FromDate = "$reportStartDay 00:00:00"
	$ToDate = "$reportEndDay 23:59:59"
	$fileDate = $reportEndDay
  $reportFile =  "$ENV:TEMP\" + "$fileDate-$ReportFileName" + ".html"
}
$reportFile =  "$ENV:TEMP\" + "$ReportFileName" + ".html"

if ($NumberOfHoursToReport){
	$FromDate = (Get-Date).AddHours(-$NumberOfHoursToReport)
}
# create hashtable which will preserve the order of the added items and mapps userParams into needed parameter format
$userParams = [ordered]@{
From = $FromDate
To = $ToDate
Age = $NumberOfDaysToReport
Rule = $NspRule
Status = $Status
}
# for loop problem because hashtable have no indices to access items, this is a workaround
# new hashtable which only holds non empty userParams
$cleanedParams=@{}
# this loop removes all empty userParams and add the otherones into the new hashtable
foreach ($userParam in $userParams.Keys) {
	if ($($userParams.Item($userParam)) -ne "") {
		$cleanedParams.Add($userParam, $userParams.Item($userParam))
	}
}
# end workaround
# condition to run Main part, if false program will end
$getMessageTracks = $true

#--------------------Main-----------------------
$nspVersion = (Get-ItemProperty -Path HKLM:\SOFTWARE\NoSpamProxy\Components -ErrorAction SilentlyContinue).'Intranet Role'
if ($nspVersion -gt '14.0') {
	try {
		Connect-Nsp -IgnoreServerCertificateErrors -ErrorAction Stop
	} catch {
		$e = $_
		Write-Warning "Not possible to connect with the NoSpamProxy. Please check the error message below."
		$e |Format-List * -Force
		EXIT
	}
	if ($(Get-NspIsProviderModeEnabled) -eq $true) {
		if ($null -eq $TenantPrimaryDomain -OR $TenantPrimaryDomain -eq "") {
			Write-Host "Please provide a TenantPrimaryDomain to run this script with NoSpamProxy v14 in provider mode."
			EXIT
		} else {
			# NSP v14 has a new authentication mechanism, Connect-Nsp is required to authenticate properly
			# -IgnoreServerCertificateErrors allows the usage of self-signed certificates
			Connect-Nsp -IgnoreServerCertificateErrors -PrimaryDomain $TenantPrimaryDomain
		}
	}
}
# check NSP version for compatibility
if(!((Get-NspIntranetRole).Version -ge [version]"13.0.19147.917")){
	throw "A minimum of NSP Version 13.0.19147.917 is needed, please update. Your version: $((Get-NspIntranetRole).Version)"
}

Write-Host "Getting data for E-Mails from External"
$resultFromExternal = getData "FromExternal"
if($null -eq $($resultFromExternal.sendersWithoutTLS)){
	$resultFromExternal.sendersWithoutTLS = 0
	$percentFromExternal = 0
}else{
	$percentFromExternal = [Math]::Round($($resultFromExternal.numberOfMessagesWithoutTls)/$($resultFromExternal.numberOfMessages)*100,2)
}

Write-Host "Getting data for E-Mails from local"
$resultFromLocal = getdata "FromLocal"
if($null -eq $($resultFromLocal.numberOfMessagesWithoutTls)){
	$resultFromLocal.numberOfMessagesWithoutTls = 0
	$percentFromLocal = 0
}else{
	$percentFromLocal = [Math]::Round($($resultFromLocal.numberOfMessagesWithoutTls)/$($resultFromLocal.numberOfMessages)*100,2)
}

Write-Host "Generating Report"
createHTML $resultFromExternal $percentFromExternal $resultFromLocal $percentFromLocal
# send mail if <NoMail> switch is not used and delete temp report file
if (!$NoMail){
	sendMail $ReportRecipient $ReportRecipientCSV
	Remove-Item $reportFile
} else {
	Move-Item -Path $reportFile -Destination "$PSScriptRoot\$(Split-Path -Path $reportFile -Leaf)"
}
Write-Host "Skript durchgelaufen"


text:
package org.ovirt.engine.api.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.VirtualNumaNode;
import org.ovirt.engine.api.model.VirtualNumaNodes;

@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {

    @GET
    public VirtualNumaNodes list();

    @POST
    @Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
    public Response add(VirtualNumaNode node);

    @Path("{iden}")
    public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}


text:
package org.apache.poi.hslf.dev;

import org.apache.poi.util.LittleEndian;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.poifs.filesystem.*;
import java.io.*;

/**
 * Utility class which dumps raw contents of a ppt file into XML format
 *
 * @author Yegor Kozlov
 */

public final class PPTXMLDump {
    public static final int HEADER_SIZE = 8; //size of the record header
    public static final int PICT_HEADER_SIZE = 25; //size of the picture header
    public final static String PPDOC_ENTRY = "PowerPoint Document";
    public final static String PICTURES_ENTRY = "Pictures";
    public static String CR = System.getProperty("line.separator");

    protected Writer out;
    protected byte[] docstream;
    protected byte[] pictstream;
    protected boolean hexHeader = true;

    public PPTXMLDump(File ppt) throws IOException {
        FileInputStream fis = new FileInputStream(ppt);
        POIFSFileSystem fs = new POIFSFileSystem(fis);
        fis.close();

        //read the document entry from OLE file system
        DocumentEntry entry = (DocumentEntry)fs.getRoot().getEntry(PPDOC_ENTRY);
        docstream = new byte[entry.getSize()];
        DocumentInputStream is = fs.createDocumentInputStream(PPDOC_ENTRY);
        is.read(docstream);

        try {
            entry = (DocumentEntry)fs.getRoot().getEntry(PICTURES_ENTRY);
            pictstream = new byte[entry.getSize()];
            is = fs.createDocumentInputStream(PICTURES_ENTRY);
            is.read(pictstream);
        } catch(FileNotFoundException e){
            //silently catch errors if the presentation does not contain pictures
        }
    }

    /**
     * Dump the structure of the supplied PPT file into XML
     * @param out Writer to write out
     * @throws java.io.IOException
     */
    public void dump(Writer out) throws IOException {
        this.out = out;

        int padding = 0;
        write(out, "<Presentation>" + CR, padding);
        padding++;
        if (pictstream != null){
            write(out, "<Pictures>" + CR, padding);
            dumpPictures(pictstream, padding);
            write(out, "</Pictures>" + CR, padding);
        }
        //dump the structure of the powerpoint document
        write(out, "<PowerPointDocument>" + CR, padding);
        padding++;
        dump(docstream, 0, docstream.length, padding);
        padding--;
        write(out, "</PowerPointDocument>" + CR, padding);
        padding--;
        write(out, "</Presentation>", padding);
    }

    /**
     * Dump a part of the document stream into XML
     * @param data PPT binary data
     * @param offset offset from the beginning of the document
     * @param length of the document
     * @param padding used for formatting results
     * @throws java.io.IOException
     */
    public void dump(byte[] data, int offset, int length, int padding) throws IOException {
        int pos = offset;
        while (pos <= (offset + length - HEADER_SIZE)){
            if (pos < 0) break;

            //read record header
            int info = LittleEndian.getUShort(data, pos);
            pos += LittleEndian.SHORT_SIZE;
            int type = LittleEndian.getUShort(data, pos);
            pos += LittleEndian.SHORT_SIZE;
            int size = (int)LittleEndian.getUInt(data, pos);
            pos += LittleEndian.INT_SIZE;

            //get name of the record by type
            String recname = RecordTypes.recordName(type);
            write(out, "<"+recname + " info=\""+info+"\" type=\""+type+"\" size=\""+size+"\" offset=\""+(pos-8)+"\"", padding);
            if (hexHeader){
                out.write(" header=\"");
                dump(out, data, pos-8, 8, 0, false);
                out.write("\"");
            }
            out.write(">" + CR);
			padding++;
            //this check works both for Escher and PowerPoint records
            boolean isContainer = (info & 0x000F) == 0x000F;
            if (isContainer) {
                //continue to dump child records
                dump(data, pos, size, padding);
            } else {
                //dump first 100 bytes of the atom data
                dump(out, data, pos, Math.min(size, data.length-pos), padding, true);
            }
			padding--;
            write(out, "</"+recname + ">" + CR, padding);

            pos += size;
        }
    }

    /**
     * Dumps the Pictures OLE stream into XML.
     *
     * @param data from the Pictures OLE data stream
     * @param padding
     * @throws java.io.IOException
     */
    public void dumpPictures(byte[] data, int padding) throws IOException {
        int pos = 0;
        while (pos < data.length) {
            byte[] header = new byte[PICT_HEADER_SIZE];

            System.arraycopy(data, pos, header, 0, header.length);
            int size = LittleEndian.getInt(header, 4) - 17;
            byte[] pictdata = new byte[size];
            System.arraycopy(data, pos + PICT_HEADER_SIZE, pictdata, 0, pictdata.length);
            pos += PICT_HEADER_SIZE + size;

            padding++;
            write(out, "<picture size=\""+size+"\" type=\""+getPictureType(header)+"\">" + CR, padding);
            padding++;
            write(out, "" + CR, padding);
            dump(out, header, 0, header.length, padding, true);
            write(out, "" + CR, padding);
            write(out, "<imgdata>" + CR, padding);
            dump(out, pictdata, 0, Math.min(pictdata.length, 100), padding, true);
            write(out, "</imgdata>" + CR, padding);
            padding--;
            write(out, "</picture>" + CR, padding);
            padding--;

        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 0){
            System.out.println(
                "Usage: PPTXMLDump (options) pptfile\n" +
                "Where options include:\n" +
                "    -f     write output to <pptfile>.xml file in the current directory"
            );
            return;
        }
        boolean outFile = false;
        for (int i = 0; i < args.length; i++){

            if (args[i].startsWith("-")) {
                if ("-f".equals(args[i])){
                    //write ouput to a file
                    outFile = true;
                }
            } else {
                File ppt = new File(args[i]);
                PPTXMLDump dump = new PPTXMLDump(ppt);
                System.out.println("Dumping " + args[i]);

                if (outFile){
                    FileWriter out = new FileWriter(ppt.getName() + ".xml");
                    dump.dump(out);
                    out.close();
                } else {
                    StringWriter out = new StringWriter();
                    dump.dump(out);
                    System.out.println(out.toString());
                }
            }

        }
    }

    /**
     *  write a string to out with the specified padding
     */
    private static void write(Writer out, String str, int padding) throws IOException {
        for (int i = 0; i < padding; i++) out.write("  ");
        out.write(str);
    }

    private String getPictureType(byte[] header){
        String type;
        int meta = LittleEndian.getUShort(header, 0);

        switch(meta){
            case 0x46A0: type = "jpeg"; break;
            case 0x2160: type = "wmf"; break;
            case 0x6E00: type = "png"; break;
            default: type = "unknown"; break;
        }
        return type;
    }

    /**
     *  dump binary data to out with the specified padding
     */
    private static void dump(Writer out, byte[] data, int offset, int length, int padding, boolean nl) throws IOException {
        int linesize = 25;
        for (int i = 0; i < padding; i++) out.write("  ");
        int i;
        for (i = offset; i < (offset + length); i++) {
            int c = data[i];
            out.write((char) hexval[(c & 0xF0) >> 4]);
            out.write((char) hexval[(c & 0x0F) >> 0]);
            out.write(' ');
            if((i+1-offset) % linesize == 0 && i != (offset + length-1)) {
                out.write(CR);
                for (int j = 0; j < padding; j++) out.write("  ");
            }
        }
        if(nl && length > 0)out.write(CR);
    }

    private static final byte hexval[] =
        {(byte) '0', (byte) '1', (byte) '2', (byte) '3',
         (byte) '4', (byte) '5', (byte) '6', (byte) '7',
         (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
         (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'};

}


text:
require 'juncture'
require 'hashie'
require 'uri'
require 'segregate/version'
require 'segregate/http_methods'
require 'segregate/http_headers'
require 'segregate/http_regular_expressions'

class Segregate
  attr_reader :uri, :type, :state, :http_version, :headers
  attr_accessor :request_method, :status_code, :status_phrase, :body

  def method_missing meth, *args, &block
    if @uri.respond_to? meth
      @uri.send meth, *args, &block
    else
      super
    end
  end

  def respond_to?(meth, include_private = false)
    @uri.respond_to?(meth, include_private) || super
  end

  def debug message
    if @debug
      puts "DEBUG: " + message.to_s
    end
  end

  def initialize callback = nil, *args, **kwargs
    @debug = kwargs[:debug] ? true : false
    @callback = callback
    @http_version = [nil, nil]

    # :request, :response
    @type = Juncture.new :request, :response
    @state = Juncture.new :waiting, :headers, :body, :done, default: :waiting

    @headers = Hashie::Mash.new
    @body = ""

    @stashed_data = ""
    @stashed_body = ""

    @header_order = []
  end

  def request?
    @type == :request
  end

  def response?
    @type == :response
  end

  def headers_complete?
    @state > :headers
  end

  def done?
    @state >= :done
  end

  def request_line
    request? ? "%s %s HTTP/%d.%d" % [request_method, request_url.to_s, *http_version] : nil
  end

  def status_line
    response? ? "HTTP/%d.%d %d %s" % [*http_version, status_code, status_phrase] : nil
  end

  def request_url
    uri ? uri.to_s : nil
  end

  def major_http_version
    http_version[0]
  end

  def major_http_version= value
    http_version[0] = value
  end

  def minor_http_version
    http_version[1]
  end

  def minor_http_version= value
    http_version[1] = value
  end

  def update_content_length
    unless @body.empty?
      if @headers['content-length']
        @headers['content-length'] = @body.length.to_s
      end
    end
  end

  def raw_data
    raw_message = ""
    update_content_length

    build_headers raw_message
    build_body raw_message

    return raw_message
  end

  def build_headers raw_message
    request? ? raw_message << request_line + "\r\n" : raw_message << status_line + "\r\n"
    @header_order.each do |header|
      values = @headers[header.downcase]
      if values.kind_of?(Array)
        values.each do |value|
          raw_message << "%s: %s\r\n" % [header, value]
        end
      else
        raw_message << "%s: %s\r\n" % [header, values]
      end
    end
    raw_message << "\r\n"
  end

  def build_body raw_message
    new_body, size = deflate_if_needed(@body)
    if @headers['content-length']
      raw_message << new_body
      raw_message << "\r\n\r\n"
    elsif @headers['transfer-encoding'] == 'chunked'
      raw_message << "%s\r\n" % (size.to_s(16))
      raw_message << new_body + "\r\n"
      raw_message << "0\r\n\r\n"
    end
  end

  def deflate_if_needed(body)
    return [body, body.size] unless gzip_encoded_body?

    str_io = StringIO.new('w')
    w_gz = Zlib::GzipWriter.new(str_io)
    w_gz.write(body)
    w_gz.close

    # To specify the number of bytes for a gzip string
    # we should check for the buffer size instead of the string size
    [str_io.string, str_io.size]
  end

  def parse_data data
    data = StringIO.new(@stashed_data + data)
    @stashed_data = ""

    while !data.eof? && @state < :done
      line, complete_line = get_next_line data
      complete_line ? parse_line(line) : @stashed_data = line
    end

    data.close
  end

  def parse_line line
    case @state.state
    when :waiting
      read_in_first_line line
    when :headers
      read_in_headers line
    when :body
      read_in_body line
    end

    @callback.on_message_complete self if @callback.respond_to?(:on_message_complete) && done?
  end

  private

  def get_next_line data
    if @headers['content-length'] && @state >= :body
      line = data.readline("\r\n")
      @inital_line = line
      [line, true]
    else
      line = data.readline("\r\n")
      @inital_line = line
      result = line.end_with?("\r\n")
      line = line[0..-3] if result
      [line, result]
    end
  end

  def read_in_first_line line
    @callback.on_message_begin self if @callback.respond_to?(:on_message_begin)

    if line =~ REQUEST_LINE
      parse_request_line line
    elsif line =~ STATUS_LINE
      parse_status_line line
    else
      raise "ERROR: Unknown first line: %s" % line
    end

    @state.next
  end

  def parse_request_line line
    @type.set :request
    @request_method, url, @http_version[0], @http_version[1] = line.scan(REQUEST_LINE).flatten
    @http_version.map! {|v| v.to_i}
    @uri = URI.parse url

    @callback.on_request_line self if @callback.respond_to?(:on_request_line)
  end

  def parse_status_line line
    @type.set :response
    @http_version[0], @http_version[1], code, @status_phrase = line.scan(STATUS_LINE).flatten
    @http_version.map! {|v| v.to_i}
    @status_code = code.to_i

    @callback.on_status_line self if @callback.respond_to?(:on_status_line)
  end

  def read_in_headers line
    if line.empty?
      @state.next
    else
      key, value = line.split(": ",2)
      @header_order << key unless @header_order.include?(key)
      save_value(@headers, key, value)
    end

    if headers_complete?
      @callback.on_headers_complete self if @callback.respond_to?(:on_headers_complete)
      if headers['transfer-encoding'].nil? && (headers['content-length'] == "0" || headers['content-length'].nil?)
        @state.set :done
      end
    end
  end

  def read_in_body line
    if headers['content-length']
      parse_body line
    elsif headers['transfer-encoding'] == 'chunked'
      parse_chunked_data line
    end
  end

  def parse_body line
    line = @stashed_body + line
    @stashed_body = ""

    if line.length >= headers['content-length'].to_i
      # Removing delimiters characters from the HTTP protocol
      line = line[0..-3]
      @body = inflate_body_if_needed(line)
      @callback.on_body @body if @callback.respond_to?(:on_body)
      @state.next
    else
      @stashed_body = line
    end
  end

  def inflate_body_if_needed(body)
    return body unless gzip_encoded_body?

    gzip_str  = StringIO.new(body)
    gzip_body = Zlib::GzipReader.new( gzip_str )
    gzip_body.read()
  end

  def gzip_encoded_body?
    headers.key?('content-encoding') && headers['content-encoding'].eql?('gzip')
  end

  def parse_chunked_data line
    @chunked_body_state ||= Juncture.new :size, :chunk, default: :size

    case @chunked_body_state.state
    when :size
      parse_chunked_data_size line.to_i(16)
    when :chunk
      parse_chunked_data_chunk line
    end
  end

  def parse_chunked_data_size chunk_size
    if chunk_size == 0
      @state.next
    else
      @chunk_size = chunk_size
    end
    @chunked_body_state.next
  end

  def parse_chunked_data_chunk line
    line = @stashed_body + line
    @stashed_body = ""

    if line.length >= @chunk_size
      @body << line
      @original_body = @body
      @body = inflate_body_if_needed(@body)
      @callback.on_body line if @callback.respond_to?(:on_body)
      @chunked_body_state.next
    else
      @stashed_body = @inital_line.end_with?("\r\n") ? (line + "\r\n") : line
    end
  end

  def save_value(store_hash, key, value)
    key = key.downcase
    if store_hash.key?(key)
      store_hash[key] = [] << store_hash[key] unless store_hash[key].kind_of?(Array)
      store_hash[key] << value
    else
      store_hash[key] = value
    end
  end
end


text:
package org.elasticsearch.search.aggregations.bucket.significant;

import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.CheckedSupplier;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.ParsedMultiBucketAggregation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public abstract class ParsedSignificantTerms extends ParsedMultiBucketAggregation<ParsedSignificantTerms.ParsedBucket>
        implements SignificantTerms {

    private Map<String, ParsedBucket> bucketMap;
    protected long subsetSize;
    protected long supersetSize;

    protected long getSubsetSize() {
        return subsetSize;
    }

    protected long getSupersetSize() {
        return supersetSize;
    }

    @Override
    public List<? extends SignificantTerms.Bucket> getBuckets() {
        return buckets;
    }

    @Override
    public SignificantTerms.Bucket getBucketByKey(String term) {
        if (bucketMap == null) {
            bucketMap = buckets.stream().collect(Collectors.toMap(SignificantTerms.Bucket::getKeyAsString, Function.identity()));
        }
        return bucketMap.get(term);
    }

    @Override
    public Iterator<SignificantTerms.Bucket> iterator() {
        return buckets.stream().map(bucket -> (SignificantTerms.Bucket) bucket).collect(Collectors.toList()).iterator();
    }

    @Override
    protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        builder.field(CommonFields.DOC_COUNT.getPreferredName(), subsetSize);
        builder.field(InternalMappedSignificantTerms.BG_COUNT, supersetSize);
        builder.startArray(CommonFields.BUCKETS.getPreferredName());
        for (SignificantTerms.Bucket bucket : buckets) {
            bucket.toXContent(builder, params);
        }
        builder.endArray();
        return builder;
    }

    static <T extends ParsedSignificantTerms> T parseSignificantTermsXContent(final CheckedSupplier<T, IOException> aggregationSupplier,
                                                                              final String name) throws IOException {
        T aggregation = aggregationSupplier.get();
        aggregation.setName(name);
        for (ParsedBucket bucket : aggregation.buckets) {
            bucket.subsetSize = aggregation.subsetSize;
            bucket.supersetSize = aggregation.supersetSize;
        }
        return aggregation;
    }

    static void declareParsedSignificantTermsFields(final ObjectParser<? extends ParsedSignificantTerms, Void> objectParser,
                                     final CheckedFunction<XContentParser, ParsedSignificantTerms.ParsedBucket, IOException> bucketParser) {
        declareMultiBucketAggregationFields(objectParser, bucketParser::apply, bucketParser::apply);
        objectParser.declareLong((parsedTerms, value) -> parsedTerms.subsetSize = value , CommonFields.DOC_COUNT);
        objectParser.declareLong((parsedTerms, value) -> parsedTerms.supersetSize = value ,
                new ParseField(InternalMappedSignificantTerms.BG_COUNT));
    }

    public abstract static class ParsedBucket extends ParsedMultiBucketAggregation.ParsedBucket implements SignificantTerms.Bucket {

        protected long subsetDf;
        protected long subsetSize;
        protected long supersetDf;
        protected long supersetSize;
        protected double score;

        @Override
        public long getDocCount() {
            return getSubsetDf();
        }

        @Override
        public long getSubsetDf() {
            return subsetDf;
        }

        @Override
        public long getSupersetDf() {
            return supersetDf;
        }

        @Override
        public double getSignificanceScore() {
            return score;
        }

        @Override
        public long getSupersetSize() {
            return supersetSize;
        }

        @Override
        public long getSubsetSize() {
            return subsetSize;
        }

        @Override
        public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            builder.startObject();
            keyToXContent(builder);
            builder.field(CommonFields.DOC_COUNT.getPreferredName(), getDocCount());
            builder.field(InternalSignificantTerms.SCORE, getSignificanceScore());
            builder.field(InternalSignificantTerms.BG_COUNT, getSupersetDf());
            getAggregations().toXContentInternal(builder, params);
            builder.endObject();
            return builder;
        }

        @Override
        protected abstract XContentBuilder keyToXContent(XContentBuilder builder) throws IOException;

        static <B extends ParsedBucket> B parseSignificantTermsBucketXContent(final XContentParser parser, final B bucket,
            final CheckedBiConsumer<XContentParser, B, IOException> keyConsumer) throws IOException {

            final List<Aggregation> aggregations = new ArrayList<>();
            XContentParser.Token token;
            String currentFieldName = parser.currentName();
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if (CommonFields.KEY_AS_STRING.getPreferredName().equals(currentFieldName)) {
                        bucket.setKeyAsString(parser.text());
                    } else if (CommonFields.KEY.getPreferredName().equals(currentFieldName)) {
                        keyConsumer.accept(parser, bucket);
                    } else if (CommonFields.DOC_COUNT.getPreferredName().equals(currentFieldName)) {
                        long value = parser.longValue();
                        bucket.subsetDf = value;
                        bucket.setDocCount(value);
                    } else if (InternalSignificantTerms.SCORE.equals(currentFieldName)) {
                        bucket.score = parser.longValue();
                    } else if (InternalSignificantTerms.BG_COUNT.equals(currentFieldName)) {
                        bucket.supersetDf = parser.longValue();
                    }
                } else if (token == XContentParser.Token.START_OBJECT) {
                    XContentParserUtils.parseTypedKeysObject(parser, Aggregation.TYPED_KEYS_DELIMITER, Aggregation.class,
                            aggregations::add);
                }
            }
            bucket.setAggregations(new Aggregations(aggregations));
            return bucket;
        }
    }
}


text:
Talend plugin allowing to use Talend TOS DI in command line to export jobs.

## How to use it

Talend TOS DI can be called with the following arguments:

* **-nosplash** Start Talend without the GUI.
* **-data \[DIRECTORY\]** Specify where the Talend workspace is located.
* **-application com.bsb.tools.talend.JobExportApplication** Specify that the application to execute is our application.
* **-targetFile \[ZIP FILE\]** Specify the FQN of the zip file containing exported jobs.
* **-projectName \[PROJECT NAME\]** Specify the name of the Talend project in the current workspace.
* **-jobsToExport \[PATTERN\]** Specify with a regex the jobs to export (based on their labels).
* **-clean** Clean the workspace.
* **-version** Job-Version to export. If not set, the latest will be exported
* **-context** Context name. If not set, "Default" will be used.

Example exporting all "Extractions" jobs (for instance "Extractions/fromComponentBToC"):

``
C:\tools\talend\6.1.1\TOS_DI-win-x86_64.exe -nosplash -data C:\projects\trunk\com.bsb.myProject.transformation\src\main\talend -application com.bsb.tools.talend.export.JobExportApplication -targetFile C:\projects\trunk\com.bsb.myProject.transformation\target\Extractions.zip -projectName MY_PROJECT_TRANSFORMATION -jobsToExport "Extractions/[0-9a-zA-Z]*" -clean
``

## How to build

* Checkout this repository to a local directory.
* Make sure you can execute `mvn` on your command line.

* The `org.talend.repository_6.1.1.20151214_1327.jar`  have to be installed in your local Maven
repository.
See [install-file Maven command](https://maven.apache.org/plugins/maven-install-plugin/examples/specific-local-repo.html)  for more details about the install-file Maven command e.g.:

`mvn install:install-file -Dfile=plugins\org.talend.repository_6.1.1.20151214_1327.jar -DgroupId=org.talend.studio -DartifactId=org.talend.repository -Dversion=6.1.1 -Dpackaging=jar`

 * Build the plugin with the `mvn clean install` command.

## Install the plugin

Once built with the standard Maven command `mvn clean install`, the jar file can be moved in the "plugins" directory of your Talend TOS DI installation.