text:
package goleveldb

import (
	"bytes"
	"errors"
	"io/ioutil"
	"os"

	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/util"

	"github.com/aptly-dev/aptly/database"
)

type storage struct {
	path string
	db   *leveldb.DB
}

// CreateTemporary creates new DB of the same type in temp dir
func (s *storage) CreateTemporary() (database.Storage, error) {
	tempdir, err := ioutil.TempDir("", "aptly")
	if err != nil {
		return nil, err
	}

	db, err := internalOpen(tempdir, true)
	if err != nil {
		return nil, err
	}
	return &storage{db: db, path: tempdir}, nil
}

// Get key value from database
func (s *storage) Get(key []byte) ([]byte, error) {
	value, err := s.db.Get(key, nil)
	if err != nil {
		if err == leveldb.ErrNotFound {
			return nil, database.ErrNotFound
		}
		return nil, err
	}

	return value, nil
}

// Put saves key to database, if key has the same value in DB already, it is not saved
func (s *storage) Put(key []byte, value []byte) error {
	old, err := s.db.Get(key, nil)
	if err != nil {
		if err != leveldb.ErrNotFound {
			return err
		}
	} else {
		if bytes.Equal(old, value) {
			return nil
		}
	}
	return s.db.Put(key, value, nil)
}

// Delete removes key from DB
func (s *storage) Delete(key []byte) error {
	return s.db.Delete(key, nil)
}

// KeysByPrefix returns all keys that start with prefix
func (s *storage) KeysByPrefix(prefix []byte) [][]byte {
	result := make([][]byte, 0, 20)

	iterator := s.db.NewIterator(nil, nil)
	defer iterator.Release()

	for ok := iterator.Seek(prefix); ok && bytes.HasPrefix(iterator.Key(), prefix); ok = iterator.Next() {
		key := iterator.Key()
		keyc := make([]byte, len(key))
		copy(keyc, key)
		result = append(result, keyc)
	}

	return result
}

// FetchByPrefix returns all values with keys that start with prefix
func (s *storage) FetchByPrefix(prefix []byte) [][]byte {
	result := make([][]byte, 0, 20)

	iterator := s.db.NewIterator(nil, nil)
	defer iterator.Release()

	for ok := iterator.Seek(prefix); ok && bytes.HasPrefix(iterator.Key(), prefix); ok = iterator.Next() {
		val := iterator.Value()
		valc := make([]byte, len(val))
		copy(valc, val)
		result = append(result, valc)
	}

	return result
}

// HasPrefix checks whether it can find any key with given prefix and returns true if one exists
func (s *storage) HasPrefix(prefix []byte) bool {
	iterator := s.db.NewIterator(nil, nil)
	defer iterator.Release()
	return iterator.Seek(prefix) && bytes.HasPrefix(iterator.Key(), prefix)
}

// ProcessByPrefix iterates through all entries where key starts with prefix and calls
// StorageProcessor on key value pair
func (s *storage) ProcessByPrefix(prefix []byte, proc database.StorageProcessor) error {
	iterator := s.db.NewIterator(nil, nil)
	defer iterator.Release()

	for ok := iterator.Seek(prefix); ok && bytes.HasPrefix(iterator.Key(), prefix); ok = iterator.Next() {
		err := proc(iterator.Key(), iterator.Value())
		if err != nil {
			return err
		}
	}

	return nil
}

// Close finishes DB work
func (s *storage) Close() error {
	if s.db == nil {
		return nil
	}
	err := s.db.Close()
	s.db = nil
	return err
}

// Reopen tries to open (re-open) the database
func (s *storage) Open() error {
	if s.db != nil {
		return nil
	}

	var err error
	s.db, err = internalOpen(s.path, false)
	return err
}

// CreateBatch creates a Batch object
func (s *storage) CreateBatch() database.Batch {
	return &batch{
		db: s.db,
		b:  &leveldb.Batch{},
	}
}

// OpenTransaction creates new transaction.
func (s *storage) OpenTransaction() (database.Transaction, error) {
	t, err := s.db.OpenTransaction()
	if err != nil {
		return nil, err
	}

	return &transaction{t: t}, nil
}

// CompactDB compacts database by merging layers
func (s *storage) CompactDB() error {
	return s.db.CompactRange(util.Range{})
}

// Drop removes all the DB files (DANGEROUS!)
func (s *storage) Drop() error {
	if s.db != nil {
		return errors.New("DB is still open")
	}

	return os.RemoveAll(s.path)
}

// Check interface
var (
	_ database.Storage = &storage{}
)


text:
package com.facebook.buck.intellij.plugin.ui.tree;

import javax.swing.tree.TreeNode;

public class BuckTreeNodeDetailError extends BuckTreeNodeDetail {
    private final int mLine;
    private final int mColumn;

    public BuckTreeNodeDetailError(TreeNode parent, String detail, int line, int column) {
        super(parent, DetailType.ERROR, detail);
        mLine = line;
        mColumn = column;
    }

    public String getError() { return mDetail; }
    public int getLine() { return mLine; }
    public int getColumn() { return mColumn; }
}

redpajama_set_name: RedPajamaGithub


text:
from django.db import models
from django.utils.translation import gettext_lazy as _

class CaptionedFile(models.Model):
    caption = models.CharField(max_length=200, verbose_name=_('caption'))
    publication = models.FileField(upload_to='captioned-files', verbose_name=_('Uploaded File'))

    def __str__(self):
        return self.caption

    class Meta:
        verbose_name = _('Captioned File')
        verbose_name_plural = _('Captioned Files')

class UncaptionedFile(models.Model):
    publication = models.FileField(upload_to='uncaptioned-files', verbose_name=_('Uploaded File'))

    def __str__(self):
        return self.publication.name

    class Meta:
        verbose_name = _('Uncaptioned File')
        verbose_name_plural = _('Uncaptioned Files')


text:
import React, {PropTypes} from 'react';
import {Link, IndexLink} from 'react-router';
import LoadingDots from './LoadingDots';
import LoginLink from './LoginLink';
import LogoutLink from './LogoutLink';
import AdminLink from './AdminLink';

const Header = ({loading, signOut, auth, user}) => {

  let loginLogoutLink = auth.isLogged ? <LogoutLink signOut={signOut} /> : <LoginLink />;
  let adminLink = user.isAdmin ? <AdminLink /> : null;

  return (
    <nav>
      <IndexLink to="/" activeClassName="active">Home</IndexLink>
      {" | "}
      <Link to="/chat" activeClassName="active">Chat</Link>
      {" | "}
      <Link to="/about" activeClassName="active">About</Link>
      {" | "}
      <Link to="/protected" activeClassName="active">Protected</Link>
      {adminLink}
      {" | "}
      {loginLogoutLink}
      {loading && <LoadingDots interval={100} dots={20}/>}
    </nav>
  );
};

Header.propTypes = {
  signOut: React.PropTypes.func.isRequired,
  auth: React.PropTypes.object.isRequired,
  user: React.PropTypes.object.isRequired,
  loading: PropTypes.bool.isRequired
};

export default Header;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="img/favicon.ico">
    <title>InvAid</title>

    <link href="stylesheets/bootstrap.css" rel="stylesheet">

    <link href='http://fonts.googleapis.com/css?family=Exo+2:300,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/main.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/chat.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

          </button>
          InvAid

Dashboard

Inventory

Messenger

Log Out

Logged in as: Ryan Chavez

Messenger

          <input type="text" id="messageInput" class="form-control">

            <button type="button" id="submit" class="btn btn-default"> Send </button>


text:
<Alloy>
	<Window class="container">
		<TextArea id="ta"></TextArea>
		<TextArea id="content"></TextArea>
	</Window>
</Alloy>


text:
SetTrustworthyScoreWidget::SetTrustworthyScoreWidget(const int &trustscore, QWidget *parent)
    : QWidget(parent)
{
    scoreLabel = new QLabel(tr("A 'trustworthy' domain/COG score (should be not less than a minimum score):"), this);

    hintLabel = new QLabel(tr("Regardless of an overlapping region size, domains/COGs with 'trustworthy' scores will be shown."), this);

    scoreSpinBox = new QSpinBox(this);
    scoreSpinBox->setRange(25, 100500);
    scoreSpinBox->setValue(trustscore);
    scoreSpinBox->setSuffix(tr(" bits"));

    defaultButton = new QPushButton(tr("Set a default score"), this);
    defaultButton->setDefault(false);
    connect(defaultButton, SIGNAL(clicked()), this, SLOT(setDefaultScore()));

    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addWidget(scoreLabel);
    topLayout->addWidget(scoreSpinBox);
    topLayout->addWidget(defaultButton);
    topLayout->addStretch();

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(hintLabel);
    mainLayout->addStretch();
    setLayout(mainLayout);
}

int SetTrustworthyScoreWidget::tunedTrustworthyScore() const
{
    return scoreSpinBox->value();
}

void SetTrustworthyScoreWidget::setDefaultScore()
{
    scoreSpinBox->setValue(250);
}


text:
import calculations from '../calculate/calculations';
import numberToChange from '../helpers/general/number-to-change';
import formatPosition from './helpers/format-position';
import mapParamToModule from '../configure/helpers/map-param-to-module';

export default class Cell {
    constructor (column, result, params) {
        this.column = column;
        this.result = result;

        if (this[column]) {
            return this[column](result, params);
        } else if (calculations.hasOwnProperty(column)) {
            return this.makeCalculation(column, result, params);
        } else if (column.includes('.change')) {
            return this.makeChange(column, result, params);
        } else if (column.includes('spark')) {
            return this.makeSpark(column, result, params);
        } else if (mapParamToModule(column, result.extras)) {
            return this.makeExtra(column, result, params);
        } else {
            this.text = '';
            this.classes = [];
            return this;
        }
    }

    position (result, params) {
        this.text = formatPosition(result.position, params.positionWhenTied);
        this.classes = ['position'];
        return this;
    }

    item (result, params) {
        this.text = result.item;
        this.classes = ['item', 'clickable'];
        return this;
    }

    match (result, params) {
        this.text = result.match ? `${result.match.score}-${result.match.opponentScore} ${result.match.opponent}` : '';
        this.classes = ['change'];
        return this;
    }

    outcome (result, params) {
        this.text = '';
        this.classes = ['outcome'];
        this.backgroundColor = params.colors[result.outcome] || 'transparent';
        return this;
    }

    goalsDifference (result, params) {
        this.text = numberToChange(result.goalsDifference.total, '0');
        this.classes = ['calculation'];
        return this;
    }

    winningPercentage (result, params) {
        this.text = result.winningPercentage.total.toFixed(3).toString().replace('0','');
        this.classes = ['calculation'];
        return this;
    }

    round (result, params) {
        this.text = result.roundMeta.name;
        this.classes = ['round', 'clickable'];
        return this;
    }

    makeCalculation (column, result, params) {
        this.text = result[column].total;
        this.classes = ['calculation'];
        return this;
    }

    makeChange (column, result, params) {
        const calc = column.replace('.change', '');
        this.text = numberToChange(result[calc].change);
        this.classes = ['change'];
        return this;
    }

    makeSpark (column, result, params) {
        this.text = '';
        this.classes = ['spark'];

        this.roundIndex = Number.parseInt(column.split('.')[1]);
        const itemResults = params.sparklinesData.get(result.item);

        if (this.roundIndex >= itemResults.length) {
            this.backgroundColor = 'transparent';
            this.result = {};
        } else {
            this.result = itemResults[this.roundIndex];

            if (this.roundIndex === params.currentRound) {
                this.classes.push('current');
                this.backgroundColor = params.currentSparkColors[itemResults[this.roundIndex].outcome] || 'transparent';
            } else {
                this.backgroundColor = params.sparkColors[itemResults[this.roundIndex].outcome] || 'transparent';
            }
        }

        return this;
    }

    makeExtra (column, result, params) {
        const extraType = mapParamToModule(column, result.extras);
        this.text = result.extras[extraType][column];
        this.classes = [`extra-${extraType}`];
        return this;
    }
};


text:
package estreamj.framework;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;

/**
 * The engine accumulates all the stream ciphers available. All implementations
 * register with the engine by themselves.
 */
public class Engine {
    /**
     * @return the names of all ciphers registered; can be empty if no ciphers
     * have been registered so far
     */
    public static String[] getCipherNames() {
        String[] result;

        synchronized (_cphMks) {
            Vector<String> lst = new Vector<String>();
            lst.addAll(_cphMks.keySet());
            Collections.sort(lst);
            result = lst.toArray(new String[lst.size()]);
        }

        return result;
    }

    /**
     * Creates a new cipher instance.
     *
     * @param name name of the cipher to make
     * @return new cipher instance
     * @throws ESJException if any error occured
     */
    public static ICipher createCipher(String name) throws ESJException {
        ICipherMaker maker;

        synchronized (_cphMks) {
            maker = _cphMks.get(name);
            if (null == maker) {
                throw new ESJException(
                        "no maker registered for cipher \"" +
                                name + "\""
                );
            }
        }
        return maker.create();
    }

    ///////////////////////////////////////////////////////////////////////////

    static HashMap<String, ICipherMaker> _cphMks =
            new HashMap<String, ICipherMaker>();

    /**
     * Called by cipher implementations to register their factories, usually
     * during startup time.
     *
     * @param cphMk the factory to register
     */
    public static void registerCipher(ICipherMaker cphMk) {
        String name = cphMk.getName();

        synchronized (_cphMks) {
            if (_cphMks.containsKey(name)) {
                System.err.println(
                        "cipher \"" + name +
                                "\" has been registered already"
                );
                System.exit(1);
            }
            _cphMks.put(cphMk.getName(), cphMk);
        }
    }

    ///////////////////////////////////////////////////////////////////////////

    // all the cipher classes must be listed here, the rest of the registration
    // is done via reflection; this is done by having every class implementing
    // a 'public static void register()' method (see below)
    @SuppressWarnings("rawtypes")
    static Class[] _cipherClasses =
            {
                    //estreamj.ciphers.phelix.Phelix.class,
                    //estreamj.ciphers.hc256.HC256.class,
                    //estreamj.ciphers.salsa20.Salsa20.class,
                    //estreamj.ciphers.aes.AESCTR.class,
                    //estreamj.ciphers.mickey.MICKEY.class,
                    //estreamj.ciphers.mickey.MICKEY128.class,
                    //estreamj.ciphers.hermes8.Hermes8.class,
                    //estreamj.ciphers.rc4.RC4.class,
                    //estreamj.ciphers.dragon.Dragon.class,
                    //estreamj.ciphers.lex.LEX.class,
                    estreamj.ciphers.trivium.Trivium.class//,
                    //estreamj.ciphers.sosemanuk.Sosemanuk.class,
                    //estreamj.ciphers.grain.GrainP2.class,
                    //estreamj.ciphers.grain.Grain128.class,
                    //estreamj.ciphers.nil.Nil.class
            };

    ///////////////////////////////////////////////////////////////////////////

    static {
        try {
            for (int i = 0; i < _cipherClasses.length; i++) {
                // check if the register method is there and static
                Class<?> cls = _cipherClasses[i];
                Method mthd = cls.getMethod("register", (Class[]) null);
                if (Modifier.STATIC != (mthd.getModifiers() & Modifier.STATIC)) {
                    throw new Exception(
                            "register() method is not static (" + cls + ")"
                    );
                }
                // ready to register
                mthd.invoke(null, (Object[]) null);
            }
        } catch (Exception e) {
            System.err.println(
                    "cipher registration error (" + e.getMessage() + ")"
            );
            System.exit(1);
        }
    }
}


text:
package com.cardpay.pccredit.report.model;

/**
 * @author chenzhifang
 *
 * 2014-12-18下午3:39:28
 */
public class NameValueRecord {
	//
	private String id;

	// 名称
	private String name;

	// 值
	private String value;
	private String value1;
	private String value2;

	public String getValue1() {
		return value1;
	}

	public void setValue1(String value1) {
		this.value1 = value1;
	}

	public String getValue2() {
		return value2;
	}

	public void setValue2(String value2) {
		this.value2 = value2;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getValue() {
		return value;
	}

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


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

namespace EventGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<ServiceHost>(s =>
                {
                    s.ConstructUsing(n => new ServiceHost());
                    s.WhenStarted(service => service.Start());
                    s.WhenStopped(service => service.Stop());
                });

                x.RunAsLocalSystem();
                x.UseAssemblyInfoForServiceInfo();
            });
        }
    }
}


text:
Castform App
===================================

Synchronizes weather information from OpenWeatherMap on Android phones and tablets.

Major project for semester 8.

Pre-requisites
--------------
Android SDK 21 or higher

Build Tools version 21.1.2

Android Support AppCompat 22.2.0

Android Support Annotations 22.2.0

Android Support GridLayout 22.2.0

Android Support CardView 22.2.0

Android Support Design 22.2.0

Android Support RecyclerView 22.2.0

Google Play Services GCM 7.0.0

BumpTech Glide 3.5.2

Getting Started
---------------
Uses the Gradle build system.  To build this project, use the "gradlew build" command or use "Import Project" in Android Studio.


text:
<?php

/**
 * Null billing Plugin
 *
 * @package nullbilling
 * @version 1.0.1
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru
 * @license BSD
 */
?>


text:
"""Unit tests for decorators.py."""
import inspect
import logging
import os
import sys

from absl.testing import parameterized
from gazoo_device import decorators
from gazoo_device import errors
from gazoo_device.tests.unit_tests.utils import unit_test_case

class NamedDevice:

  def __init__(self, device_name):
    self.name = device_name

class ShinyNewError(errors.DeviceError):
  pass

class _WithRepr:
  """A class where __repr__ works."""

  def __repr__(self):
    return "Representation"

class _WithoutReprWithStr:
  """A class where __repr__ doesn't work, but __str__ does."""

  def __repr__(self):
    raise ValueError("Something went wrong")

  def __str__(self):
    return "String"

class _WithoutReprWithoutStr:
  """A class where neither __repr__ nor __str__ works."""

  def __repr__(self):
    raise ValueError("Something went wrong")

  def __str__(self):
    raise ValueError("Something went wrong")

class _TestClass:
  """A class with a variety of method signatures."""

  @classmethod
  def class_method(cls):
    """A class method without any arguments."""

  def instance_method_with_positional_arg(self, positional_arg):
    """An instance method with a positional argument."""
    del positional_arg  # Unused.

  def instance_method_with_keyword_arg(self, keyword_arg="foo"):
    """An instance method with a keyword argument."""
    del keyword_arg  # Unused.

  def instance_method_with_positional_and_keyword_arg(
      self, positional_arg, keyword_arg="foo"):
    """An instance method with a positional and a keyword argument."""
    del positional_arg, keyword_arg  # Unused.

def _test_function(positional_arg, keyword_arg="foo"):
  """A function with a positional and a keyword argument."""
  del positional_arg, keyword_arg  # Unused.

_TestClassInstance = _TestClass()

class LogDecoratorSuite(unit_test_case.UnitTestCase):
  """Unit tests for decorators."""

  def setUp(self):
    super().setUp()
    self._create_logger()

  def test_function_name_stays_same(self):
    """Decorator must not change __name__ and __doc__ of the function."""

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger)
      def some_method(self):
        """Some docstring."""
        pass

    test_device = FakeDevice("SomeDevice")
    test_device.some_method()

    self.assertEqual(test_device.some_method.__name__, "some_method")
    self.assertEqual(test_device.some_method.__doc__, "Some docstring.")

  def test_function_return_value_stays_same(self):
    """Decorator must not change return value of the function."""

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger)
      def some_method_with_return(self, return_value):
        return return_value

    test_device = FakeDevice("SomeDevice")

    method_return_value = 5
    result = test_device.some_method_with_return(method_return_value)

    self.assertEqual(result, method_return_value)

  def test_function_signature_stays_same(self):
    """Decorator must not change the function signature."""

    decorator = decorators.LogDecorator(self.test_logger)

    class FakeDevice(NamedDevice):

      def some_method_with_params(self, posparam, kwparam="kwparamval"):
        pass

    test_device = FakeDevice("SomeDevice")

    decorated_method = decorator(test_device.some_method_with_params)

    signature_undecorated = inspect.getfullargspec(
        test_device.some_method_with_params)
    signature_decorated = inspect.getfullargspec(
        decorators.unwrap(decorated_method))

    self.assertEqual(signature_decorated, signature_undecorated)

  def test_silence_no_logs(self):
    """No log messages should be printed in silence mode."""

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.NONE)
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice("SomeDevice")
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    self.assertFalse(file_contents)

  def test_silence_no_skip_message(self):
    """No skip message should be printed in silence mode."""
    skip_reason = "Skipping method some_method_raises_skip"

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.NONE)
      def some_method_raises_skip(self):
        raise decorators.SkipExceptionError(skip_reason)

    test_device = FakeDevice("SomeDevice")
    test_device.some_method_raises_skip()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    self.assertFalse(file_contents)

  def test_silence_exceptions_wrapped(self):
    """Exceptions should still be wrapped in silence mode."""
    error_msg = "Provided Foo was too Bar."
    exc_msg = "ValueError: " + error_msg

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.NONE)
      def some_method_raises(self):
        raise ValueError(error_msg)

    test_device = FakeDevice("SomeDevice")

    self.assertRaisesRegex(errors.DeviceError, exc_msg,
                           test_device.some_method_raises)

  def test_log_messages_printed(self):
    """Decorator should print messages on method start and successful finish."""
    device_name = "SomeDevice"
    self.test_logger.setLevel(decorators.INFO)

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.INFO)
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice(device_name)
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(device_name, FakeDevice.__name__,
                                           test_device.some_method.__name__)
    success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
        device_name, FakeDevice.__name__, test_device.some_method.__name__, 2)
    self.assertIn(start_msg, file_contents)
    self.assertRegex(file_contents, success_rx)

  def test_class_name_for_inherited_methods(self):
    """Tests method class name retrieval for an inherited method."""
    device_name = "SomeDevice"
    self.test_logger.setLevel(decorators.INFO)

    class FakeDeviceParent(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.INFO)
      def some_method(self):
        return 1 + 1

    class FakeDeviceChild(FakeDeviceParent):
      pass

    test_device = FakeDeviceChild(device_name)
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(device_name,
                                           FakeDeviceParent.__name__,
                                           test_device.some_method.__name__)
    success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
        device_name, FakeDeviceParent.__name__,
        test_device.some_method.__name__, 2)
    self.assertIn(start_msg, file_contents)
    self.assertRegex(file_contents, success_rx)
    self.assertNotIn(FakeDeviceChild.__name__, file_contents)

  def test_class_name_for_overridden_methods(self):
    """Tests method class name retrieval for an overridden inherited method."""
    device_name = "SomeDevice"
    self.test_logger.setLevel(decorators.INFO)

    class FakeDeviceParent(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.INFO)
      def some_method(self):
        return 1 + 1

    class FakeDeviceChild(FakeDeviceParent):

      @decorators.LogDecorator(self.test_logger, level=decorators.INFO)
      def some_method(self):
        return super().some_method()

    test_device = FakeDeviceChild(device_name)
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    for class_name in [FakeDeviceParent.__name__, FakeDeviceChild.__name__]:
      start_msg = "{} starting {}.{}".format(device_name, class_name,
                                             test_device.some_method.__name__)
      success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
          device_name, class_name, test_device.some_method.__name__, 2)
      self.assertIn(start_msg, file_contents)
      self.assertRegex(file_contents, success_rx)

  def test_skip_message_printed(self):
    """Tests that decorator prints a skip message."""
    device_name = "SomeDevice"
    skip_reason = "Skipping method some_method_raises_skip"

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger)
      def some_method_raises_skip(self):
        raise decorators.SkipExceptionError(skip_reason)

    test_device = FakeDevice(device_name)
    test_device.some_method_raises_skip()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(
        device_name, FakeDevice.__name__,
        test_device.some_method_raises_skip.__name__)
    success_rx = (r"{} {}.{} returned .*. It took \d+s.".format(
        device_name, FakeDevice.__name__,
        test_device.some_method_raises_skip.__name__))
    skip_msg = ("{} {}.{} skipped. {}".format(
        device_name, FakeDevice.__name__,
        test_device.some_method_raises_skip.__name__, skip_reason))
    self.assertIn(start_msg, file_contents)
    self.assertNotRegex(file_contents, success_rx)
    self.assertIn(skip_msg, file_contents)

  def test_exceptions_wrapped(self):
    """Tests wrapping exceptions in DeviceError."""
    device_name = "SomeDevice"
    error_msg = "Provided Foo was too Bar."
    exc_msg = "ValueError: " + error_msg

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger)
      def some_method_raises(self):
        raise ValueError(error_msg)

    test_device = FakeDevice(device_name)
    with self.assertRaisesRegex(errors.DeviceError, exc_msg):
      test_device.some_method_raises()

  def test_exceptions_wrapped_different_wrap_type(self):
    """Tests wrapping exceptions in a custom wrap_type."""
    device_name = "SomeDevice"
    error_msg = "Provided Foo was too Bar."
    exc_msg = "ValueError: " + error_msg
    wrap_type = ShinyNewError

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, wrap_type=wrap_type)
      def some_method_raises(self):
        raise ValueError(error_msg)

    test_device = FakeDevice(device_name)
    with self.assertRaisesRegex(wrap_type, exc_msg):
      test_device.some_method_raises()

  def test_raise_subclass_of_deviceerror(self):
    """Tests wrapping of errors which are subclasses of DeviceError."""
    device_name = "Dummy_device"
    err_reason = "Dummy error"

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger)
      def some_method_raises(self):
        raise errors.DfuModeError(device_name, err_reason)

    test_device = FakeDevice(device_name)
    self.assertRaisesRegex(errors.DfuModeError, err_reason,
                           test_device.some_method_raises)

  def test_log_messages_printed_no_device_name_available(self):
    """Tests falling back to the default device name, DEFAULT_DEVICE_NAME."""
    device_name = decorators.DEFAULT_DEVICE_NAME

    class FakeDevice:

      @decorators.LogDecorator(self.test_logger)
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice()
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(device_name, FakeDevice.__name__,
                                           test_device.some_method.__name__)
    success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
        device_name, FakeDevice.__name__, test_device.some_method.__name__, 2)
    self.assertIn(start_msg, file_contents)
    self.assertRegex(file_contents, success_rx)

  def test_different_device_name_attribute(self):
    """Test device name attribute that's not 'self.name'."""
    device_name = "CoolDevice"

    class FakeDevice:

      @decorators.LogDecorator(
          self.test_logger, name_attr="some_device_name_attr")
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice()
    test_device.some_device_name_attr = device_name

    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(device_name, FakeDevice.__name__,
                                           test_device.some_method.__name__)
    success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
        device_name, FakeDevice.__name__, test_device.some_method.__name__, 2)
    self.assertIn(start_msg, file_contents)
    self.assertRegex(file_contents, success_rx)

  def test_debug_level_not_in_info_logger(self):
    """Test that debug messages are omitted from logger with INFO level."""
    self.test_logger.setLevel(decorators.INFO)

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.DEBUG)
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice("SomeDevice")
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    self.assertFalse(file_contents)

  def test_info_level_in_debug_logger(self):
    """Test that INFO messages are present in logger with DEBUG level."""
    self.test_logger.setLevel(decorators.DEBUG)
    device_name = "SomeDevice"

    class FakeDevice(NamedDevice):

      @decorators.LogDecorator(self.test_logger, level=decorators.INFO)
      def some_method(self):
        return 1 + 1

    test_device = FakeDevice(device_name)
    test_device.some_method()

    with open(self.log_file) as lf:
      file_contents = lf.read()

    start_msg = "{} starting {}.{}".format(device_name, FakeDevice.__name__,
                                           test_device.some_method.__name__)
    success_rx = r"{} {}.{} returned {}. It took \d+s.".format(
        device_name, FakeDevice.__name__, test_device.some_method.__name__, 2)
    self.assertIn(start_msg, file_contents)
    self.assertRegex(file_contents, success_rx)

  def test_cannot_decorate_non_methods(self):
    """Tests than an error is raised if a non-method is decorated."""
    decorator = decorators.LogDecorator(self.test_logger)

    def func():
      pass

    lambda_func = lambda: None

    invalid_values = [
        func, lambda_func, "string", None, 5, 5.0, {}, [], (),
        set()
    ]

    for val in invalid_values:
      with self.assertRaises(TypeError):
        decorator(val)

  def test_cannot_decorate_static_method(self):
    """Test that methods decorated with @staticmethod cannot be decorated."""
    decorator = decorators.LogDecorator(self.test_logger)

    class SomeClass:

      @staticmethod
      def foo():
        pass

    instance = SomeClass()

    with self.assertRaisesRegex(
        TypeError, r".*Decorating static methods is not supported"):
      decorator(SomeClass.foo)

    with self.assertRaisesRegex(
        TypeError, r".*Decorating static methods is not supported"):
      decorator(instance.foo)

  def test_cannot_decorate_class_method(self):
    """Test that methods decorated with @classmethod cannot be decorated."""
    decorator = decorators.LogDecorator(self.test_logger)

    class SomeClass:

      @classmethod
      def foo(cls):
        pass

    instance = SomeClass()

    with self.assertRaisesRegex(TypeError,
                                r".*Decorating class methods is not supported"):
      decorator(SomeClass.foo)

    with self.assertRaisesRegex(TypeError,
                                r".*Decorating class methods is not supported"):
      decorator(instance.foo)

  def test_unwrap_not_a_function(self):
    """Test unwrap on an object which is not a function."""
    someint = 1
    self.assertEqual(someint, decorators.unwrap(someint))

  def test_unwrap_function_not_decorated(self):
    """Test unwrap on a function which has not been decorated."""

    def foo():
      pass

    self.assertEqual(foo, decorators.unwrap(foo))

  def test_unwrap_decorated_method(self):
    """Test unwrap on a decorated method."""
    decorator = decorators.LogDecorator(self.test_logger)

    class FakeDevice(NamedDevice):

      def some_method(self):
        pass

    test_device = FakeDevice("SomeDevice")

    undecorated_method = test_device.some_method
    decorated_method = decorator(undecorated_method)

    self.assertEqual(undecorated_method, decorators.unwrap(decorated_method))

  def test_arg_to_str_for_repr(self):
    """Tests _arg_to_str() for an object where __repr__ works."""
    self.assertEqual(decorators._arg_to_str(_WithRepr()), "Representation")

  def test_arg_to_str_for_str(self):
    """Tests _arg_to_str() for object where __repr__ fails but __str__ works."""
    self.assertEqual(decorators._arg_to_str(_WithoutReprWithStr()), "String")

  def test_arg_to_str_no_description(self):
    """Tests _arg_to_str() for object where both __repr__ and __str__ fail."""
    self.assertEqual(
        decorators._arg_to_str(_WithoutReprWithoutStr()), "<No description>")

  @parameterized.named_parameters(
      ("no_print_args", False, logging.INFO,
       _TestClassInstance.instance_method_with_positional_arg,
       ("foo",), {}, ""),
      ("debug_arg_length_clipping", True, logging.DEBUG,
       _TestClassInstance.instance_method_with_positional_arg,
       ("a" * 10000,), {},
       "(positional_arg='{})".format(
           "a" * (decorators._MAX_ARG_REPR_LENGTH_DEBUG - 1) + "...")),
      ("info_arg_length_clipping", True, logging.INFO,
       _TestClassInstance.instance_method_with_positional_arg,
       ("a" * 10000,), {},
       "(positional_arg='{})".format(
           "a" * (decorators._MAX_ARG_REPR_LENGTH_INFO - 1) + "...")),
      ("function_with_positional_and_keyword_arg", True, logging.INFO,
       _test_function, ("foo",), {"keyword_arg": "bar"},
       "(positional_arg='foo', keyword_arg='bar')"),
      ("class_method_no_args", True, logging.INFO,
       _TestClass.class_method, (), {}, "()"),
      ("instance_method_positional_arg", True, logging.INFO,
       _TestClassInstance.instance_method_with_positional_arg,
       ("foo",), {}, "(positional_arg='foo')"),
      ("instance_method_keyword_arg", True, logging.INFO,
       _TestClassInstance.instance_method_with_keyword_arg,
       (), {"keyword_arg": "bar"}, "(keyword_arg='bar')"),
      ("instance_method_with_positional_and_keyword_arg", True, logging.INFO,
       _TestClassInstance.instance_method_with_positional_and_keyword_arg,
       ("foo",), {"keyword_arg": "bar"},
       "(positional_arg='foo', keyword_arg='bar')"))
  def test_get_args_and_kwargs_str(
      self, print_args, log_level, method_or_function, args, kwargs, expected):
    """Tests _get_args_and_kwargs_str()."""
    self.assertEqual(
        decorators._get_args_and_kwargs_str(
            print_args=print_args,
            log_level=log_level,
            method_signature=inspect.signature(method_or_function),
            method_args=args,
            method_kwargs=kwargs),
        expected)

  def _create_logger(self):
    self.test_logger = logging.getLogger(self._testMethodName)
    self.log_file = os.path.join(self.artifacts_directory,
                                 self._testMethodName + ".log")
    file_handler = logging.FileHandler(self.log_file, "w")
    self.addCleanup(file_handler.close)

    self.test_logger.addHandler(file_handler)
    self.test_logger.addHandler(logging.StreamHandler(sys.stdout))
    self.test_logger.setLevel(logging.DEBUG)

if __name__ == "__main__":
  unit_test_case.main()


text:
<!DOCTYPE html>

<button id="outer-button" autofocus></button>
<dialog id="outer-dialog">
    <dialog id="dialog" tabindex=0>
        <button disabled></button>
        <dialog>
            <button autofocus></button>
        </dialog>
        <button id="first-button"></button>

                <button id="autofocus-button" autofocus></button>

        <button id="final-button"></button>
    </dialog>
</dialog>


text:
package corbit.tagdep.handler;

import java.util.Set;
import java.util.TreeSet;

import corbit.commons.util.Statics;

public abstract class AtomicFeatures
{
	public final TreeSet<String> fvdelay;

	protected final int numFeatures;
	protected String[] features;
	protected int hash;

	protected AtomicFeatures(int n, TreeSet<String> _fvdelay)
	{
		numFeatures = n;
		features = new String[n];
		hash = 0;
		fvdelay = _fvdelay;
	}

	public String get(int n)
	{
		return features[n];
	}

	@Override
	public int hashCode()
	{
		return hash;
	}

	@Override
	public boolean equals(Object obj)
	{
		// check the equality of the type
		if (obj == null || !(obj instanceof AtomicFeatures))
			return false;
		AtomicFeatures atoms = (AtomicFeatures)obj;

		// return hash == atoms.hash;

		// check the equality of features
		for (int i = 0; i < features.length; ++i)
		{
			String s1 = features[i];
			String s2 = atoms.features[i];
			if ((s1 == null ^ s1 == null) || s1 != null && !s1.equals(s2)) return false;
		}
		// check the equality of delayed features
		Set<String> fvdelay2 = atoms.fvdelay;
		if (fvdelay != null)
		{
			if (fvdelay == null) return false;
			return (Statics.setEquals(fvdelay, fvdelay2));
		}
		else if (fvdelay2 != null) return false;
		return true;
	}

	protected void setHash()
	{
		hash = hash();
	}

	protected int hash()
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < features.length; ++i)
		{
			sb.append(features[i]);
			sb.append(' ');
		}
		if (fvdelay != null)
		{
			for (String s : fvdelay)
			{
				sb.append(s);
				sb.append(' ');
			}
		}
		return sb.toString().hashCode();
	}

}


text:
package OpenXPKI::Workflow::Config;

use strict;
use warnings;

use Workflow 1.39;
use OpenXPKI::Exception;
use OpenXPKI::Debug;
use OpenXPKI::Server::Context qw( CTX );
use Data::Dumper;

use Moose;

has '_workflow_config' => (
    is => 'rw',
    isa => 'HashRef',
    reader => 'workflow_config',
    lazy => 1,
    builder => '_build_workflow_config',
);

has '_config' => (
    is => 'rw',
    isa => 'Object',
    lazy => 1, # This is fundamental! (race condition within loader -> empty ref)
    default => sub { return CTX('config'); }
);

has 'logger' => (
    is => 'ro',
    isa => 'Object',
    lazy => 1,
    default => sub { return CTX('log')->workflow(); }
);

sub _build_workflow_config {
    my $self = shift;

    my $conn = $self->_config();

    # Fetch serialized workflow definition from config layer
    if (!$conn->exists('workflow.def')) {
        my $pki_realm = CTX('session')->data->pki_realm;
        OpenXPKI::Exception->throw(
            message => 'No workflow configuration found for current realm',
            params => {
                realm => $pki_realm,
                config_path => "realm.$pki_realm.workflow.def",
            },
        );
    }

    # Init structure
    my $wf_conf = { condition => [], validator => [], action =>[], workflow => [], persister => [] };

    # Add persisters
    my @persister = sort $conn->get_keys('workflow.persister');
    foreach my $persister (@persister) {
        my $conf = $conn->get_hash(['workflow','persister', $persister]);
        $conf->{name} = $persister;
        push @{$wf_conf->{persister}}, $conf;
    }

    my @global_fields = $self->__process_fields(['workflow', 'global', 'field']);

    # Add workflows
    my %known_prefixes;
    my @workflow_def = sort $conn->get_keys('workflow.def');
    foreach my $wf_name (@workflow_def) {
        # The main workflow definiton (the flow rules)
        push @{$wf_conf->{workflow}}, $self->__process_workflow($wf_name);

        my $prefix = $conn->get( ['workflow', 'def', $wf_name, 'head', 'prefix'] );

        OpenXPKI::Exception->throw(
            message => "Duplicate workflow prefix '$prefix' - unable to load workflow configuration",
            params => { workflow_a => $known_prefixes{$prefix}, workflow_b => $wf_name }
        ) if defined $known_prefixes{$prefix};
        $known_prefixes{$prefix} = $wf_name;

        $prefix = $prefix . '_';

        # Workflow defined actions, conditions, validators
        my @wf_fields = $self->__process_fields(['workflow', 'def', $wf_name, 'field']);
        push @{$wf_conf->{action}},    $self->__process_actions(   ['workflow','def', $wf_name, 'action'], $prefix, $wf_name, [@wf_fields, @global_fields]);
        push @{$wf_conf->{condition}}, $self->__process_conditions(['workflow','def', $wf_name, 'condition'], $prefix);
        push @{$wf_conf->{validator}}, $self->__process_validators(['workflow','def', $wf_name, 'validator'], $prefix);
    }

    # Global actions, conditions, validators
    push @{$wf_conf->{action}},    $self->__process_actions(   ['workflow','global', 'action'], 'global_', undef, \@global_fields);
    push @{$wf_conf->{condition}}, $self->__process_conditions(['workflow','global', 'condition'], 'global_');
    push @{$wf_conf->{validator}}, $self->__process_validators(['workflow','global', 'validator'], 'global_');
    push @{$wf_conf->{validator}}, {
        name => '_internal_basic_field_type',
        class => 'OpenXPKI::Server::Workflow::Validator::BasicFieldType'
    };

    # check for duplicate names
    foreach my $class (('action','condition','validator')) {
        my %known_item;
        foreach my $item (@{$wf_conf->{$class}}) {
            my $name = $item->{name};
            OpenXPKI::Exception->throw(
                message => "Duplicate $class name '$name' - unable to load workflow configuration",
            ) if defined $known_item{$name};
            $known_item{$name} = 1;
        }
    }

    return $wf_conf;
}

sub __process_workflow {
    my ($self, $wf_name) = @_;

    my $workflow = {
        type => $wf_name,
        persister => 'OpenXPKI',
        observer => [
            { class => 'OpenXPKI::Server::Workflow::Observer::AddExecuteHistory' },
            { class => 'OpenXPKI::Server::Workflow::Observer::Log' },
        ],
        state => []
    };

    my $conn = $self->_config();
    my @cfg_wf_head = ('workflow', 'def', $wf_name, 'head');
    my @cfg_wf_state = ('workflow', 'def', $wf_name, 'state');

    my $wf_persister = $conn->get( [ @cfg_wf_head, 'persister' ] );
    $workflow->{persister} = $wf_persister if $wf_persister;

    my $wf_prefix = $conn->get( [ @cfg_wf_head, 'prefix' ] );

    if (!$wf_prefix || ($wf_prefix =~ /[^a-z0-9]/)) {
        OpenXPKI::Exception->throw(
            message => 'Workflow prefix must be set and contain no other chars as a-z and 0-9',
            params => {
                name => $wf_name,
                prefix => $wf_prefix
            }
        );
    }

    my @states = sort $conn->get_keys( \@cfg_wf_state );

    # The FAILURE state is required for the autofail feature
    push @states, 'FAILURE' unless (grep /FAILURE/, @states);

    foreach my $state_name (@states) {
        # We are not interested in eye candy, just the logic.
        # 'action' attribute has a list/scalar with a combo string.
        # Left hand is action name, right hand the target state:
        #   action: run_test1 > PENDING

        my @actions;
        my @action_items = $conn->get_scalar_as_list([ @cfg_wf_state, $state_name, 'action' ] );

        foreach my $action_item (@action_items) {
            my ($auto, $global, $action_name, $next_state, $nn, $conditions) =
                ($action_item =~ m{ \A (\W?)(global_)?([\w\s]+\w)\s*>\s*(\w+)(\s*\?\s*([!\w\s]+))? }xs);

            # Support for internal chaining of actions, sep. by space
            my @inline_action = split /\s+/, $action_name;
            $action_name = shift @inline_action;

            $self->logger()->debug("Adding action: $action_name -> $next_state");

            # As actions share a global namespace, we add a prefix to their names
            # except if the action has the "global" prefix
            my $prefix = $global ? 'global_' : "${wf_prefix}_";

            my $item = {
                name => $prefix.$action_name,
                resulting_state => $next_state
            };
            if ($conditions) {
                my @conditions = split /\s+/, $conditions;
                $item->{condition} = [];
                # we need to insert the prefix and take care of the ! mark
                foreach my $cond (@conditions) {
                    # Check for opposite
                    my $flag_opposite = '';
                    if ($cond =~ /^!/) {
                        $flag_opposite = '!';
                        $cond = substr($cond,1);
                    }

                    # Conditions can have another prefix then the action, so check for it
                    if ($cond !~ /^global_/) {
                        $cond = $wf_prefix.'_'.$cond;
                    }

                    # Merge opposite and prefixed name
                    push @{$item->{condition}}, { name => $flag_opposite.$cond }

                }
            }

            # TODO - this is experimental!
            if (scalar @inline_action) {

                $self->logger()->debug("Auto append inline actions: " . join (" > ", @inline_action));

                my $generator_name = uc($state_name.'_'.$item->{name}).'_%01d';
                my $generator_index = 0;

                # point the first action to the first auto generated state
                $item->{resulting_state} = sprintf($generator_name, $generator_index);

                while (my $auto_action = shift @inline_action) {

                    if ($auto_action !~ /^global_/) {
                        $auto_action = $wf_prefix.'_'.$auto_action;
                    }

                    push @{$workflow->{state}}, {
                        name => sprintf($generator_name, $generator_index++),
                        autorun => 'yes',
                        action => [{
                            name => $auto_action,
                            resulting_state => (scalar @inline_action ? sprintf($generator_name, $generator_index) : $next_state),
                        }]
                    };
                }
            }

            push @actions, $item;

        } # end actions

        my $state = {
            name => $state_name,
            action => \@actions
        };

        # Autorun
        my $is_autorun = $conn->get([ @cfg_wf_state, $state_name, 'autorun' ] );
        if ($is_autorun && $is_autorun =~ m/(1|true|yes)/) {
            $state->{autorun} = 'yes';
        }
        push @{$workflow->{state}}, $state;

    } # end states

    $self->logger()->info("Adding workflow: $wf_name");

    ##! 32: 'Workflow Config ' . Dumper $workflow
    return $workflow;
}

sub __process_fields {
    my ($self, $root_path) = @_;
    my @result = ();
    my $conn = $self->_config();

    for my $field_name (sort $conn->get_keys($root_path)) {
        my @path = (@{$root_path}, $field_name);
        ##! 16: 'Processing field ' . join (".", @path)

        my $context_key = $conn->get([ @path, 'name' ]) || $field_name;
        my $type = $conn->get( [ @path, 'type' ] ) || '';

        my $field = {
            name => $field_name,
            context_key => $context_key,
            type => $type,
        };
        #
        # check if validator is needed
        #
        my $is_array = ($conn->exists( [ @path, 'min' ] ) || $conn->exists( [ @path, 'max' ] ));
        # As the upstream "required" validator accepts the empty string as
        # true which we want to be "false" we do not set the required flag
        # but use our own field type validator
        my $required = $conn->get( [ @path, 'required' ] );
        my $is_required = (defined $required && $required =~ m/(yes|1)/i);
        my $match = $conn->get( [ @path, 'match' ] ) || '';

        ##! 64: "Adding basic validator for $context_key with $type:$is_array:$is_required:$match"
        # this string will be interpreted in OpenXPKI::Server::Workflow::Validator::BasicFieldType
        $field->{basic_validator} = sprintf ("%s:%s:%01d:%01d:%s", $context_key, $type, $is_array, $is_required, $match);

        push @result, $field;
    }
    return @result;
}

=head2 __process_actions

Add the action implementation details to the global action definition.
This includes class, class params, fields and validators.

=cut
sub __process_actions {
    my ($self, $root_path, $prefix, $wf_name, $fields) = @_;
    my @result = ();
    my $conn = $self->_config();

    for my $action_name (sort $conn->get_keys($root_path)) {
        my @path = (@{$root_path}, $action_name);
        $self->logger()->debug("Adding action definition: " . join (".", @path));
        ##! 16: 'Processing action ' . join (".", @path)

        # Get the implementation class
        my $action_class = $conn->get([ @path, 'class' ] );

        # Get input fields
        my @input = $conn->get_scalar_as_list( [ @path, 'input' ] );
        my @fields = ();

        my @basic_validator = ();
        foreach my $field_name (@input) {
            # it is important to use grep on the sorted list here as $fields
            # contains the local and global definitions so there might be a
            # "wrong" definition in a later position.
            my ($field) = grep { $_->{name} eq $field_name } @{$fields};
            if (!$field) {
                OpenXPKI::Exception->throw(
                    message => 'Field name used in workflow config is not defined',
                    params => {
                        workflow => $wf_name,
                        action => $action_name,
                        field => $field_name,
                    }
                );
            }
            push @basic_validator, $field->{basic_validator} if $field->{basic_validator}; # 'basic_validator' is set in __process_fields()
            push @fields, {
                name => $field->{context_key},
                is_required => 'no',
                class => 'OpenXPKI::Server::Workflow::Field', # Workflow::Action::InputField always sets type to "basic"
                type => $field->{type},
            };
            $self->logger()->debug("- adding field $field_name / $field->{context_key}");
        }

        my @validators = ();

        ##! 32: 'Basic validator ' . Dumper \@basic_validator

        # add basic validator - if required (class: OpenXPKI::Server::Workflow::Validator::BasicFieldType)
        push @validators, { name => '_internal_basic_field_type', arg => \@basic_validator } if (scalar @basic_validator > 0);

        # Attach validators - name => $name, arg  => [ $value ]
        my @valid = $conn->get_scalar_as_list( [ @path, 'validator' ] );
        foreach my $valid_name (@valid) {

            my @item_path;
            # Inside workflow, check if validator has global prefix
            if ($valid_name =~ /^global_(\S+)/) {
                @item_path = ( 'workflow', 'global', 'validator', $1 );
            } else {
                # Are we in a global definiton?
                if ($wf_name) {
                    @item_path = ( 'workflow', 'def', $wf_name, 'validator', $valid_name );
                } else {
                    @item_path = ( 'workflow', 'global', 'validator', $valid_name );
                }
                 # Prefix is global_ in global defs, so matches both cases
                $valid_name = $prefix.$valid_name;
            }

            # Validator can have an argument list, params are handled by the global implementation definiton!
            my @extra_args = $conn->get_scalar_as_list( [ @item_path, 'arg' ] );

            ##! 16: 'Validator path ' . Dumper \@item_path
            ##! 16: 'Validator arguments ' . Dumper @extra_args

            $self->logger()->debug("Adding validator $valid_name with args " . (join", ", @extra_args));

            # Push to the field list for the action
            push @validators, { name => $valid_name,  arg => \@extra_args };

        }

        my $action = {
            name => $prefix.$action_name,
            class => $action_class,
            field => \@fields,
            validator => \@validators,
        };

        # Additional params are read from the object itself
        my $param = $conn->get_hash([ @path, 'param' ] );
        $action->{$_} = $param->{$_} for sort keys %{$param};

        $self->logger()->trace("Adding action " . (Dumper $action)) if $self->logger->is_trace;
        ##! 32: 'Action definition: ' . Dumper($action)

        push @result, $action;
    }
    return @result;
}

=head2 __process_conditions

Add the condition implementation details to the global definition.
This includes class, class params and parameters.

=cut
sub __process_conditions {
    my ($self, $root_path, $prefix) = @_;
    my @result = ();
    my $conn = $self->_config();

    for my $condition_name (sort $conn->get_keys($root_path)) {
        my @path = (@{$root_path}, $condition_name);
        $self->logger()->debug("Adding condition " . join(".", @path));
        ##! 16: 'Processing condition ' . join (".", @path)

        # Get the implementation class
        my $condition_class = $conn->get([ @path, 'class' ] );

        # FIXME - remove once upstream Workflow::Condition::Evaluate got rid of the "Safe" module
        $condition_class = "OpenXPKI::Server::Workflow::Condition::Evaluate" if "Workflow::Condition::Evaluate" eq $condition_class;

        my $condition = {
            name => $prefix.$condition_name,
            class => $condition_class,
        };

        # Get params
        my $param = $conn->get_hash([ @path, 'param' ] );
        my @param = map { { name => $_, value => $param->{$_} } } sort keys %{$param};

        if (scalar @param) {
            $condition->{param} = \@param;
        }

        $self->logger()->trace("Adding condition " . (Dumper $condition)) if $self->logger->is_trace;
        push @result, $condition;
    }

    return @result;
}

=head2 __process_validators

Add the validator implementation details to the global definition.
This includes class, class params and parameters.

=cut
sub __process_validators {
    my ($self, $root_path, $prefix) = @_;
    my @result = ();
    my $conn = $self->_config();

    for my $validator_name (sort $conn->get_keys($root_path)) {
        my @path = (@{$root_path}, $validator_name);
        $self->logger()->debug("Adding validator " . join(".", @path));
        ##! 16: 'Processing validator ' . join (".", @path)

        # Get the implementation class
        my $validator_class = $conn->get([ @path, 'class' ] );

        my $validator = {
            name => $prefix.$validator_name,
            class => $validator_class,
        };

        # Get params
        my $param = $conn->get_hash([ @path, 'param' ] );
        my @param = map { { name => $_, value => $param->{$_} } } sort keys %{$param};

        if (scalar @param) {
            $validator->{param} = \@param;
        }

        $self->logger()->trace("Adding validator " . (Dumper $validator)) if $self->logger->is_trace;
        push @result, $validator;
    }
    return @result;
}

__PACKAGE__->meta->make_immutable;

__END__;


text:
var express = require('express');
var request = require('request');
var fs = require('fs');
var config = require('../config');
var app = express();

// during the initialize call below, the app will replace the following data
// with data of the config file.
var SSOconfig = {
    partnerId: "PSN2-SAML2-Entity",
    startUrl : "https://sso.mypsn.com/sp/startSSO.ping",
    refUrl : "https://sso.mypsn.com/ext/ref/pickup",
    protocol:'http://',
    headers: {
      "ping.uname": 'PSN2AgentlessDemoUser',
      "ping.pwd": 'jlAclUVoA6oAfrlUbOEMo-Troe*',
      "ping.instanceId": "PSN2AgentlessDemo"
      }
};
var casigningcert = "";

var security = {
  initialize: function(opts) {
    for(k in opts){
        v = opts[k];
        SSOconfig[k] = v;
    }
  },
  authenticationRequired: function(req, res, next) {
    // console.log('authRequired');
    // console.log('cookie:', req.cookies.BechtelEmailAddress);
    // Should check SSO instead
    if(req.headers && req.cookies.BechtelEmailAddress){
        req.sso = {
            email: req.cookies.BechtelEmailAddress.toLowerCase(),
            token: req.cookies.OAuthToken
        };
        next();
    } else {
        // Just send the index.html for logout
        // res.sendfile('index.html', { root: config.server.distFolder });
        res.sendfile('login.html', { root: config.server.distFolder });
    }
  },
  login: function(req, res, next) {
    callback = SSOconfig.protocol + req.header('host') + "/";
    opt = {
          url: SSOconfig.startUrl + "?PartnerIdpId=" + SSOconfig.partnerId + "&TargetResource=" + callback,
          headers: SSOconfig.headers
     };
    var stream = request(opt);
    stream.pipe(res);

    stream.on( 'error', function(e) {
        console.log("Security Login Error - Stream", e);
        // Just send the login.html
        res.sendfile('login.html', { root: config.server.distFolder });
    });

  },
  reflogin: function(req, res, next){
    url = SSOconfig.refUrl + "?REF=" + req.params.ref;
    opt = {headers: SSOconfig.headers};
    // console.log("url", url, "opt", opt);

    request( url, opt, function(err, resp, body) {
        if(err){
            console.log("Security Login Error - Err", err);
            return res.send(500,{error:err.message});
        }
        try{
            out=JSON.parse(body);
        }
        catch(e){
            console.log("Security Login Error - Catch", e);
            return res.send(500, {error:"Invalid REF token"});
        }
        console.log("reflogin", out);
        return res.send(200, out);

    });
  },
  prelogin: function(req, res, next){
      // console.log("requesting login page");
    return res.sendfile('login.html', { root: config.server.distFolder });
  }
};

module.exports = security;


text:
.class public interface abstract Landroid/net/wifi/p2p/WifiP2pManager$WifiP2pLinkInfoListener;
.super Ljava/lang/Object;
.source "WifiP2pManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/p2p/WifiP2pManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "WifiP2pLinkInfoListener"
.end annotation

# virtual methods
.method public abstract onLinkInfoAvailable(Landroid/net/wifi/p2p/link/WifiP2pLinkInfo;)V
.end method


text:
"""Tests for tfx.tools.cli.handler.kubeflow_handler."""

import datetime
import os
import sys
from unittest import mock

import kfp
import tensorflow as tf

from tfx.dsl.components.base import base_driver
from tfx.dsl.io import fileio
from tfx.tools.cli import labels
from tfx.tools.cli.handler import kubeflow_dag_runner_patcher
from tfx.tools.cli.handler import kubeflow_handler
from tfx.utils import test_case_utils

class _MockRunResponse:

  def __init__(self, pipeline_name, run_id, status, created_at):
    self.pipeline_spec = mock.MagicMock()
    self.pipeline_spec.pipeline_name = pipeline_name
    self.id = run_id
    self.status = status
    self.created_at = created_at

class KubeflowHandlerTest(test_case_utils.TfxTest):

  def setUp(self):
    super().setUp()

    # Flags for handler.
    self.engine = 'kubeflow'
    self.chicago_taxi_pipeline_dir = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'testdata')

    self.enter_context(test_case_utils.change_working_dir(self.tmp_dir))
    self.enter_context(
        test_case_utils.override_env_var('KFP_E2E_BASE_CONTAINER_IMAGE',
                                         'dummy-image'))
    self.enter_context(
        test_case_utils.override_env_var('KFP_E2E_BUCKET_NAME', 'dummy-bucket'))
    self.enter_context(
        test_case_utils.override_env_var('KFP_E2E_TEST_DATA_ROOT',
                                         'dummy-root'))

    self.pipeline_path = os.path.join(self.chicago_taxi_pipeline_dir,
                                      'test_pipeline_kubeflow_1.py')
    self.pipeline_name = 'chicago_taxi_pipeline_kubeflow'

    # Kubeflow client params.
    self.endpoint = 'dummyEndpoint'
    self.namespace = 'kubeflow'
    self.iap_client_id = 'dummyID'

    self.runtime_parameter = {'a': '1', 'b': '2'}

    default_flags = {
        labels.ENGINE_FLAG: self.engine,
        labels.ENDPOINT: self.endpoint,
        labels.IAP_CLIENT_ID: self.iap_client_id,
        labels.NAMESPACE: self.namespace,
    }

    self.flags_with_name = {
        **default_flags,
        labels.PIPELINE_NAME: self.pipeline_name,
    }

    self.flags_with_runtime_param = {
        **default_flags,
        labels.PIPELINE_NAME: self.pipeline_name,
        labels.RUNTIME_PARAMETER: self.runtime_parameter,
    }

    self.flags_with_dsl_path = {
        **default_flags,
        labels.PIPELINE_DSL_PATH: self.pipeline_path,
    }

    # Pipeline args for mocking subprocess.
    self.pipeline_args = {'pipeline_name': 'chicago_taxi_pipeline_kubeflow'}
    self.pipeline_id = 'the_pipeline_id'
    self.experiment_id = 'the_experiment_id'
    self.pipeline_version_id = 'the_pipeline_version_id'

    mock_client_cls = self.enter_context(
        mock.patch.object(kfp, 'Client', autospec=True))
    self.mock_client = mock_client_cls.return_value
    # Required to access generated apis.
    self.mock_client._experiment_api = mock.MagicMock()

    self.mock_client.get_pipeline_id.return_value = self.pipeline_id
    self.mock_client.get_experiment.return_value.id = self.experiment_id
    versions = [mock.MagicMock()]
    versions[0].id = self.pipeline_version_id
    self.mock_client.list_pipeline_versions.return_value.versions = versions

  def testCreatePipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_dsl_path)

    self.mock_client.get_pipeline_id.return_value = None
    self.mock_client.upload_pipeline.return_value.id = 'new_pipeline_id'

    handler.create_pipeline()

    self.mock_client.upload_pipeline.assert_called_once_with(
        pipeline_package_path=mock.ANY,
        pipeline_name=self.pipeline_name)
    self.mock_client.create_experiment.assert_called_once_with(
        self.pipeline_name)
    self.mock_client.upload_pipeline_version.assert_not_called()

  def testCreatePipelineExistentPipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_dsl_path)

    # 'the_pipeline_id' will be returned.
    with self.assertRaises(SystemExit) as err:
      handler.create_pipeline()
    self.assertIn(
        f'Pipeline "{self.pipeline_args[labels.PIPELINE_NAME]}" already exists.',
        str(err.exception))
    self.mock_client.upload_pipeline.assert_not_called()

  def testUpdatePipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_dsl_path)

    # Update test_pipeline and run update_pipeline
    handler.update_pipeline()

    self.mock_client.upload_pipeline.assert_not_called()
    self.mock_client.create_experiment.assert_not_called()
    self.mock_client.upload_pipeline_version.assert_called_once_with(
        pipeline_package_path=mock.ANY,
        pipeline_version_name=mock.ANY,
        pipeline_id=self.pipeline_id)

  def testUpdatePipelineNoPipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_dsl_path)

    self.mock_client.get_pipeline_id.return_value = None

    with self.assertRaises(SystemExit) as err:
      handler.update_pipeline()
    self.assertIn(f'Cannot find pipeline "{self.pipeline_name}".',
                  str(err.exception))

    self.mock_client.upload_pipeline.assert_not_called()
    self.mock_client.upload_pipeline_version.assert_not_called()

  def testCompilePipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_dsl_path)
    with self.captureWritesToStream(sys.stdout) as captured:
      handler.compile_pipeline()
    self.assertIn('Pipeline compiled successfully', captured.contents())
    self.assertIn('Pipeline package path', captured.contents())

  def testDeletePipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_name)

    handler.delete_pipeline()

    self.mock_client.delete_pipeline.assert_called_once_with(self.pipeline_id)
    self.mock_client._experiment_api.delete_experiment.assert_called_once_with(
        self.experiment_id)

  def testDeletePipelineNonExistentPipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_name)

    self.mock_client.get_pipeline_id.return_value = None

    with self.assertRaises(SystemExit) as err:
      handler.delete_pipeline()
    self.assertIn(f'Cannot find pipeline "{self.pipeline_name}".',
                  str(err.exception))
    self.mock_client.delete_pipeline.assert_not_called()
    self.mock_client._experiment_api.delete_experiment.assert_not_called()

  @mock.patch.object(
      kubeflow_handler.KubeflowHandler, 'execute_dsl', autospec=True)
  def testGetSchema(self, mock_execute_dsl):
    temp_pipeline_root = os.path.join(self.tmp_dir, 'pipeline_root')

    handler = kubeflow_handler.KubeflowHandler(
        {labels.ENGINE_FLAG: self.engine})
    assert isinstance(handler, kubeflow_handler.KubeflowHandler)
    mock_execute_dsl.return_value = {
        kubeflow_dag_runner_patcher.KubeflowDagRunnerPatcher.PIPELINE_NAME:
            self.pipeline_name,
        kubeflow_dag_runner_patcher.KubeflowDagRunnerPatcher.PIPELINE_ROOT:
            temp_pipeline_root
    }

    # No pipeline root
    with self.assertRaises(SystemExit) as err:
      handler.get_schema()
    self.assertEqual(
        str(err.exception),
        'Create a run before inferring schema. If pipeline is already running, then wait for it to successfully finish.'
    )

    # No SchemaGen output.
    fileio.makedirs(temp_pipeline_root)
    with self.assertRaises(SystemExit) as err:
      handler.get_schema()
    self.assertEqual(
        str(err.exception),
        'Either SchemaGen component does not exist or pipeline is still running. If pipeline is running, then wait for it to successfully finish.'
    )

    # Successful pipeline run.
    # Create fake schema in pipeline root.
    component_output_dir = os.path.join(temp_pipeline_root, 'SchemaGen')
    schema_path = base_driver._generate_output_uri(  # pylint: disable=protected-access
        component_output_dir, 'schema', 3)
    fileio.makedirs(schema_path)
    with open(os.path.join(schema_path, 'schema.pbtxt'), 'w') as f:
      f.write('SCHEMA')
    with self.captureWritesToStream(sys.stdout) as captured:
      handler.get_schema()
      curr_dir_path = os.path.join(os.getcwd(), 'schema.pbtxt')
      self.assertIn('Path to schema: {}'.format(curr_dir_path),
                    captured.contents())
      self.assertIn(
          '*********SCHEMA FOR {}**********'.format(
              self.pipeline_name.upper()), captured.contents())
      self.assertTrue(fileio.exists(curr_dir_path))

  def testCreateRun(self):
    self.mock_client.run_pipeline.return_value = _MockRunResponse(
        self.pipeline_name, '1', 'Success', datetime.datetime.now())

    handler = kubeflow_handler.KubeflowHandler(self.flags_with_runtime_param)
    with self.captureWritesToStream(sys.stdout) as captured:
      handler.create_run()
    self.assertIn('Run created for pipeline: ', captured.contents())
    self.mock_client.run_pipeline.assert_called_once_with(
        experiment_id=self.experiment_id,
        job_name=self.pipeline_name,
        params={
            'a': '1',
            'b': '2'
        },
        version_id=self.pipeline_version_id)

  def testCreateRunNoPipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_name)

    self.mock_client.get_pipeline_id.return_value = None

    with self.assertRaises(SystemExit) as err:
      handler.create_run()
    self.assertIn(f'Cannot find pipeline "{self.pipeline_name}".',
                  str(err.exception))
    self.mock_client.run_pipeline.assert_not_called()

  def testListRuns(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_name)

    self.mock_client.list_runs.return_value.runs = [
        _MockRunResponse(self.pipeline_name, '1', 'Success',
                         datetime.datetime.now()),
        _MockRunResponse(self.pipeline_name, '2', 'Failed',
                         datetime.datetime.now()),
    ]

    with self.captureWritesToStream(sys.stdout) as captured:
      handler.list_runs()

    self.mock_client.list_runs.assert_called_once_with(
        experiment_id=self.experiment_id)
    self.assertIn('pipeline_name', captured.contents())

  def testListRunsNoPipeline(self):
    handler = kubeflow_handler.KubeflowHandler(self.flags_with_name)

    self.mock_client.get_pipeline_id.return_value = None

    with self.assertRaises(SystemExit) as err:
      handler.list_runs()
    self.assertIn(f'Cannot find pipeline "{self.pipeline_name}".',
                  str(err.exception))

if __name__ == '__main__':
  tf.test.main()


text:
module.exports = (buildup) => {
  buildup.task('hello:world', function (done) {
    // Inside here is any task logic
    buildup.logger.info('Hello World!');
    done();
  })
  buildup.task('hello', ['hello:world'], function (done) {
    // Inside here is any task logic
    buildup.logger.info('Welcome to buildup!');
    done();
  })
}


text:
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_

#include "grpcpp/grpcpp.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/macros.h"

namespace tensorflow {

// Represents a pending asynchronous client call as a tag that can be
// stored in a `grpc::CompletionQueue`.
class GrpcClientCQTag {
 public:
  GrpcClientCQTag() {}
  virtual ~GrpcClientCQTag() {}

  // OnCompleted is invoked when the RPC has finished.
  // Implementations of OnCompleted can delete *this.
  virtual void OnCompleted(bool ok) = 0;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(GrpcClientCQTag);
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_


text:
/*global QUnit,sinon*/

(function (QUnit, sinon, core, controller, xmlview) {
	"use strict";

	sap.ui.require(["jquery.sap.global"], function (jQuery) {

		jQuery.sap.registerModulePath("view", "./view");

		controller("viewController", {});

		QUnit.module("ObjectPage - Rendering - Footer Visibility", {
			beforeEach: function () {
				this.objectPageSampleView = xmlview("UxAP-162_ObjectPageSample", {
					viewName: "view.UxAP-162_ObjectPageSample"
				});
				sinon.config.useFakeTimers = true;
				this.objectPageSampleView.placeAt("qunit-fixture");
				core.applyChanges();
				this.oObjectPage = this.objectPageSampleView.byId("objectPage162");
			},
			afterEach: function () {
				this.objectPageSampleView.destroy();
			}
		});

		QUnit.test("ObjectPage Footer rendered correctly", function (assert) {
			var $footerWrapper = this.oObjectPage.$("footerWrapper"),
				oFooter = this.oObjectPage.getFooter(),
				$footer = oFooter.$();

			assert.ok($footer.length, "The footer is rendered");
			assert.ok($footerWrapper.length, "The footer wrapper is rendered");

			this.oObjectPage.setShowFooter(true);

		});

		QUnit.test("ObjectPage Footer visibility", function (assert) {
			var $footerWrapper = this.oObjectPage.$("footerWrapper"),
				oFooter = this.oObjectPage.getFooter(),
				$footer = oFooter.$();

			assert.ok($footerWrapper.hasClass("sapUiHidden"), "Footer is not visible initially");
			this.oObjectPage.setShowFooter(true);

			assert.ok(!$footerWrapper.hasClass("sapUiHidden"), "Footer is visible");
			assert.ok($footer.hasClass("sapUxAPObjectPageFloatingFooterShow"));
			this.oObjectPage.setShowFooter(false);

			core.applyChanges();
			this.clock.tick(1000);

			assert.ok($footerWrapper.hasClass("sapUiHidden"), "Footer is not visible");
			assert.ok($footer.hasClass("sapUxAPObjectPageFloatingFooterHide"));

			this.oObjectPage.setShowFooter(true);

			assert.ok(!$footerWrapper.hasClass("sapUiHidden"), "Footer is visible again");
			assert.ok($footer.hasClass("sapUxAPObjectPageFloatingFooterShow"));
		});

		QUnit.test("ObjectPage Footer is visible after setting to false and then to true consecutively", function (assert) {
			var $footerWrapper = this.oObjectPage.$("footerWrapper");

			this.oObjectPage.setShowFooter(false);
			this.oObjectPage.setShowFooter(true);

			this.clock.tick(1000);

			assert.ok(!$footerWrapper.hasClass("sapUiHidden"), "Footer is visible");
		});

		QUnit.test("Animation CSS class is removed after the animation is over", function (assert) {
			var oFooter = this.oObjectPage.getFooter(),
				$footer = oFooter.$(),
				iSomeMsBeforeAnimationEnd = 20;

			this.oObjectPage.setShowFooter(true);

			this.clock.tick(sap.uxap.ObjectPageLayout.FOOTER_ANIMATION_DURATION - iSomeMsBeforeAnimationEnd);
			assert.ok($footer.hasClass("sapUxAPObjectPageFloatingFooterShow"), "Animation CSS class is still there while animation is running");

			this.clock.tick(iSomeMsBeforeAnimationEnd + 1);
			assert.ok(!$footer.hasClass("sapUxAPObjectPageFloatingFooterShow"), "Animation CSS class is removed");
		});
	});

}(QUnit, sinon, sap.ui.getCore(), sap.ui.controller, sap.ui.xmlview));


text:
class CintercloudGW:
	"""Class to define the intercloudGW category structure"""
	def __init__( self,name,node,account,price,state ):
		"""Constructor of the class"""
		self.name = name
		self.node = node
		self.account = account
		self.price = price
		self.state = state


text:
var queryAABB = qc.defineBehaviour('qc.engine.queryAABB', qc.Behaviour, function() {
    // need this behaviour be scheduled in editor
    //this.runInEditor = true;
}, {
    // fields need to be serialized
    graphicsNode : qc.Serializer.NODE,
    toggles : qc.Serializer.NODE
});

// Called when the script instance is being loaded.
queryAABB.prototype.awake = function() {
    var self = this;
    self.lastGameObjects = [];

    var toggleGroup = this.toggles.getScript('qc.ToggleGroup');
    self.itemType = toggleGroup.toggle.name;
    this.addListener(toggleGroup.onValueChange, function() {
        self.itemType = toggleGroup.toggle.name;
    });
};

// 恢复 tint 颜色
queryAABB.prototype.tryRestoreTint = function(event) {
    if (!this.lastGameObjects.length) return;
    for (var i = 0; i < this.lastGameObjects.length; i++) {
        this.lastGameObjects[i].colorTint = new qc.Color(0xffffff);
    }
    this.lastGameObjects = [];
};

// 拖拽的时候,绘制拖拽框
queryAABB.prototype.onDrag = function(event) {
    var self = this;
    self.tryRestoreTint();

    var source = event.source;
    var startX = source.startX;
    var startY = source.startY;
    var endX = source.x;
    var endY = source.y;

    var x = Math.min(startX, endX);
    var y = Math.min(startY, endY);
    var width = Math.abs(startX - endX);
    var height = Math.abs(startY - endY);
    this.graphicsNode.getScript('qc.engine.drawGraphics').drawRect(x, y, x + width, y + height);

	var result = this.game.box2d.queryAABB(x, y, width, height, true, function(gameObject) {
        var name = gameObject.parent.name;
        if (name === self.itemType || self.itemType === 'both') return true;
        return false;
    });
    var len = result.length;

    self.lastGameObjects = [];
	for (var i = 0; i < len; i++) {
        var info = result[i];
        info.gameObject.colorTint = new qc.Color(0xCC2255);
        self.lastGameObjects.push(info.gameObject);
    }
};

// 拖拽结束清空
queryAABB.prototype.onDragEnd = function(event) {
    this.tryRestoreTint();
    this.graphicsNode.clear();
};


text:
<?php

namespace DTS\eBaySDK\Shopping\Enums\Test;

use DTS\eBaySDK\Shopping\Enums\FeedbackRatingDetailCodeType;

class FeedbackRatingDetailCodeTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new FeedbackRatingDetailCodeType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Shopping\Enums\FeedbackRatingDetailCodeType', $this->obj);
    }
}


text:
ribbbon
=======

Reminder+Backbone.js


text: <div class="element star" v-for="star of stars" :style="`left: ${star[0]};top: ${star[1]};animation-delay: ${star[2]};`">


text:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Candidate extends Model {

    protected $guarded = [];

}


text:
/**
     * Standardize the given input tuples. This means that the mean of
     * the given tuples is subtracted from them, and they are divided
     * by the standard deviation.

     *

     * The results will be written into the given result tuples.
     * If the given results list is null, then a new
     * list will be created and returned.

     *

     * If the result list is not null, then it must have the
     * same size as the input collection, otherwise an
     * IllegalArgumentException will be thrown.

     *

     * If the input collection contains null elements, then a
     * NullPointerException will be thrown.

     *

     * If the result list contains null elements, then a
     * NullPointerException will be thrown.

     *

     * The input collection and the results list may contain
     * pairwise identical elements.

     *

     * The input collection and the results list may be identical.
     *

     * @param inputs The input tuples
     * @param results The result tuples
     * @return The result tuples
     * @throws IllegalArgumentException If the result list is not
     * null and has a size that is different from the size
     * of the input collection
     * @throws NullPointerException If the inputs list is null
     * or contains null elements, or if the output list is
     * non-null and contains null elements
     */
    public static List<MutableDoubleTuple> standardize(
        Collection<? extends DoubleTuple> inputs,
        List<MutableDoubleTuple> results)
    {
        results = validate(inputs, results);
        MutableDoubleTuple mean = arithmeticMean(inputs, null);
        MutableDoubleTuple standardDeviation =
            standardDeviationFromMean(inputs, mean, null);
        int index = 0;

        for (DoubleTuple input : inputs)
        {
            MutableDoubleTuple result = results.get(index);
            DoubleTuples.subtract(input, mean, result);
            DoubleTuples.divide(result, standardDeviation, result);
            index++;
        }

        boolean printResults = false;
        //printResults = true;
        if (printResults)
        {
            MutableDoubleTuple newMean = arithmeticMean(results, null);
            MutableDoubleTuple newStandardDeviation =
                standardDeviationFromMean(results, newMean, null);
            DoubleTuple min = min(results, null);
            DoubleTuple max = max(results, null);
            System.out.println("After standardization:");
            System.out.println("mean              : "+newMean);
            System.out.println("standard deviation: "+newStandardDeviation);
            System.out.println("min               : "+min);
            System.out.println("max               : "+max);
        }

        return results;
    }

    /**
     * Validate the given results list. If the given results list
     * is null, then a new results list will be created
     * and returned, that contains one MutableDoubleTuple instance
     * for each tuple from the inputs list, with the same size
     * as the corresponding tuple from the input collection.

     *

     * If the result list is not null, then it must have the
     * same size as the input collection, otherwise an
     * IllegalArgumentException will be thrown.

     *

     *
     * @param inputs The inputs
     * @param results The results
     * @return The results
     * @throws IllegalArgumentException If the given results list is not
     * null, and has a different size than the given inputs
     * collection
     */
    private static List<MutableDoubleTuple> validate(
        Collection<? extends DoubleTuple> inputs,
        List<MutableDoubleTuple> results)
    {
        if (results == null)
        {
            results = new ArrayList<MutableDoubleTuple>(inputs.size());
            for (DoubleTuple input : inputs)
            {
                results.add(DoubleTuples.create(input.getSize()));
            }
        }
        else
        {
            if (inputs.size() != results.size())
            {
                throw new IllegalArgumentException(
                    "The number of inputs (" + inputs.size() + ") must " +
                    "be the same as the number of results " +
                    "(" + results.size() + ")");
            }
        }
        return results;
    }

    /**
     * Normalize the given collection of {@link MutableDoubleTuple}s.

     *

     * The results will be written into the given result tuples.
     * If the given results list is null, then a new
     * list will be created and returned.

     *

     * If the result list is not null, then it must have the
     * same size as the input collection, otherwise an
     * IllegalArgumentException will be thrown.

     *

     * If the input collection contains null elements, then a
     * NullPointerException will be thrown.

     *

     * If the result list contains null elements, then a
     * NullPointerException will be thrown.

     *

     * The input collection and the results list may contain
     * pairwise identical elements.

     *

     * The input collection and the results list may be identical.
     *

     *
     * @param inputs The tuples to normalize
     * @param results The result tuples
     * @return The result tuples
     * @throws IllegalArgumentException If the result list is not
     * null and has a size that is different from the size
     * of the input collection
     * @throws NullPointerException If the inputs list is null
     * or contains null elements, or if the output list is
     * non-null and contains null elements
     * @see DoubleTuples#normalize(DoubleTuple, MutableDoubleTuple)
     */
    public static List<MutableDoubleTuple> normalize(
        Collection<? extends DoubleTuple> inputs,
        List<MutableDoubleTuple> results)
    {
        results = validate(inputs, results);
        int index = 0;
        for (DoubleTuple input : inputs)
        {
            MutableDoubleTuple result = results.get(index);
            DoubleTuples.normalize(input, result);
            index++;
        }
        return results;
    }

    /**
     * Computes the component-wise arithmetic mean of the given collection
     * of {@link DoubleTuple} objects.
     *
     * @param tuples The input tuples
     * @param result The result tuple
     * @return The result, or null if the given collection is empty
     * @throws IllegalArgumentException If the given result is not
     * null, and has a {@link Tuple#getSize() size}
     * that is different from that of the input tuples.
     */
    public static MutableDoubleTuple arithmeticMean(
        Collection<? extends DoubleTuple> tuples,
        MutableDoubleTuple result)
    {
        if (tuples.isEmpty())
        {
            return null;
        }
        result = add(tuples, result);
        return DoubleTuples.multiply(result, 1.0 / tuples.size(), result);
    }

    /**
     * Computes the component-wise variance of the given collection
     * of {@link DoubleTuple} objects. The method will compute
     * the arithmetic mean, and then compute the actual result
     * with the {@link #variance(Collection, DoubleTuple, MutableDoubleTuple)}
     * method.
     *
     * @param tuples The input tuples
     * @param result The result tuple
     * @return The result, or null if the given collection is empty
     * @throws IllegalArgumentException If the given result is not
     * null, and has a {@link Tuple#getSize() size}
     * that is different from that of the input tuples.
     */
    public static MutableDoubleTuple variance(
        Collection<? extends DoubleTuple> tuples,
        MutableDoubleTuple result)
    {
        if (tuples.isEmpty())
        {
            return null;
        }
        DoubleTuple mean = arithmeticMean(tuples, null);
        return variance(tuples, mean, result);
    }

    /**
     * Computes the component-wise variance of the given collection
     * of {@link DoubleTuple} objects.
     *
     * @param tuples The input tuples
     * @param mean The mean, which may have been computed before with
     * {@link #arithmeticMean}
     * @param result The result tuple
     * @return The result, or null if the given collection is empty
     * @throws IllegalArgumentException If the given result is not
     * null, and has a {@link Tuple#getSize() size}
     * that is different from that of the input tuples.
     */
    public static MutableDoubleTuple variance(
        Collection<? extends DoubleTuple> tuples, DoubleTuple mean,
        MutableDoubleTuple result)
    {
        if (tuples.isEmpty())
        {
            return null;
        }
        DoubleTuple first = tuples.iterator().next();
        result = DoubleTuples.validate(first, result);
        DoubleTuples.set(result, 0.0);
        int d = result.getSize();
        for (DoubleTuple tuple : tuples)
        {
            for (int i=0; i<d; i++)
            {
                double difference = tuple.get(i) - mean.get(i);
                double v = result.get(i);
                result.set(i, v + difference * difference);
            }
        }
        return DoubleTuples.multiply(result, 1.0 / tuples.size(), result);
    }

    /**
     * Returns the component-wise standard deviation of the given collection
     * of {@link DoubleTuple} objects. The method will compute
     * the arithmetic mean, and then compute the actual result
     * with the {@link #standardDeviationFromMean} method.
     *
     * @param tuples The input tuples
     * @param result The result tuple
     * @return The result, or null if the given collection is empty
     * @throws IllegalArgumentException If the given result is not
     * null, and has a {@link Tuple#getSize() size}
     * that is different from that of the input tuples.
     */
    public static MutableDoubleTuple standardDeviation(
        Collection<? extends DoubleTuple> tuples,
        MutableDoubleTuple result)
    {
        if (tuples.isEmpty())
        {
            return null;
        }
        DoubleTuple mean = arithmeticMean(tuples, null);
        return standardDeviationFromMean(tuples, mean, result);
    }

    /**
     * Returns the component-wise standard deviation of the given collection
     * of {@link DoubleTuple} objects.
     * The method will compute {@link #variance}, and then compute
     * the actual result with the
     * {@link DoubleTuples#standardDeviationFromVariance}
     * method.
     *
     * @param tuples The input tuples
     * @param mean The mean, which may have been computed before with
     * {@link #arithmeticMean}
     * @param result The result tuple
     * @return The result, or null if the given collection is empty
     * @throws IllegalArgumentException If the given result is not
     * null, and has a {@link Tuple#getSize() size}
     * that is different from that of the input tuples.
     */
    public static MutableDoubleTuple standardDeviationFromMean(
        Collection<? extends DoubleTuple> tuples, DoubleTuple mean,
        MutableDoubleTuple result)
    {
        if (tuples.isEmpty())
        {
            return null;
        }
        result = variance(tuples, mean, result);
        return DoubleTuples.standardDeviationFromVariance(result, result);
    }


text:
<?php

namespace Akeneo\Bundle\BatchBundle\Command;

use Akeneo\Bundle\BatchBundle\Job\DoctrineJobRepository;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class PurgeJobExecutionCommand extends ContainerAwareCommand
{
    const DEFAULT_NUMBER_OF_DAYS = 90;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('akeneo:batch:purge-job-execution');
        $this->setDescription('Purge jobs execution older than number of days you want, by default 90 days');
        $this->addOption(
            'days',
            'd',
            InputOption::VALUE_OPTIONAL,
            'How many days of jobs execution you want to keep'
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $days = $this->getNumberOfDaysOption($input);

        $jobsExecutions = $this->getJobExecutionRepository()->findPurgeables($days);

        if (!empty($jobsExecutions)) {
            //TODO TIP-385: re-wite this implementation to use 'akeneo_batch.remover.job_execution'
            $this->getJobExecutionRepository()->remove($jobsExecutions);
        }
    }

    /**
     * @param InputInterface $input
     *
     * @return int
     */
    protected function getNumberOfDaysOption(InputInterface $input)
    {
        if ($input->getOption('days') && (int) $input->getOption('days')) {
            return (int) $input->getOption('days');
        }

        return self::DEFAULT_NUMBER_OF_DAYS;
    }

    /**
     * @return DoctrineJobRepository
     */
    protected function getJobExecutionRepository()
    {
        return $this->getContainer()->get('akeneo_batch.job_repository');
    }
}


text:
package com.enioka.jqm.tools;

/**
 * Handler of POSIX-like TERM/INT signals: gracefully shut down.
 */
class SignalHandler extends Thread
{
    private JqmEngine e = null;

    SignalHandler(JqmEngine e)
    {
        this.e = e;
    }

    @Override
    public void run()
    {
        e.stop();
    }

}


text:
/*
This is an example application to demonstrate parsing an ID Token.
*/
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"

	"github.com/ericchiang/oidc"

	"golang.org/x/net/context"
	"golang.org/x/oauth2"
)

var (
	clientID     = os.Getenv("GOOGLE_OAUTH2_CLIENT_ID")
	clientSecret = os.Getenv("GOOGLE_OAUTH2_CLIENT_SECRET")
)

func main() {
	ctx := context.Background()

	provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
	if err != nil {
		log.Fatal(err)
	}
	verifier := provider.NewVerifier(ctx)

	config := oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		Endpoint:     provider.Endpoint(),
		RedirectURL:  "http://127.0.0.1:5556/auth/google/callback",
		Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
	}

	state := "foobar" // Don't do this in production.

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, config.AuthCodeURL(state), http.StatusFound)
	})

	http.HandleFunc("/auth/google/callback", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("state") != state {
			http.Error(w, "state did not match", http.StatusBadRequest)
			return
		}

		oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
		if err != nil {
			http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
			return
		}
		rawIDToken, ok := oauth2Token.Extra("id_token").(string)
		if !ok {
			http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
			return
		}
		idToken, err := verifier.Verify(rawIDToken)
		if err != nil {
			http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
			return
		}

		oauth2Token.AccessToken = "*REDACTED*"

		resp := struct {
			OAuth2Token   *oauth2.Token
			IDTokenClaims *json.RawMessage // ID Token payload is just JSON.
		}{oauth2Token, new(json.RawMessage)}

		if err := idToken.Claims(&resp.IDTokenClaims); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		data, err := json.MarshalIndent(resp, "", "    ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(data)
	})

	log.Printf("listening on http://%s/", "127.0.0.1:5556")
	log.Fatal(http.ListenAndServe("127.0.0.1:5556", nil))
}


text:
"""
Created on Thu Mar  2 14:48:24 2017

@author: thomas
"""
#from layers import Latent_Layer
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.append(os.path.abspath(os.path.dirname(__file__)))

import tensorflow as tf
import tensorflow.contrib.slim as slim
from tfutils.helpers import repeat_v2
from tfutils.distributions import logsumexp, DiagonalGaussian

class Network(object):
    ''' Generic VAE template '''

    def __init__(self,hps):

        # placeholders
        self.x = x = tf.placeholder("float32", shape=[None,1])
        self.y = y = tf.placeholder("float32", shape=[None,1])
        self.is_training = is_training = tf.placeholder("bool") # if True: sample from q, else sample from p
        self.k = k = tf.placeholder('int32') # number of importance samples
        self.temp = temp = tf.Variable(5.0,name='temperature',trainable=False) # Temperature for discrete latents
        self.lamb = lamb = tf.Variable(1.0,name="lambda",trainable=False) # Lambda for KL annealing

        # Importance sampling: repeats along second dimension
        x_rep = repeat_v2(x,k)
        y_rep = repeat_v2(y,k)

        if not hps.deterministic:
            # stochastic noise input to network
            z_dist = DiagonalGaussian(tf.zeros([tf.shape(x_rep)[0],hps.z_size]),tf.zeros([tf.shape(x_rep)[0],hps.z_size]))
            z = z_dist.sample
            logpz = tf.reduce_sum(z_dist.logps(z),axis=1)
            xz = tf.concat([z,x_rep],1)
        else:
            xz = x_rep
            logpz = 0.0
            hps.ignore_sigma_outcome = True

        # Decoder: x,z --> y
        dec1 = slim.fully_connected(xz,50,tf.nn.relu)
        dec2 = slim.fully_connected(dec1,50,tf.nn.relu)
        dec3 = slim.fully_connected(dec2,50,activation_fn=None)
        mu_y = slim.fully_connected(dec3,1,activation_fn=None)

        if hps.ignore_sigma_outcome:
            log_dec_noise = tf.zeros(tf.shape(mu_y))
        else:
            log_dec_noise = slim.fully_connected(dec3,1,activation_fn=None)

        kl_sum = tf.zeros(tf.shape(mu_y))
	   # p(y|x,z)
        dec_noise = tf.exp(tf.clip_by_value(log_dec_noise,-10,10))
        outdist = tf.contrib.distributions.Normal(mu_y,dec_noise)
        self.log_py_x = log_py_x = tf.reduce_sum(outdist.log_prob(y_rep),axis=1)
        self.nats = -1*tf.reduce_mean(logsumexp(tf.reshape(log_py_x + logpz,[-1,k])) - tf.log(tf.to_float(k)))

        if hps.ignore_sigma_outcome:
            self.y_sample = mu_y
        else:
            self.y_sample = outdist.sample()
        # To display
        self.kl = tf.reduce_mean(kl_sum)

        # ELBO
        log_divergence = tf.reshape(log_py_x + logpz,[-1,k]) # shape [batch_size,k]
        logF = logsumexp(log_divergence)
        self.elbo = elbo = tf.reduce_mean(logF - tf.log(tf.to_float(k)))
        self.loss = loss = -elbo

        ### Optimizer
        self.lr = lr = tf.Variable(0.001,name="learning_rate",trainable=False)
        global_step = tf.Variable(0,name='global_step',trainable=False)
        optimizer = tf.train.AdamOptimizer(learning_rate=lr)
        self.train_op = optimizer.minimize(loss,global_step=global_step)
        self.init_op=tf.global_variables_initializer()