text:
package com.cflint;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import com.cflint.plugins.core.ValidName;

public class TestValidNames {

    private ValidName name;

    @Before
    public void setUp() throws Exception {
        name = new ValidName(3, 20, 3);
    }

    @Test
    public void testInvalid() {
        assertFalse(name.isInvalid("camelCase","CamelCase"));
        assertFalse(name.isInvalid("product_id","CamelCase"));
        assertFalse(name.isInvalid("size","CamelCase"));
        assertFalse(name.isInvalid("lowercase","CamelCase"));
        assertFalse(name.isInvalid("UPPERCASE","CamelCase"));
        assertFalse(name.isInvalid("99_bottles_of_beer","CamelCase"));

        assertTrue(name.isInvalid("UppperCaseCamel","CamelCase"));
        assertFalse(name.isInvalid("endsInNumber99","CamelCase"));
    }

    @Test
    public void testValidChars() {
        assertTrue(name.validChars("camelCase"));
        assertTrue(name.validChars("product_id"));
        assertTrue(name.validChars("99_bottles_of_beer"));

        assertFalse(name.validChars("no$items"));
        assertFalse(name.validChars("no-items"));
        assertFalse(name.validChars("no+items"));
    }

    @Test
    public void testIsCamelCaseLower() {
        assertTrue(name.isCamelCase("product"));
        assertTrue(name.isCamelCase("camelCase"));
        assertTrue(name.isCamelCase("product4G"));
        assertTrue(name.isCamelCase("productID"));
        assertTrue(name.isCamelCase("requestViaHTTPS"));
        assertTrue(name.isCamelCase("myURLRequest"));

        assertFalse(name.isCamelCase("product_id"));
        assertFalse(name.isCamelCase("UpperCase"));
        assertFalse(name.isCamelCase("Uppercase"));
        assertFalse(name.isCamelCase("ProductID"));
        assertFalse(name.isCamelCase("PRODUCTID"));
    }

    @Test
    public void testIsCamelCaseUpper() {
        assertTrue(name.isPascalCase("Product"));
        assertTrue(name.isPascalCase("PamelCase"));
        assertTrue(name.isPascalCase("Product4G"));
        assertTrue(name.isPascalCase("ProductID"));
        assertTrue(name.isPascalCase("RequestViaHTTPS"));
        assertTrue(name.isPascalCase("MyURLRequest"));

        assertFalse(name.isPascalCase("product"));
        assertFalse(name.isPascalCase("Product_id"));
        assertFalse(name.isPascalCase("Product_Id"));
        assertFalse(name.isPascalCase("PRODUCTID"));
    }

    @Test
    public void testUsesUnderscores() {
        assertTrue(name.usesUnderscores("product_name"));
        assertTrue(name.usesUnderscores("_atstart"));
        assertTrue(name.usesUnderscores("atend_"));
        assertTrue(name.usesUnderscores("lots_of_under_scores"));

        assertFalse(name.usesUnderscores("productName"));
        assertFalse(name.usesUnderscores("productname"));
    }

    @Test
    public void testEndsInNumber() {
        assertTrue(name.endsInNumber("endsInNumber99"));
        assertTrue(name.endsInNumber("temp2"));

        assertFalse(name.endsInNumber("productName"));
        assertFalse(name.endsInNumber("phone4G"));
        assertFalse(name.endsInNumber("99beers"));
    }

    @Test
    public void testTooShort() {
        assertTrue(name.tooShort("a"));
        assertTrue(name.tooShort("to"));

        assertFalse(name.tooShort("the"));
        assertFalse(name.tooShort("chars"));
        assertFalse(name.tooShort("averylongname"));
    }

    @Test
    public void testTooLong() {
        assertTrue(name.tooLong("123456789012345678901"));
        assertTrue(name.tooLong("aVeryLongNameThatIsTooLong"));

        assertFalse(name.tooLong("shortName"));
        assertFalse(name.tooLong("short_name"));
        assertFalse(name.tooLong("12345678901234567890"));
    }

    @Test
    public void testTooWordy() {
        assertTrue(name.tooWordy("thisIsAVeryWordyName"));
        assertTrue(name.tooWordy("alsoFarTooWordy"));

        assertFalse(name.tooWordy("ProductName"));
        assertFalse(name.tooWordy("aSimpleName"));
        assertFalse(name.tooWordy("simple"));
    }

    @Test
    public void testIsTemporary() {
        assertTrue(name.isTemporary("temp"));
        assertTrue(name.isTemporary("tmp"));
        assertTrue(name.isTemporary("myVar"));
        assertTrue(name.isTemporary("aFunc"));
        assertTrue(name.isTemporary("nameObj"));
        assertTrue(name.isTemporary("name_obj"));
        assertTrue(name.isTemporary("tmp_array"));

        assertFalse(name.isTemporary("temperature"));
        assertFalse(name.isTemporary("productName"));
        assertFalse(name.isTemporary("first_name"));
    }

    @Test
    public void testHasPrefixOrPostfix() {
        assertTrue(name.hasPrefixOrPostfix("stName"));
        assertTrue(name.hasPrefixOrPostfix("oPerson"));
        assertTrue(name.hasPrefixOrPostfix("qGet"));
        assertTrue(name.hasPrefixOrPostfix("nameStr"));
        assertTrue(name.hasPrefixOrPostfix("bValid"));

        assertFalse(name.isTemporary("temperature"));
        assertFalse(name.isTemporary("strength"));
        assertFalse(name.isTemporary("argument"));
        assertFalse(name.isTemporary("first_name"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.bitdecay.game.camera;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.bitdecay.game.util.RectangleExt;

import java.util.ArrayList;
import java.util.List;

/**
 * The FollowOrthoCamera will try and follow a list of points.  As the points spread out, the camera will zoom out.  As they get closer together, the camera will zoom in.  You have to give the camera a new list of points to follow every update step.
 */
public class FollowOrthoCamera extends OrthographicCamera {
    public float maxZoom = 0.05f;
    public float minZoom = 0.1f;
    public float buffer = 10;
    public float snapSpeed = 0.05f;
    public boolean limitWindow = false;
    public float limitWindowMinX = 0;
    public float limitWindowMinY = 0;
    public float limitWindowMaxX = 0;
    public float limitWindowMaxY = 0;

    private List<Vector2> pointsToFollow = new ArrayList<>();

    private float targetZoom = 0.1f;
    private Vector2 targetPosition = new Vector2(0, 0);

    private RectangleExt window;
    private float originalWidth = 0;
    private float widthRatio = 0;
    private float heightRatio = 0;

    private float minX = 0;
    private float minY = 0;
    private float maxX = 0;
    private float maxY = 0;
    private float midX = 0;
    private float midY = 0;
    private float maxW = 0;
    private float maxH = 0;

    private boolean shake = false;
    private float shakeStrength = 0;
    private float shakeDuration = 0;

    public FollowOrthoCamera(float width, float height){
        super(width, height);
        originalWidth = width;
        widthRatio = height / width;
        heightRatio = width / height;
        window = new RectangleExt(0, 0, width, height);
    }

    public void addFollowPoint(Vector2 point){
        pointsToFollow.add(point);
    }

    @Override
    public void update(){
        update(1f / 60f);
    }

    public void update(float delta){
        super.update();
        if (pointsToFollow != null && pointsToFollow.size() > 0) {
            getWorldMaxWindow();

            window.x = midX;
            window.y = midY;
            targetPosition.x = window.x;
            targetPosition.y = window.y;
            // try max width first
            window.width = maxW;
            window.height = maxW * widthRatio;
            window.setOriginAtCenter();
            if (!testAllPoints()) {
                // then try max height
                window.height = maxH;
                window.width = maxH * heightRatio;
                window.setOriginAtCenter();
            }
            targetZoom = window.width / originalWidth;
            //
            goToTargets();
            pointsToFollow = new ArrayList<>();
        }
        if (shake){
            translate(MathUtils.random(-shakeStrength, shakeStrength), MathUtils.random(-shakeStrength, shakeStrength));

            shakeDuration -= delta;
            if (shakeDuration <= 0){
                shake = false;
            }
        }
    }

    public void shake(float duration){
        this.shake = true;
        this.shakeStrength = 5;
        this.shakeDuration = duration;
    }

    public void shake(float duration, float strength){
        this.shake = true;
        this.shakeStrength = strength;
        this.shakeDuration = duration;
    }

    public void rumble(){
        this.shake = true;
        this.shakeStrength = 1;
        this.shakeDuration = 0.0001f;
    }

    private boolean testAllPoints(){
        for (Vector2 point : pointsToFollow){
            if (!window.contains(point)){
                return false;
            }
        }
        return true;
    }

    private void goToTargets(){
        float transX = (targetPosition.x - position.x) * snapSpeed;
        float transY = (targetPosition.y - position.y) * snapSpeed;
        translate(transX, transY);
        float transZoom = ((targetZoom < maxZoom ? maxZoom : (targetZoom > minZoom ? minZoom : targetZoom)) - zoom) * snapSpeed;
        zoom += transZoom;
    }

    private void getWorldMaxWindow(){
        minX = 0;
        minY = 0;
        maxX = 0;
        maxY = 0;
        maxW = 0;
        maxH = 0;
        midX = 0;
        midY = 0;
        if (pointsToFollow.size() > 0){
            Vector2 firstPoint = pointsToFollow.get(0);
            minX = firstPoint.x;
            minY = firstPoint.y;
            maxX = minX;
            maxY = minY;
        }

        for (Vector2 point : pointsToFollow){
            if (point.x < minX){
                minX = point.x;
            }
            if (point.x > maxX){
                maxX = point.x;
            }
            if (point.y < minY){
                minY = point.y;
            }
            if (point.y > maxY){
                maxY = point.y;
            }
        }

        if (limitWindow){
            minX = (minX < limitWindowMinX ? limitWindowMinX : (minX > limitWindowMaxX ? limitWindowMaxX : minX));
            maxX = (maxX > limitWindowMaxX ? limitWindowMaxX : (maxX < limitWindowMinX ? limitWindowMinX : maxX));

            minY = (minY < limitWindowMinY ? limitWindowMinY : (minY > limitWindowMaxY ? limitWindowMaxY : minY));
            maxY = (maxY > limitWindowMaxY ? limitWindowMaxY : (maxY < limitWindowMinY ? limitWindowMinY : maxY));

        }

        maxW = (maxX - minX) + (buffer * 2);
        maxH = (maxY - minY) + (buffer * 2);
        midX = maxW / 2f + (minX - buffer);
        midY = maxH / 2f + (minY - buffer);
    }
}


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

module AMQ
  module Protocol
    class Connection
      describe Start do
        describe '.decode' do
          subject do
            Start.decode("\x00\t\x00\x00\x00\xFB\tcopyrightS\x00\x00\x00gCopyright (C) 2007-2010 LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.\vinformationS\x00\x00\x005Licensed under the MPL.  See http://www.rabbitmq.com/\bplatformS\x00\x00\x00\nErlang/OTP\aproductS\x00\x00\x00\bRabbitMQ\aversionS\x00\x00\x00\x052.2.0\x00\x00\x00\x0EPLAIN AMQPLAIN\x00\x00\x00\x05en_US")
          end

          its(:version_major) { should == 0 }
          its(:version_minor) { should == 9 }
          its(:server_properties) { should == {'copyright' => 'Copyright (C) 2007-2010 LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.', 'information' => 'Licensed under the MPL.  See http://www.rabbitmq.com/', 'platform' => 'Erlang/OTP', 'product' => 'RabbitMQ', 'version' => '2.2.0'} }
          its(:mechanisms) { should == 'PLAIN AMQPLAIN' }
          its(:locales) { should == 'en_US' }
        end
      end

      describe StartOk do
        describe '.encode' do
          it 'encodes the parameters into a MethodFrame' do
            client_properties = {:platform => 'Ruby 1.9.2', :product => 'AMQ Client', :information => 'http://github.com/ruby-amqp/amq-client', :version => '0.2.0'}
            mechanism = 'PLAIN'
            response = "\x00guest\x00guest"
            locale = 'en_GB'
            method_frame = StartOk.encode(client_properties, mechanism, response, locale)
            # the order of the table parts isn't deterministic in Ruby 1.8
            method_frame.payload[0, 8].should == "\x00\n\x00\v\x00\x00\x00x"
            method_frame.payload.should include("\bplatformS\x00\x00\x00\nRuby 1.9.2")
            method_frame.payload.should include("\aproductS\x00\x00\x00\nAMQ Client")
            method_frame.payload.should include("\vinformationS\x00\x00\x00&http://github.com/ruby-amqp/amq-client")
            method_frame.payload.should include("\aversionS\x00\x00\x00\x050.2.0")
            method_frame.payload[-28, 28].should == "\x05PLAIN\x00\x00\x00\f\x00guest\x00guest\x05en_GB"
            method_frame.payload.length.should == 156
          end
        end
      end

      describe Secure do
        describe '.decode' do
          subject do
            Secure.decode("\x00\x00\x00\x03foo")
          end

          its(:challenge) { should == 'foo' }
        end
      end

      describe SecureOk do
        describe '.encode' do
          it 'encodes the parameters as a MethodFrame' do
            response = 'bar'
            method_frame = SecureOk.encode(response)
            method_frame.payload.should == "\x00\x0a\x00\x15\x00\x00\x00\x03bar"
          end
        end
      end

      describe Tune do
        describe '.decode' do
          subject do
            Tune.decode("\x00\x00\x00\x02\x00\x00\x00\x00")
          end

          its(:channel_max) { should == 0 }
          its(:frame_max) { should == 131072 }
          its(:heartbeat) { should == 0}
        end
      end

      describe TuneOk do
        describe '.encode' do
          it 'encodes the parameters into a MethodFrame' do
            channel_max = 0
            frame_max = 65536
            heartbeat = 1
            method_frame = TuneOk.encode(channel_max, frame_max, heartbeat)
            method_frame.payload.should == "\x00\n\x00\x1F\x00\x00\x00\x01\x00\x00\x00\x01"
          end
        end
      end

      describe Open do
        describe '.encode' do
          it 'encodes the parameters into a MethodFrame' do
            vhost = '/test'
            method_frame = Open.encode(vhost)
            method_frame.payload.should == "\x00\n\x00(\x05/test\x00\x00"
          end
        end
      end

      describe OpenOk do
        describe '.decode' do
          subject do
            OpenOk.decode("\x00")
          end

          its(:known_hosts) { should == '' }
        end
      end

      describe Close do
        describe '.decode' do
          context 'with code 200' do
            subject do
              Close.decode("\x00\xc8\x07KTHXBAI\x00\x05\x00\x06")
            end

            its(:reply_code) { should == 200 }
            its(:reply_text) { should == 'KTHXBAI' }
            its(:class_id) { should == 5 }
            its(:method_id) { should == 6 }
          end

          context 'with an error code' do
            it 'returns method frame and lets calling code handle the issue' do
              Close.decode("\x01\x38\x08NO_ROUTE\x00\x00")
            end
          end
        end

        describe '.encode' do
          it 'encodes the parameters into a MethodFrame' do
            reply_code = 540
            reply_text = 'NOT_IMPLEMENTED'
            class_id = 0
            method_id = 0
            method_frame = Close.encode(reply_code, reply_text, class_id, method_id)
            method_frame.payload.should == "\x00\x0a\x002\x02\x1c\x0fNOT_IMPLEMENTED\x00\x00\x00\x00"
          end
        end
      end

      describe CloseOk do
        describe '.encode' do
          it 'encodes a MethodFrame' do
            method_frame = CloseOk.encode
            method_frame.payload.should == "\x00\n\x003"
          end
        end
      end
    end
  end
end


text:
using System;

namespace SharpDX.Direct3D10
{
    public partial struct SpriteInstance
    {
        /// <summary>
        /// Gets or sets the texture.
        /// </summary>
        /// <value>The texture.</value>
        public ShaderResourceView Texture
        {
            get
            {
                return new ShaderResourceView(ShaderResourceViewPointer);
            }
            set
            {
                ShaderResourceViewPointer = value.NativePointer;
            }
        }
    }
}
#endif


text:
/*global describe, it, before */
var testUtils = require('./helper/test-utils'),
    assert = testUtils.assert;

var _      = require('underscore'),
    authorize = require('./helper/webauth'),
    OAuth2 = require('../lib/oauth2'),
    config = require('./config/oauth2');

/**
 *
 */
describe("oauth2", function() {

  this.timeout(40000); // set timeout to 40 sec.

  var oauth2 = new OAuth2(config);

/*------------------------------------------------------------------------*/
if (testUtils.isNodeJS) {
  /**
   *
   */
  describe("OAuth2 web server flow", function() {
    var code, accessToken, refreshToken;

    it("should receive authz code", function(done) {
      var url = oauth2.getAuthorizationUrl({ state: 'hello' });
      authorize(url, config.username, config.password, function(err, params) {
        if (err) { throw err; }
        assert.ok(_.isString(params.code));
        assert.ok(params.state === 'hello');
        code = params.code;
      }.check(done));
    });

    it("should receive access/refresh token", function(done) {
      oauth2.requestToken(code, function(err, res) {
        if (err) { throw err; }
        assert.ok(_.isString(res.access_token));
        assert.ok(_.isString(res.refresh_token));
        accessToken = res.access_token;
        refreshToken = res.refresh_token;
      }.check(done));
    });

    it("should refresh access token", function(done) {
      oauth2.refreshToken(refreshToken, function(err, res) {
        if (err) { throw err; }
        assert.ok(_.isString(res.access_token));
      }.check(done));
    });

  });

  /**
   *
   */
  describe("OAuth2 username & password flow : authenticate", function() {
    it("should receive access token", function(done) {
      oauth2.authenticate(config.username, config.password, function(err, res) {
        if (err) { throw err; }
        assert.ok(_.isString(res.access_token));
      }.check(done));
    });
  });

}
/*------------------------------------------------------------------------*/

});


text:
# Coding rules

This file shows the coding rules of the project

## Indentation

* Tab, length 4, no spaces
* the maximum line length is 80 columns
* do not mix tab and spaces
* For multi-line commands (e.g. commands that goes over 80 columns, use double indentation)
```C
x = super_mega_long_function_with_a_lot_of_params(int a,
		int b, int c, int d, int e, int f, int g, int as,
		int z);
```
## Functions/Methods

* On declaration return type and method modifiers shall be on the same line
```C
static int FooClass::my_method(int a, int b);
```
* On implementation return type and method modifiers shall be on a single line
```C
static int
FooClass::my_method(int a, int)
{
	/* code here */
}
```
* Curly brackets (opening and closing shall be on a separate line
* Return values shall be around round brackets
```C
static int
FooClass::my_method(int a,int b)
{
	return (1);
}
```
* Use empty lines to create logical separations between actions into methods
```C
static int
FooClass::my_other_method(int c)
{
	/* Variable declarations*/

	/* core of the method */

	/* return types or error/failure paths*/
}
```
* Use lowercase letters for methods and CamelCase for Classes
## Control flow

* Put a space before the parentheses in `if`, `switch`, `for` and `while`
* Open curly brackets on the same line of loops and `if`
* Put a space before and after binary operators

```C
if (a == b) {
	/*do somehting*/
} else {
	/*do somehting else */
}

for (int i=0, i < 1000, i++) {
	/* do the same for 1000 times */
}

switch (a) {
	case A:
		/*A*/
		break;
	case B:
		/*B*/
		break;
}
```

## Doxygen

* Doxygen shall be only on .h file

* The file should have this header (Please note that copyright date should be updated regularly)
```C
//
// Copyright (c) 2017 Regents of the SIGNET lab, University of Padova.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University of Padova (SIGNET lab) nor the
//    names of its contributors may be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
 * @file   uwpolling_NODE.h
 * @author Federico Favaro
 * @version 1.0.0
 *
 * \brief Class that represents a node of UWPOLLING
 *
 *
 */
```
* Method definition should have this doxygen
```
    /**
     * TCL command interpreter. It implements the following OTcl methods:
     *
     * @param argc Number of arguments in <i>argv</i>.
     * @param argv Array of strings which are the command parameters (Note that <i>argv[0]</i> is the name of the object).
     * @return TCL_OK or TCL_ERROR whether the command has been dispatched successfully or not.
     *
     **/
	 virtual int command(int argc, const char*const* argv);
```
* Variables should have this doxygen
```C
Packet* curr_data_pkt; /**< Pointer to the current DATA packet */
```


text:
using Robust.Client.GameObjects;

using static Content.Shared.Paper.SharedPaperComponent;

namespace Content.Client.Paper;

public sealed class PaperSystem : VisualizerSystem<PaperVisualsComponent>
{
    protected override void OnAppearanceChange(EntityUid uid, PaperVisualsComponent component, ref AppearanceChangeEvent args)
    {
        if (args.Sprite == null)
            return;

        if (args.Component.TryGetData(PaperVisuals.Status , out PaperStatus writingStatus))
            args.Sprite.LayerSetVisible(PaperVisualLayers.Writing, writingStatus == PaperStatus.Written);

        if (args.Component.TryGetData(PaperVisuals.Stamp, out string stampState))
        {
            args.Sprite.LayerSetState(PaperVisualLayers.Stamp, stampState);
            args.Sprite.LayerSetVisible(PaperVisualLayers.Stamp, true);
        }
    }
}

public enum PaperVisualLayers
{
    Stamp,
    Writing
}


text:
<?php

namespace Btn\AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Doctrine\ORM\EntityRepository;
use Btn\AppBundle\Util\Form;

class TimeFilterType extends AbstractType
{

    protected $filters = array(
                'user'     => 'u.username',
                'project'  => 't.project',
                'timeFrom' => 't.createdAt',
                'timeTo'   => 't.createdAt',
              );

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('user', 'entity', array(
                'label' => 'User',
                'class' => 'Btn\UserBundle\Entity\User',
                'empty_value' => 'All users',
                'required' => false,
            ))
            ->add('project', 'entity', array(
                'label' => 'Project',
                'class' => 'Btn\AppBundle\Entity\Project',
                'empty_value' => 'All projects',
                'required' => false,
            ))
            //filter time from
            ->add('timeFrom', 'text', array(
                'label' => 'Time from',
                'required' => false,
                'attr' => array('class' => 'input-small')
            ))
            //filter time to
            ->add('timeTo', 'text', array(
                'label' => 'Time to',
                'required' => false,
                'attr' => array('class' => 'input-small')
            ))
        ;
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'csrf_protection' => false
        );
    }

    public function getName()
    {
        return 'filter';
    }

    public function getProject($project, $expr)
    {
        return $expr->eq('p.name', $expr->literal($project));
    }

    public function getTimeFrom($timeFrom, $expr)
    {
        $from = new \DateTime($timeFrom);
        return $expr->gte('t.createdAt', $expr->literal($from->format('Y-m-d H:i:s')));
    }

    public function getTimeTo($timeTo, $expr)
    {
        $to = new \DateTime($timeTo);
        return $expr->lte('t.createdAt', $expr->literal($to->format('Y-m-d H:i:s')));
    }

    public function getUser($user, $expr)
    {
        return $expr->eq('u.username', $expr->literal($user));
    }

    public function getExpr($binded_data, $expr)
    {
        return Form::getExpr($binded_data, $expr, $this->filters, $this);
    }

}


text:
"""Tests for the views of the ``aps_purchasing`` app."""
import os

from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils.timezone import now

from django_libs.tests.mixins import ViewRequestFactoryTestMixin
from django_libs.tests.factories import UserFactory
from aps_bom.tests.factories import BOMFactory

from ..factories import (
    CurrencyFactory,
    DistributorFactory,
    ManufacturerFactory,
    PriceFactory,
)
from ...models import Quotation, QuotationItem, Price
from ... import views

class QuotationUploadViewTestCase(ViewRequestFactoryTestMixin, TestCase):
    """Tests for the ``QuotationUploadView`` view class."""
    longMessage = True
    view_class = views.QuotationUploadView

    def get_view_name(self):
        return 'aps_purchasing_quotation_upload'

    def setUp(self):
        self.user = UserFactory()
        self.distributor = DistributorFactory()
        ManufacturerFactory(name='Samsung')
        ManufacturerFactory(name='TDK')
        self.usd = CurrencyFactory(iso_code='USD')

        self.quotation_file = open(os.path.join(
            settings.APP_ROOT, 'tests/files/Quotation.csv'))

        self.data = {
            'distributor': self.distributor.pk,
            'ref_number': 'REF123',
            'issuance_date': now(),
            'expiry_date': now(),
            'is_completed': True,
            'quotation_file': SimpleUploadedFile('Quotation.csv',
                                                 self.quotation_file.read()),
        }

    def test_view(self):
        self.should_redirect_to_login_when_anonymous()

        self.is_callable(user=self.user)

        self.is_postable(user=self.user, data=self.data, to=self.get_url())

        self.assertEqual(Quotation.objects.count(), 1, msg=(
            'After a post with valid data, there should be one Quotation in'
            ' the database.'))
        self.assertEqual(QuotationItem.objects.count(), 2, msg=(
            'After a post with valid data, there should be four QuotationItems'
            ' in the database.'))
        self.assertEqual(Price.objects.count(), 4, msg=(
            'After a post with valid data, there should be three Prices in'
            ' the database.'))

        self.quotation_file.seek(0)
        self.data['quotation_file'] = SimpleUploadedFile(
            'Quotation.csv', self.quotation_file.read())
        self.is_postable(user=self.user, data=self.data, to=self.get_url())
        self.assertEqual(Quotation.objects.count(), 1, msg=(
            'After posting again, there should stil be one Quotation in the'
            ' database.'))
        self.assertEqual(QuotationItem.objects.count(), 2, msg=(
            'After posting again, there should still be four QuotationItems'
            ' in the database.'))
        self.assertEqual(Price.objects.count(), 4, msg=(
            'After posting again, there should still be three Prices in'
            ' the database.'))

class ReportViewTestCase(ViewRequestFactoryTestMixin, TestCase):
    """Tests for the ``ReportView`` view class."""
    longMessage = True
    view_class = views.ReportView

    def get_view_name(self):
        return 'aps_purchasing_report'

    def get_view_kwargs(self):
        return {'pk': self.bom.pk}

    def setUp(self):
        self.user = UserFactory()
        self.bom = BOMFactory()
        self.price = PriceFactory()
        self.item = self.price.quotation_item
        self.quotation = self.item.quotation

    def test_view(self):
        self.is_callable(user=self.user)
        self.is_callable(user=self.user, kwargs={})
        self.redirects(user=self.user, kwargs={}, data={
            'part_number': self.bom.ipn.code}, to=self.get_url())
        self.is_callable(user=self.user, kwargs={}, data={
            'part_number': 'wrongcode'})


text:
__drv_functionClass(EVT_SYSTEMWORKITEM)
__drv_maxIRQL(PASSIVE_LEVEL)
__drv_maxFunctionIRQL(DISPATCH_LEVEL)
__drv_sameIRQL
typedef
VOID
EVT_SYSTEMWORKITEM(
    __in PVOID Parameter
    );

typedef EVT_SYSTEMWORKITEM *PFN_WDF_SYSTEMWORKITEM;

// </FxSystemWorkItem.hpp>

#include "FxCallbackSpinlock.hpp"
#include "FxCallbackMutexLock.hpp"
#include "FxPackage.hpp"
#include "IfxMemory.hpp"
#include "FxCallback.hpp"
#include "FxRequestContext.hpp"
#include "FxRequestContextTypes.h"
#include "FxRequestBase.hpp"
#include "FxRequest.hpp"
#include "FxPkgPnp.hpp"
#include "FxPkgIo.hpp"
#include "FxIoQueue.hpp"

#include "FxDmaEnabler.hpp"
#include "FxSystemWorkItem.hpp"

#include "FxDsf.h"    // DSF support.
#include <device_common.h>
#include "FxTelemetry.hpp"

_Must_inspect_result_
NTSTATUS
SendDeviceUsageNotificationWorker(
    __in MxDeviceObject* RelatedDevice,
    __inout FxIrp* RelatedIrp,
    __in FxIrp* OriginalIrp,
    __in BOOLEAN Revert
    );

IO_WORKITEM_ROUTINE
_DeviceUsageNotificationWorkItem;

struct FxUsageWorkitemParameters {

    FxUsageWorkitemParameters(
        VOID
        )
    {
        RelatedDevice = NULL;
        RelatedIrp = NULL;
        OriginalIrp = NULL;
        Status = STATUS_UNSUCCESSFUL;
    }

    _In_ MxDeviceObject* RelatedDevice;

    _In_ FxIrp* RelatedIrp;

    _In_ FxIrp* OriginalIrp;

    _In_ BOOLEAN Revert;

    _In_ FxCREvent Event;

    _Out_ NTSTATUS Status;
};

#endif // _PNPPRIVKM_H_


text:
title: Internal Templates
linktitle: Internal Templates
description: Hugo ships with a group of boilerplate templates that cover the most common use cases for static websites.
date: 2017-03-06
publishdate: 2017-03-06
lastmod: 2017-03-06
categories: [templates]
keywords: [internal, analytics,]
menu:
  docs:
    parent: "templates"
    weight: 168
weight: 168
sections_weight: 168
draft: false
aliases: []
toc: true
wip: true
---

{{% warning %}}
While the following internal templates are called similar to partials, they do *not* observe the partial template lookup order.
{{% /warning %}}

## Google Analytics

Hugo ships with internal templates supporting Google Analytics, both [Google Analytics 4][GA4] (GA4) and Universal Analytics.

**Note:** Universal Analytics are deprecated. For details, see [Universal Analytics will be going away][].

[GA4]: https://support.google.com/analytics/answer/10089681
[Universal Analytics will be going away]: https://support.google.com/analytics/answer/11583528

### Configure Google Analytics

Provide your tracking ID in your configuration file:

**Google Analytics 4 (gtag.js)**
{{}}
googleAnalytics = "G-MEASUREMENT_ID"
{{}}

**Google Universal Analytics (analytics.js)**
{{}}
googleAnalytics = "UA-PROPERTY_ID"
{{}}

### Use the Google Analytics Template

You can then include the Google Analytics internal template:

```go-html-template
{{ template "_internal/google_analytics_async.html" . }}
```

**Note:** The async template is _not_ suitable for Google Analytics 4.

```go-html-template
{{ template "_internal/google_analytics.html" . }}
```

If you want to create your own template, you can access the configured ID with `{{ site.Config.Services.GoogleAnalytics.ID }}`.

## Disqus

Hugo also ships with an internal template for [Disqus comments][disqus], a popular commenting system for both static and dynamic websites. In order to effectively use Disqus, you will need to secure a Disqus "shortname" by [signing up for the free service][disqussignup].

### Configure Disqus

To use Hugo's Disqus template, you first need to set a single configuration value:

{{}}
disqusShortname = "your-disqus-shortname"
{{}}

You also have the option to set the following in the front matter for a given piece of content:

* `disqus_identifier`
* `disqus_title`
* `disqus_url`

### Use the Disqus Template

To add Disqus, include the following line in templates where you want your comments to appear:

```go-html-template
{{ template "_internal/disqus.html" . }}
```

A `.Site.DisqusShortname` variable is also exposed from the config.

### Conditional Loading of Disqus Comments

Users have noticed that enabling Disqus comments when running the Hugo web server on `localhost` (i.e. via `hugo server`) causes the creation of unwanted discussions on the associated Disqus account.

You can create the following `layouts/partials/disqus.html`:

{{}}

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus
{{}}

The `if` statement skips the initialization of the Disqus comment injection when you are running on `localhost`.

You can then render your custom Disqus partial template as follows:

```go-html-template
{{ partial "disqus.html" . }}
```

## Open Graph

An internal template for the [Open Graph protocol](https://ogp.me/), metadata that enables a page to become a rich object in a social graph.
This format is used for Facebook and some other sites.

### Configure Open Graph

Hugo's Open Graph template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.

{{}}
[params]
  title = "My cool site"
  images = ["site-feature-image.jpg"]
  description = "Text about my cool site"
[taxonomies]
  series = "series"
{{}}

{{}}
title = "Post title"
description = "Text about this post"
date = "2006-01-02"
images = ["post-cover.png"]
audio = []
videos = []
series = []
tags = []
{{}}

Hugo uses the page title and description for the title and description metadata.
The first 6 URLs from the `images` array are used for image metadata.
If [page bundles](/content-management/page-bundles/) are used and the `images` array is empty or undefined, images with filenames matching `*feature*` or `*cover*,*thumbnail*` are used for image metadata.

Various optional metadata can also be set:

- Date, published date, and last modified data are used to set the published time metadata if specified.
- `audio` and `videos` are URL arrays like `images` for the audio and video metadata tags, respectively.
- The first 6 `tags` on the page are used for the tags metadata.
- The `series` taxonomy is used to specify related "see also" pages by placing them in the same series.

If using YouTube this will produce a og:video tag like `<meta property="og:video" content="url">`. Use the `https://youtu.be/<id>` format with YouTube videos (example: `https://youtu.be/qtIqKaDlqXo`).

### Use the Open Graph Template

To add Open Graph metadata, include the following line between the `<head>` tags in your templates:

```go-html-template
{{ template "_internal/opengraph.html" . }}
```

## Twitter Cards

An internal template for [Twitter Cards](https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards),
metadata used to attach rich media to Tweets linking to your site.

### Configure Twitter Cards

Hugo's Twitter Card template is configured using a mix of configuration variables and [front-matter](/content-management/front-matter/) on individual pages.

{{}}
[params]
  images = ["site-feature-image.jpg"]
  description = "Text about my cool site"
{{}}

{{}}
title = "Post title"
description = "Text about this post"
images = ["post-cover.png"]
{{}}

If `images` aren't specified in the page front-matter, then hugo searches for [image page resources](/content-management/image-processing/) with `feature`, `cover`, or `thumbnail` in their name.
If no image resources with those names are found, the images defined in the [site config](/getting-started/configuration/) are used instead.
If no images are found at all, then an image-less Twitter `summary` card is used instead of `summary_large_image`.

Hugo uses the page title and description for the card's title and description fields. The page summary is used if no description is given.

The `.Site.Social.twitter` variable is exposed from the config as the value for `twitter:site`.

{{}}
[social]
  twitter = "GoHugoIO"
{{}}

NOTE: The `@` will be added for you

```html
<meta name="twitter:site" content="@GoHugoIO"/>
```

### Use the Twitter Cards Template

To add Twitter card metadata, include the following line immediately after the `<head>` element in your templates:

```go-html-template
{{ template "_internal/twitter_cards.html" . }}
```

## The Internal Templates

The code for these templates is located [here](https://github.com/gohugoio/hugo/tree/master/tpl/tplimpl/embedded/templates).

* `_internal/disqus.html`
* `_internal/google_analytics.html`
* `_internal/google_analytics_async.html`
* `_internal/opengraph.html`
* `_internal/pagination.html`
* `_internal/schema.html`
* `_internal/twitter_cards.html`

[disqus]: https://disqus.com
[disqussignup]: https://disqus.com/profile/signup/


text:
<?php

namespace App\Classes;

/**
 * Classes UtilityClass
 * @package App\Classes
 */
class UtilityClass
{

}


text:
Orientate
=========

.NET bindings to OrientDB

Starting Point:
http://netorientdb.codeplex.com/


text:
package utils

import (
	"os"
	"reflect"
	"runtime"
	"strconv"
	"time"
)

// GetUserHomeDir - Get User Home Dir
func GetUserHomeDir() string {
	if runtime.GOOS == "windows" {
		home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
		if home == "" {
			home = os.Getenv("USERPROFILE")
		}
		return home
	}
	return os.Getenv("HOME")
}

// InTimeSpan - Checks if date is in time interval
func InTimeSpan(start, end, check time.Time) bool {
	return check.After(start) && check.Before(end)
}

// InvokeMethodByName - Invokes Method By Name
func InvokeMethodByName(any interface{}, name string, args ...interface{}) []reflect.Value {
	inputs := make([]reflect.Value, len(args))
	for i := range args {
		inputs[i] = reflect.ValueOf(args[i])
	}

	return reflect.ValueOf(any).MethodByName(name).Call(inputs)
}

// String2int - String to int
func String2int(sval string) int {
	val, err := strconv.Atoi(sval)

	if err != nil {
		return 0
	}

	return val
}

// ContainsRepeatingGroups - Contains Repeating Groups
func ContainsRepeatingGroups(str string) bool {
	groupSize := 2
	length := len(str) - 1

	for i := groupSize; i < length; i++ {
		if testRepeatingGroups(str, length, i) {
			return true
		}
	}

	return false
}

func testRepeatingGroups(str string, length int, groupSize int) bool {
	for i := 0; i < length; i = i + groupSize {
		for j := i + groupSize; j < length-groupSize; j = j + groupSize {
			if str[i:i+groupSize] == str[j:j+groupSize] {
				return true
			}
		}
	}

	return false
}

func stringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

// GetMinGreaterThanZero - gets the first of two numbers
func GetMinGreaterThanZero(a, b int) int {
	if a > 0 && b > 0 {
		if a <= b {
			return a
		}
		return b
	} else if a > 0 {
		return a
	} else if b > 0 {
		return b
	}

	return -1
}

// IsWhiteSpace checks if string is space, tab or enter
func IsWhiteSpace(s string) bool {
	if s == " " || s == "\t" || s == "\r" || s == "\n" {
		return true
	}
	return false
}


text:
<?php

class ActiveStateTest extends PHPUnit_Framework_TestCase
{

    public function test_basic_use()
    {
        // array
        set_active(['navbar1'=>'index']);
        $this->assertEquals(is_active('navbar1', 'index'), "active");
        $this->assertNull(is_active('navbar1', 'about'));

        // key, value
        set_active('navbar2','index2');
        $this->assertEquals(is_active('navbar2', 'index2'), "active");
        $this->assertNull(is_active('navbar2', 'about'));
    }

    public function test_set_active_syntax()
    {
        // array
        set_active(['list-group'=>'index']);
        $this->assertEquals(is_active('list-group', 'index'), "active");
        $this->assertEquals(get_active('list-group'), "index");

        // value (global key)
        set_active('winter_is_trumping');
        $this->assertEquals(is_active('winter_is_trumping'), "active");
        $this->assertEquals(get_active(), "winter_is_trumping");

        // key, value
        set_active('list-group2','index2');
        $this->assertEquals(is_active('list-group2', 'index2'), "active");
        $this->assertEquals(get_active('list-group2'), "index2");

        // key, value, settings
        set_active('list-group3','favourite-item', ['true'=>'wine','false'=>'not-active']);
        $this->assertEquals(is_active('list-group3', 'favourite-item'), "wine");
        $this->assertEquals(is_active('list-group3', 'not-favourite-item'), "not-active");
        $this->assertEquals(get_active('list-group3'), "favourite-item");

    }

    public function test_return_custom_css_class()
    {
        // array
        set_active(['navbar3'=>'index','true'=>'some-active-css-class']);

        $this->assertEquals(is_active('navbar3', 'index'), "some-active-css-class");
        $this->assertNull(is_active('navbar3', 'about'));

        // key, value, settings
        set_active('navbar4', 'index',['true'=>'some-active-css-class']);

        $this->assertEquals(is_active('navbar4', 'index'), "some-active-css-class");
        $this->assertNull(is_active('navbar4', 'about'));
    }

    public function test_return_boolean()
    {
        // array
        set_active(['navbar5'=>'index','return'=>'boolean']);

        $this->assertTrue(is_active('navbar5', 'index'));
        $this->assertFalse(is_active('navbar5', 'about'));

        // key, value, settings
        set_active('navbar6', 'index',['return'=>'boolean']);
        $this->assertTrue(is_active('navbar6', 'index'));
        $this->assertFalse(is_active('navbar6', 'about'));
    }

    public function test_global_mode()
    {
        // array
        set_active(['global_val2']);

        $this->assertEquals(is_active('global_val2'), 'active');
        $this->assertNull(is_active('wrong_global_val'));

        // key, value, settings
        set_active('global_val2',['return'=>'true']);

        $this->assertEquals(is_active('global_val2'), 'active');
        $this->assertNull(is_active('wrong_global_val'));
    }

    public function test_multiple_keys()
    {
        set_active(['top-fixed-bar'=>'admin','return'=>'boolean']);
        set_active(['sidebar'=>'dashboard']);
        set_active(['sidebar-submenu'=>'overview','true'=>'submenu-is-active']);

        $this->assertTrue(is_active('top-fixed-bar', 'admin'));
        $this->assertFalse(is_active('top-fixed-bar', 'contact'));

        $this->assertEquals(is_active('sidebar', 'dashboard'), 'active');
        $this->assertNull(is_active('sidebar', 'about'));

        $this->assertEquals(is_active('sidebar-submenu', 'overview'), 'submenu-is-active');
        $this->assertNull(is_active('sidebar-submenu', 'charts'));
    }

    public function test_override_key_and_return_type()
    {
        set_active(['navbar7'=>'index']);
        set_active(['navbar7'=>'about','return'=>'boolean']);

        $this->assertFalse(is_active('navbar7', 'index'));
        $this->assertTrue(is_active('navbar7', 'about'));
    }

    public function test_setting_class_while_return_boolean()
    {
        set_active(['navbar8'=>'index','return'=>'boolean','true'=>'some-active-css-class']);

        $this->assertTrue(is_active('navbar8', 'index'));
        $this->assertFalse(is_active('navbar8', 'about'));
    }

    public function test_key_not_exist()
    {
        $this->assertNull(is_active('key_is_not_exist', 'ufo'));
    }

    public function test_get_active()
    {
        set_active(['navbar9'=>'index']);
        $this->assertEquals(get_active('navbar9'), "index");

        set_active(['navbar10'=>'index']);
        $this->assertEquals(get_active('navbar11','default-value'), "default-value");
    }

    public function test_get_active_key_not_exist()
    {
        $this->assertNull(get_active('get_active_key_not_exist'));
    }
}


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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.github.sabomichal.akkaspringfactory.ActorSystemFactoryBean;
import com.typesafe.config.ConfigFactory;

@Configuration
@ComponentScan(basePackages={ "org.jupport.manager", "com.phn.base.component", "com.phn.tojoy.manager", "com.phn.tojoy.listener", "com.phn.tojoy.service"})
// Configurer that replaces ${...} placeholders with values from a properties file
// (in this case, JDBC-related settings for the JPA EntityManager definition below)
@PropertySource("classpath:spring/data-access.properties")
@EnableTransactionManagement
@Import({JpaPhnImConfig.class})
public class ImBusinessConfig {

	@Bean(name="actorSystem")
	public ActorSystemFactoryBean actorSystem() {
		ActorSystemFactoryBean factoryBean = new ActorSystemFactoryBean();
		factoryBean.setName("PhnActorSystem");
		factoryBean.setConfig(ConfigFactory.load("akkaActor.conf"));
		return factoryBean;
	}

}


text:
[https://unpkg.com/vuex](https://unpkg.com/vuex)

<!--email_off-->
[Unpkg.com](https://unpkg.com) fournit des liens CDN basés sur NPM. Le lien ci-dessus pointera toujours vers la dernière release sur NPM. Vous pouvez aussi utiliser un tag ou une version spécifique comme `https://unpkg.com/vuex@2.0.0`.
<!--/email_off-->

Incluez `vuex` après Vue et l'installation sera automatique :

``` html
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>
```

### NPM

``` bash
npm install vuex --save
```

### Yarn

``` bash
yarn add vuex
```

Lorsque vous utilisez un système de modules, vous devez explicitement installer le router via `Vue.use()`:

``` js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
```

Il n'est pas nécessaire de faire ceci lorsque vous utilisez des balises de script globales.

### Environnement de dev

Vous devrez cloner directement depuis GitHub et compiler `vuex` vous-même si
vous souhaitez utiliser la dernière version de dev.

``` bash
git clone https://github.com/vuejs/vuex.git node_modules/vuex
cd node_modules/vuex
npm install
npm run build
```


text:
#ifndef _PRO_RFCTIME_H_
#define _PRO_RFCTIME_H_

/*!
 * \file pro/rfctime.h
 * \brief RFC date and time conversion header.
 *
 * \verbatim
 *
 * $Log$
 * Revision 1.1  2008/01/31 09:29:05  haraldkipp
 * RFC date and time conversion added.
 *
 *
 * \endverbatim
 */

#include <time.h>

extern char *Rfc1123TimeString(struct tm *tm);

extern time_t RfcTimeParse(const char *str);
extern char *TimeParseHms(const char *str, int *hour, int *min, int *sec);
extern char *TimeParseDmy(const char *str, int *mday, int *mon, int *year);
extern char *TimeParseMonth(const char *str, int *month);
extern char *TimeParseYear(const char *str, int *year);

#endif


text:
package org.semanticweb.elk.reasoner.indexing.model;

import org.semanticweb.elk.owl.interfaces.ElkSubObjectPropertyOfAxiom;

/**
 * An {@link ElkSubObjectPropertyOfAxiomConversion} that can be modified as a
 * result of updating the {@link ModifiableOntologyIndex} where this object is
 * stored.
 *
 * @author "Yevgeny Kazakov"
 */
public interface ModifiableElkSubObjectPropertyOfAxiomConversion
		extends
			ElkSubObjectPropertyOfAxiomConversion,
			ModifiableIndexedSubObjectPropertyOfAxiomInference {

	/**
	 * A factory for creating instances
	 *
	 * @author Yevgeny Kazakov
	 *
	 */
	interface Factory {

		ModifiableElkSubObjectPropertyOfAxiomConversion getElkSubObjectPropertyOfAxiomConversion(
				ElkSubObjectPropertyOfAxiom originalAxiom,
				ModifiableIndexedPropertyChain subPropertyChain,
				ModifiableIndexedObjectProperty superProperty);

	}

}


text:
package neophytesguide01

object ExtractorDemo0 {
  def main(args: Array[String]): Unit = {
    val userList = List(User("Adam", "Riese", 9), User("Eva", "Green", 3), User("Harry", "Potter", 1))

	println(advance(userList))
	println(advance(userList.tail))
	println(advance(userList.tail.tail))
  }

  case class User(firstName: String, lastName: String, score: Int)

  def advance(xs: List[User]) = xs match {
  	case User(_, _, score1) :: User(_, _, score2) :: _ => score1 - score2
  	case _ => 0
  }
}


text:
package androidx.leanback.leanbackshowcase.app.room.di.androidinjectorannotation;

import androidx.leanback.leanbackshowcase.app.room.controller.overview.LiveDataFragment;

import dagger.Binds;
import dagger.Module;
import dagger.android.AndroidInjector;
import dagger.multibindings.ClassKey;
import dagger.multibindings.IntoMap;

@Module(subcomponents = LiveDataOverviewFragmentSubComponent.class)
public abstract class FragmentBuildersModule {

    @Binds
    @IntoMap
    @ClassKey(LiveDataFragment.class)
    abstract AndroidInjector.Factory<?> bindFragmentInjectorFactory(
            LiveDataOverviewFragmentSubComponent.Builder builder);
}


text:
package de.egore911.xdp.render;

import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;

import de.egore911.xdp.model.Border;
import de.egore911.xdp.model.Draw;
import de.egore911.xdp.model.Edge;
import de.egore911.xdp.model.Field;
import de.egore911.xdp.model.Fill;
import de.egore911.xdp.model.Font;
import de.egore911.xdp.model.Form;
import de.egore911.xdp.model.Margin;
import de.egore911.xdp.model.Page;
import de.egore911.xdp.model.ui.ButtonElement;
import de.egore911.xdp.model.ui.CheckboxElement;
import de.egore911.xdp.model.ui.TextElement;
import de.egore911.xdp.model.util.Dimension;
import de.egore911.xdp.model.util.Position;
import de.egore911.xdp.model.values.HtmlValue;
import de.egore911.xdp.model.values.ImageValue;
import de.egore911.xdp.model.values.LineValue;
import de.egore911.xdp.model.values.RectangleValue;
import de.egore911.xdp.model.values.TextValue;

public class HtmlRenderer {

	private static final Logger log = Logger.getLogger(HtmlRenderer.class
			.getName());

	public void render(Form form, File dir, int pageNumber) throws IOException {

		try (FileOutputStream fos = new FileOutputStream(new File(dir,
				form.getName() + ".html"))) {
			int imageCounter = 1;

			writeln(fos, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			writeln(fos, "<!DOCTYPE html>");
			writeln(fos, "");
			writeln(fos, " ");
			writeln(fos,
					"  <meta content=\"text/html; charset=UTF-8\" http-equiv=\"Content-Type\" />");
			writeln(fos, "  <title>" + form.getName() + "</title>");
			writeln(fos,
					"  ");
			writeln(fos, " ");
			writeln(fos, " ");

			Page page = form.getPages().get(pageNumber - 1);

			writeln(fos,
					"
");

			for (Draw d : page.getDraws()) {

				if (d.getValue() instanceof RectangleValue) {
					renderRectangleValue(fos, d);
				} else if (d.getValue() instanceof LineValue) {
					renderLineValue(fos, d);
				} else if (d.getValue() instanceof ImageValue) {
					imageCounter = renderImageValue(form, dir, fos,
							imageCounter, d);
				} else if (d.getValue() instanceof HtmlValue) {
					renderHtmlOrTextValue(fos, d);
				} else if (d.getValue() instanceof TextValue) {
					renderHtmlOrTextValue(fos, d);
				} else {
					throw new UnsupportedOperationException("Can't handle "
							+ d.getValue().getClass().getSimpleName()
							+ " as value for draw");
				}

			}

			for (Field f : page.getFields()) {
				if (f.getUi() instanceof TextElement) {
					renderTextElement(fos, f);
				} else if (f.getUi() instanceof ButtonElement) {
					renderButtonElement(fos, f);
				} else if (f.getUi() instanceof CheckboxElement) {
					renderCheckboxElement(fos, f);
				} else {
					if (f.getValue() instanceof RectangleValue) {
						renderRectangleValue(fos, f);
					} else if (f.getValue() instanceof LineValue) {
						renderLineValue(fos, f);
					} else if (f.getValue() instanceof ImageValue) {
						imageCounter = renderImageValue(form, dir, fos,
								imageCounter, f);
					} else if (f.getValue() instanceof HtmlValue) {
						renderHtmlOrTextValue(fos, f);
					} else if (f.getValue() instanceof TextValue) {
						renderHtmlOrTextValue(fos, f);
					} else {
						throw new UnsupportedOperationException("Can't handle "
								+ f.getUi().getClass().getSimpleName()
								+ " as value for field " + f.getName());
					}
				}

			}

			writeln(fos, "
");

			writeln(fos, " ");
			writeln(fos, "");

		}
		// Don't care
	}

	private void renderHtmlOrTextValue(FileOutputStream fos, Draw d)
			throws IOException {
		write(fos, "
");
		if (d.getValue() instanceof TextValue) {
			if (((TextValue) d.getValue()).getText() != null) {
				write(fos, nl2br(((TextValue) d.getValue()).getText()));
			}
		} else if (d.getValue() instanceof HtmlValue) {
			if (((HtmlValue) d.getValue()).getHtmlContent() != null) {
				write(fos, ((HtmlValue) d.getValue()).getHtmlContent());
			}
		} else {
			throw new UnsupportedOperationException("Can't handle "
					+ d.getValue().getClass().getSimpleName()
					+ " as value for draw");
		}
		writeln(fos, "
");
	}

	private int renderImageValue(Form form, File dir, FileOutputStream fos,
			int imageCounter, Draw d) throws FileNotFoundException, IOException {
		ImageValue image = (ImageValue) d.getValue();

		write(fos, " 0) {
			String fileName = form.getName() + (imageCounter++);
			if (((ImageValue) d.getValue()).getMimeType().equals("image/png")) {
				fileName += ".png";
			} else {
				log.severe("MimeType "
						+ ((ImageValue) d.getValue()).getMimeType()
						+ " of image unknown");
			}
			FileOutputStream imageFos = new FileOutputStream(new File(dir,
					fileName));
			imageFos.write(((ImageValue) d.getValue()).getData());
			imageFos.close();

			write(fos, fileName);
		} else {
			write(fos, image.getSrc());
		}

		write(fos, "\" style=\"");
		write(fos, addDimension(d.getDimension()));
		write(fos, addPosition(d.getPosition()));
		write(fos, addMargin(d.getMargin()));
		write(fos, "\"/>");
		log.severe("ImageValue not handled yet");
		return imageCounter;
	}

	private void renderLineValue(FileOutputStream fos, Draw d)
			throws IOException {
		write(fos, "
 0.001) {
			if (d.getDimension().getHeight() > 0.001
					&& d.getDimension().getWidth() > 0.001) {
				throw new RuntimeException("Line has width and height");
			} else if (d.getDimension().getHeight() > 0.001) {
				write(fos, "border-right: ");
			} else if (d.getDimension().getWidth() > 0.001) {
				write(fos, "border-top: ");
			} else {
				throw new RuntimeException("Line has no width and no height");
			}
			write(fos, Double.toString(border.getEdge().getWidthPx()));
			write(fos, "px solid ");
			write(fos, colorToRgb(border.getEdge().getColor()));
			write(fos, ";");
		} else {
			log.severe("Can't handle border of " + d);
		}

		write(fos, addDimension(d.getDimension()));
		write(fos, addPosition(d.getPosition()));
		write(fos, addFont(d.getFont()));
		write(fos, addMargin(d.getMargin()));
		write(fos, "\">");
		writeln(fos, "
");
	}

	private void renderRectangleValue(FileOutputStream fos, Draw d)
			throws IOException {
		write(fos, "
");
		writeln(fos, "
");
	}

	private void renderButtonElement(FileOutputStream fos, Field f)
			throws IOException {
		write(fos, "  <input id=\"");
		write(fos, f.getName());
		write(fos, "\" type=\"submit\" name=\"");
		write(fos, f.getName());
		write(fos, "\" style=\"");
		write(fos, addDimension(f.getDimension()));
		write(fos, addPosition(f.getPosition()));
		write(fos, addFont(f.getCaption().getFont() == null ? f.getFont() : f
				.getCaption().getFont()));
		write(fos, addMargin(f.getMargin()));
		write(fos, addBorder(f.getBorder()));
		write(fos, addVisible(f.isVisible()) + "\"");
		if (f.getCaption().getValue() instanceof TextValue
				&& ((TextValue) f.getCaption().getValue()).getText() != null) {
			write(fos, " value=\"");
			write(fos, ((TextValue) f.getCaption().getValue()).getText());
			write(fos, "\"");
		}
		if (!f.isEditable()) {
			write(fos, " disabled=\"disabled\"");
		}
		writeln(fos, " />");
	}

	private void renderCheckboxElement(FileOutputStream fos, Field f)
			throws IOException {
		write(fos, "  <input id=\"");
		write(fos, f.getName());
		write(fos, "\" type=\"checkbox\" name=\"");
		write(fos, f.getName());
		write(fos, "\" style=\"");
		write(fos, addDimension(f.getDimension()));
		write(fos, addPosition(f.getPosition()));
		write(fos, addFont(f.getCaption().getFont() == null ? f.getFont() : f
				.getCaption().getFont()));
		write(fos, addMargin(f.getMargin()));
		write(fos, addBorder(f.getBorder()));
		write(fos, addVisible(f.isVisible()) + "\"");
		if (f.getCaption().getValue() instanceof TextValue
				&& ((TextValue) f.getCaption().getValue()).getText() != null) {
			write(fos, " value=\"");
			write(fos, ((TextValue) f.getCaption().getValue()).getText());
			write(fos, "\"");
		}
		if (!f.isEditable()) {
			write(fos, " disabled=\"disabled\"");
		}
		writeln(fos, " />");
	}

	private void renderTextElement(FileOutputStream fos, Field f)
			throws IOException {

		if (f.getCaption() != null) {
			write(fos, "
");
			if (f.getCaption().getValue() != null) {
				write(fos, "  ");
				if (f.getCaption().getValue() instanceof TextValue) {
					if (((TextValue) f.getCaption().getValue()).getText() != null) {
						write(fos,
								((TextValue) f.getCaption().getValue())
										.getText());
					}
				} else {
					write(fos,
							((HtmlValue) f.getCaption().getValue())
									.getHtmlContent());
				}
				writeln(fos, "");
			}
		}

		if (((TextElement) f.getUi()).isMultiline()) {

			write(fos, "  <textarea id=\"");
			write(fos, f.getName());
			write(fos, "\" name=\"");
			write(fos, f.getName());
			write(fos, "\" style=\"");
			if (f.getCaption() == null) {
				write(fos, addDimension(f.getDimension()));
				write(fos, addPosition(f.getPosition()));
			} else {
				double offsetLeft = f.getCaption().getReservePx();
				if (Math.abs(offsetLeft) > 0.001) {
					write(fos, "position:absolute; left: " + offsetLeft + "px;");
				}
				write(fos, "top:0;");
				double height = f.getDimension().getHeight()
						- f.getMargin().getTop() - f.getMargin().getBottom();
				write(fos, "height:" + height + "mm;");
				double width = f.getDimension().getWidth()
						- f.getMargin().getLeft() - f.getMargin().getRight()
						- offsetLeft;
				write(fos, "width:" + width + "mm;");
			}

			write(fos, addFont(f.getFont()));
			write(fos, addMargin(f.getMargin()));
			write(fos, addBorder(f.getBorder()));
			write(fos, addVisible(f.isVisible()));
			write(fos, "background-color: transparent;"); // XXX guess
			write(fos, "\"");
			if (((TextValue) f.getValue()).getMaxLength() > 0) {
				write(fos,
						" maxlength=\""
								+ ((TextValue) f.getValue()).getMaxLength()
								+ "\"");
			}
			if (!f.isEditable()) {
				write(fos, " disabled=\"disabled\"");
			}
			if (f.isReadOnly()) {
				write(fos, " readonly=\"readonly\"");
			}
			write(fos, ">");
			if (((TextValue) f.getValue()).getText() != null) {
				write(fos, ((TextValue) f.getValue()).getText());
			}
			writeln(fos, "</textarea>");
		} else {
			write(fos, "  <input id=\"");
			write(fos, f.getName());
			write(fos, "\" type=\"text\" name=\"");
			write(fos, f.getName());
			write(fos, "\" style=\"");
			if (f.getCaption() == null) {
				write(fos, addDimension(f.getDimension()));
				write(fos, addPosition(f.getPosition()));
			} else {
				double offsetLeft = f.getCaption().getReserve();
				if (Math.abs(offsetLeft) > 0.001) {
					write(fos, "position:absolute; left: "
							+ f.getCaption().getReservePx() + "px;");
				}
				write(fos, "top:0;");
				double height = f.getDimension().getHeight()
						- f.getMargin().getTop() - f.getMargin().getBottom();
				write(fos, "height:" + height + "mm;");
				double width = f.getDimension().getWidth()
						- f.getMargin().getLeft() - f.getMargin().getRight()
						- offsetLeft;
				write(fos, "width:" + width + "mm;");
			}
			write(fos, addFont(f.getFont()));
			write(fos, addMargin(f.getMargin()));
			write(fos, addBorder(f.getBorder()));
			write(fos, addVisible(f.isVisible()));
			write(fos, "background-color: transparent;"); // XXX guess
			write(fos, "\"");
			if (f.getValue() instanceof TextValue
					&& ((TextValue) f.getValue()).getText() != null) {
				write(fos, " value=\"");
				write(fos, ((TextValue) f.getValue()).getText());
				write(fos, "\"");
			}
			if (!f.isEditable()) {
				write(fos, " disabled=\"disabled\"");
			}
			writeln(fos, " />");
		}

		if (f.getCaption() != null) {
			writeln(fos, "
");
		}
	}

	private String nl2br(String text) {
		if (text == null)
			return null;

		return text.replace("\r\n", "
").replace("\r", "
")
				.replace("\n", "
");
	}

	private String addMargin(Margin margin) {
		if (margin == null) {
			return "";
		}
		StringBuilder style = new StringBuilder();

		if (margin.getTop() == margin.getLeft()
				&& margin.getTop() == margin.getBottom()
				&& margin.getTop() == margin.getRight()) {
			style.append("margin:");
			style.append(margin.getTop());
			style.append("mm;");
		} else {

			if (Math.abs(margin.getTop()) > 0.001) {
				style.append("margin-top:");
				style.append(margin.getTop());
				style.append("mm;");
			}
			if (Math.abs(margin.getLeft()) > 0.001) {
				style.append("margin-left:");
				style.append(margin.getLeft());
				style.append("mm;");
			}
			if (Math.abs(margin.getBottom()) > 0.001) {
				style.append("margin-bottom:");
				style.append(margin.getBottom());
				style.append("mm;");
			}
			if (Math.abs(margin.getRight()) > 0.001) {
				style.append("margin-right:");
				style.append(margin.getRight());
				style.append("mm;");
			}
		}
		return style.toString();
	}

	private String addFill(Fill fill) {
		if (fill == null || !fill.isVisible()) {
			return "";
		}
		StringBuilder style = new StringBuilder();
		if (fill.getColor() != null) {
			style.append("background-color:");
			style.append(colorToRgb(fill.getColor()));
			style.append(";");
		}
		return style.toString();
	}

	private String addBorder(Border border) {
		if (border == null || !border.isVisible() || border.getEdge() == null) {
			return "";
		}
		StringBuilder style = new StringBuilder();
		if (border.getEdge().getWidth() > -0.999) {
			if (Math.abs(border.getEdge().getWidth()) < 0.001) {
				style.append("border: none;");
			} else {

				if (border.getEdge().getType() == null) {
					style.append("border:");
					style.append(border.getEdge().getWidthPx());
					style.append("px solid ");
					style.append(colorToRgb(border.getEdge().getColor()));
					style.append(";");
				} else {
					if (border.getEdge().getType() == Edge.Type.lowered) {
						style.append("border:");
						style.append(border.getEdge().getWidthPx());
						style.append("px inset;");
					} else if (border.getEdge().getType() == Edge.Type.raised) {
						style.append("border:");
						style.append(border.getEdge().getWidthPx());
						style.append("px outset;");
					} else {
						log.warning("Unhandled border typ "
								+ border.getEdge().getType());
					}
				}
			}
		}
		return style.toString();
	}

	private String addVisible(boolean visible) {
		if (!visible) {
			return "display:none;";
		}
		return "";
	}

	private static String colorToRgb(Color color) {

		if (color == null) {
			// Workaround: Default to black
			color = Color.black;
		}

		return "rgb(" + color.getRed() + ',' + color.getGreen() + ',' + color.getBlue() + ")";
	}

	private String addFont(Font font) {
		if (font == null) {
			return "";
		}
		StringBuilder style = new StringBuilder();
		if ("Sans".equals(font.getFamily())) {
			style.append("font-family:sans;");
		} else if ("Arial".equals(font.getFamily())) {
			style.append("font-family:Arial,sans;");
		} else if ("Verdana".equals(font.getFamily())) {
			style.append("font-family:Verdana,Arial,sans;");
		} else if ("Wingdings".equals(font.getFamily())) {
			style.append("font-family:Wingdings;");
		} else {
			throw new RuntimeException("Unknown font " + font.getFamily());
		}

		if (Math.abs(font.getSize()) > 0.001) {
			style.append("font-size:");
			style.append(font.getSizePx());
			style.append("px;");
		}

		if (font.getWeight() != null) {
			style.append("font-weight:");
			style.append(font.getWeight());
			style.append(";");
		}

		if (font.isUnderline()) {
			style.append("text-decoration:underline;");
		}

		if (font.getFill() != null && font.getFill().getColor() != null) {
			style.append("font-color:");
			style.append(colorToRgb(font.getFill().getColor()));
			style.append(";");
		}

		return style.toString();
	}

	private String addDimension(Dimension dimension) {
		StringBuilder style = new StringBuilder();
		if (Math.abs(dimension.getHeight()) > 0.001) {
			style.append("height:");
			double height = dimension.getHeightPx();
			style.append(height);
			style.append("px;");
		}
		if (Math.abs(dimension.getWidth()) > 0.001) {
			style.append("width:");
			double width = dimension.getWidthPx();
			style.append(width);
			style.append("px;");
		}
		return style.toString();
	}

	private String addPosition(Position position) {
		StringBuilder style = new StringBuilder();
		if (Math.abs(position.getX()) > 0.001) {
			style.append("left:");
			double x = position.getXPx();
			style.append(x);
			style.append("px;");
		}

		style.append("top:");
		double y = position.getYPx();
		style.append(y);
		style.append("px;");

		if (style.length() > 0) {
			style.append("position:absolute;");
		}
		return style.toString();
	}

	private static void write(FileOutputStream fos, String text)
			throws IOException {
		fos.write(text.getBytes());
	}

	private static void writeln(FileOutputStream fos, String text)
			throws IOException {
		write(fos, text);
		fos.write('\n');
	}

}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.activiti.engine.delegate.event.impl.ActivitiEntityWithVariablesEventImpl (Flowable - Engine 5.23.0 API)</title>
<meta name="date" content="2017-03-27">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.activiti.engine.delegate.event.impl.ActivitiEntityWithVariablesEventImpl

Packages that use ActivitiEntityWithVariablesEventImpl

Package
Description

org.activiti.engine.delegate.event.impl

Uses of ActivitiEntityWithVariablesEventImpl in org.activiti.engine.delegate.event.impl

Subclasses of ActivitiEntityWithVariablesEventImpl in org.activiti.engine.delegate.event.impl

Modifier and Type
Class and Description

class
ActivitiProcessStartedEventImpl

An ActivitiCancelledEvent implementation.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017 Flowable. All rights reserved.


text:
package uk.ac.ed.inf.graph.util;

import java.util.Set;

import uk.ac.ed.inf.graph.compound.ICompoundEdge;
import uk.ac.ed.inf.graph.compound.ICompoundNode;

public interface INodeSet<
		N extends ICompoundNode,
		E extends ICompoundEdge
> extends Set<N> {

	N get(int nodeIdx);

	boolean contains(int nodeIdx);
}


text:
require "aescrypt"
require "base64"
require "json"

module ActiveAsset
  class Serializer
    class DecodeError < StandardError; end

    def encode(hash, password)
      AESCrypt.encrypt(JSON.dump(hash), password).tr("\n=", "")
    end

    def decode(string, password)
      JSON.load(AESCrypt.decrypt(string, password))
    rescue ArgumentError, OpenSSL::Cipher::CipherError
      raise DecodeError, "The given string can't be decrypted, probably because string is empty or password is invalid"
    end
  end
end


text:
function Install-CUser
{
    <#
    .SYNOPSIS
    Installs a *local* user account.

    .DESCRIPTION
    `Install-CUser` creates a new *local* user account, or updates an existing *local* user account.

    Returns the user if `-PassThru` switch is used. The object returned, an instance of `System.DirectoryServices.AccountManagement.UserPrincipal`, uses external resources, which means it can leak memory when garbage collected. When you're done using the user object you get, call its `Dispose()` method so its external resources are cleaned up properly.

    The `UserCannotChangePassword` and `PasswordExpires` switches were added in Carbon 2.0.

    .OUTPUTS
    System.DirectoryServices.AccountManagement.UserPrincipal.

    .LINK
    Get-CUser

    .LINK
    New-CCredential

    .LINK
    Test-CUser

    .LINK
    Uninstall-CUser

    .EXAMPLE
    Install-CUser -Credential $lukeCredentials -Description "Luke Skywalker's account."

    Creates a new `LSkywalker` user account with the given password and description.  Luke's password is set to never expire.

    .EXAMPLE
    Install-CUser -Credential $lukeCredentials -UserCannotChangePassword -PasswordExpires

    Demonstrates how to create an account for a user who cannot change his password and whose password will expire.
    #>
    [CmdletBinding(SupportsShouldProcess=$true,DefaultParameterSetName='WithUserNameAndPassword')]
    [OutputType([System.DirectoryServices.AccountManagement.UserPrincipal])]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams","")]
    param(
        [Parameter(Mandatory=$true,ParameterSetName='WithUserNameAndPassword',DontShow=$true)]
        [ValidateLength(1,20)]
        [string]
        # OBSOLETE. The `UserName` parameter will be removed in a future major version of Carbon. Use the `Credential` parameter instead.
        $UserName,

        [Parameter(Mandatory=$true,ParameterSetName='WithUserNameAndPassword',DontShow=$true)]
        [string]
        # OBSOLETE. The `Password` parameter will be removed in a future major version of Carbon. Use the `Credential` parameter instead.
        $Password,

        [Parameter(Mandatory=$true,ParameterSetName='WithCredential')]
        [pscredential]
        # The user's credentials.
        #
        # The `Credential` parameter was added in Carbon 2.0.
        $Credential,

        [string]
        # A description of the user.
        $Description,

        [string]
        # The full name of the user.
        $FullName,

        [Switch]
        # Prevent the user from changing his password. New in Carbon 2.0.
        $UserCannotChangePassword,

        [Switch]
        # Set to true if the user's password should expire. New in Carbon 2.0.
        $PasswordExpires,

        [Switch]
        # Return the user. New in Carbon 2.0.
        $PassThru
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    Write-Timing 'Install-CUser Start'

    if( $PSCmdlet.ParameterSetName -eq 'WithCredential' )
    {
        $UserName = $Credential.UserName
    }

    Write-Timing '              Getting user'
    $user = Get-CUser -userName $UserName -ErrorAction Ignore

    Write-Timing '              Creating PrincipalContext'
    if( $user )
    {
        $ctx = $user.Context
    }
    else
    {
        $ctx = New-Object 'DirectoryServices.AccountManagement.PrincipalContext' ([DirectoryServices.AccountManagement.ContextType]::Machine)
    }

    try
    {
        $operation = 'update'
        if( -not $user )
        {
            Write-Timing '              Creating UserPrincipal'
            $operation = 'create'
            $user = New-Object 'DirectoryServices.AccountManagement.UserPrincipal' $ctx
            $creating = $true
        }

        $user.SamAccountName = $UserName
        $user.DisplayName = $FullName
        $user.Description = $Description
        $user.UserCannotChangePassword = $UserCannotChangePassword
        $user.PasswordNeverExpires = -not $PasswordExpires

        Write-Timing '              Setting password'
        if( $PSCmdlet.ParameterSetName -eq 'WithUserNameAndPassword' )
        {
            Write-CWarningOnce ('Install-CUser function''s `UserName` and `Password` parameters are obsolete and will be removed in a future version of Carbon. Please use the `Credential` parameter instead.')
            $user.SetPassword( $Password )
        }
        else
        {
            $user.SetPassword( $Credential.GetNetworkCredential().Password )
        }

        if( $PSCmdlet.ShouldProcess( $Username, "$operation local user" ) )
        {
            Write-Timing '              Saving'
            $user.Save()
        }

        if( $PassThru )
        {
            return $user
        }
    }
    finally
    {
        Write-Timing '              Finally'
        if( -not $PassThru )
        {
            $user.Dispose()
            $ctx.Dispose()
        }
        Write-Timing 'Install-CUser Done'
    }
}


text:
"""Binary for evaluating Tensorflow models on the YouTube-8M dataset."""

import time
import numpy

import eval_util
import losses
import frame_level_models
import video_level_models
import xp_frame_level_models
import xp_video_level_models
import readers
import tensorflow as tf
from tensorflow import app
from tensorflow import flags
from tensorflow import gfile
from tensorflow import logging
import utils
import model_utils

FLAGS = flags.FLAGS

if __name__ == "__main__":
  # Dataset flags.
  flags.DEFINE_string("train_dir", "/tmp/yt8m_model/",
                      "The directory to load the model files from. "
                      "The tensorboard metrics files are also saved to this "
                      "directory.")
  flags.DEFINE_string("check_point", "", "if not blank, use this check point")
  flags.DEFINE_string("output_file", "/tmp/eval_output.csv",
                      "The file to save the predictions to.")
  flags.DEFINE_string(
      "eval_data_pattern", "",
      "File glob defining the evaluation dataset in tensorflow.SequenceExample "
      "format. The SequenceExamples are expected to have an 'rgb' byte array "
      "sequence feature as well as a 'labels' int64 context feature.")
  flags.DEFINE_string("feature_names", "mean_rgb", "Name of the feature "
                      "to use for training.")
  flags.DEFINE_string("feature_sizes", "1024", "Length of the feature vectors.")
  flags.DEFINE_bool(
       "apply_global_normalization", True,
       "By default, apply l2_normalization with calculated global mean/std.")
  flags.DEFINE_bool("apply_batch_l2_normalization", True, "By default, apply l2 batch normalization")
  flags.DEFINE_integer("truncated_num_classes", 4716, "Number of classes to train for.")
  # Model flags.
  flags.DEFINE_bool(
      "frame_features", False,
      "If set, then --eval_data_pattern must be frame-level features. "
      "Otherwise, --eval_data_pattern must be aggregated video-level "
      "features. The model must also be set appropriately (i.e. to read 3D "
      "batches VS 4D batches.")
  flags.DEFINE_string(
      "model", "LogisticModel",
      "Which architecture to use for the model. Options include 'Logistic', "
      "'SingleMixtureMoe', and 'TwoLayerSigmoid'. See aggregated_models.py and "
      "frame_level_models.py for the model definitions.")
  flags.DEFINE_integer("batch_size", 1024,
                       "How many examples to process per batch.")
  flags.DEFINE_string("label_loss", "CrossEntropyLoss",
                      "Loss computed on validation data")
  flags.DEFINE_float("loss_epsilon", 1e-6, "log(x+epsilon)")

  # Other flags.
  flags.DEFINE_integer("num_readers", 8,
                       "How many threads to use for reading input files.")
  flags.DEFINE_bool("decode_zlib", True,
      		        "Whether or not the data files are zlib compressed.")
  flags.DEFINE_boolean("run_once", False, "Whether to run eval only once.")
  flags.DEFINE_integer("top_k", 20, "How many predictions to output per video.")

def find_class_by_name(name, modules):
  """Searches the provided modules for the named class and returns it."""
  modules = [getattr(module, name, None) for module in modules]
  return next(a for a in modules if a)

def format_lines(video_ids, predictions, top_k):
  batch_size = len(video_ids)
  for video_index in range(batch_size):
    top_indices = numpy.argpartition(predictions[video_index], -top_k)[-top_k:]
    line = [(class_index, predictions[video_index][class_index])
            for class_index in top_indices]
    line = sorted(line, key=lambda p: -p[1])
    yield video_ids[video_index].decode('utf-8') + "," + " ".join("%i %f" % pair
                                                  for pair in line) + "\n"

def get_input_evaluation_tensors(reader,
                                 data_pattern,
                                 batch_size=1024,
                                 num_readers=1):
  """Creates the section of the graph which reads the evaluation data.

  Args:
    reader: A class which parses the training data.
    data_pattern: A 'glob' style path to the data files.
    batch_size: How many examples to process at a time.
    num_readers: How many I/O threads to use.

  Returns:
    A tuple containing the features tensor, labels tensor, and optionally a
    tensor containing the number of frames per video. The exact dimensions
    depend on the reader being used.

  Raises:
    IOError: If no files matching the given pattern were found.
  """
  logging.info("Using batch size of " + str(batch_size) + " for evaluation.")
  with tf.name_scope("eval_input"):
    files = gfile.Glob(data_pattern)
    if not files:
      raise IOError("Unable to find the evaluation files.")
    logging.info("number of evaluation files: " + str(len(files)))
    filename_queue = tf.train.string_input_producer(
        files, shuffle=False, num_epochs=1)
    eval_data = [
        reader.prepare_reader(filename_queue) for _ in range(num_readers)
    ]
    return tf.train.batch_join(
        eval_data,
        batch_size=batch_size,
        capacity=3 * batch_size,
        allow_smaller_final_batch=True,
        enqueue_many=True)

def build_graph(reader,
                model,
                eval_data_pattern,
                label_loss_fn,
                batch_size=1024,
                num_readers=1):
  """Creates the Tensorflow graph for evaluation.

  Args:
    reader: The data file reader. It should inherit from BaseReader.
    model: The core model (e.g. logistic or neural net). It should inherit
           from BaseModel.
    eval_data_pattern: glob path to the evaluation data files.
    label_loss_fn: What kind of loss to apply to the model. It should inherit
                from BaseLoss.
    batch_size: How many examples to process at a time.
    num_readers: How many threads to use for I/O operations.
  """
  # model params
  g_mean, g_std = model_utils.load_global_moments()
  g_inv_std = 1.0/g_std
  global_mean = tf.constant(g_mean, dtype=tf.float32)
  global_inv_std = tf.constant(g_inv_std, dtype=tf.float32)

  # No need to weight the labels in eval or inference. Just pass the param.
  wgts_np = numpy.ones(FLAGS.truncated_num_classes)
  wgts_4_lossfn= tf.constant(wgts_np, dtype=tf.float32)

  global_step = tf.Variable(0, trainable=False, name="global_step")
  video_id_batch, model_input_raw, labels_batch, num_frames = get_input_evaluation_tensors(  # pylint: disable=g-line-too-long
      reader,
      eval_data_pattern,
      batch_size=batch_size,
      num_readers=num_readers)
  tf.summary.histogram("model_/input_raw", model_input_raw)

  #feature_dim = len(model_input_raw.get_shape()) - 1
  # Normalize input features or not
  model_input = model_input_raw
  if FLAGS.apply_global_normalization:
     model_input = (model_input - global_mean) * global_inv_std
  if FLAGS.apply_batch_l2_normalization:
     feature_dim = len(model_input.get_shape()) - 1
     model_input = tf.nn.l2_normalize(model_input, feature_dim)

  with tf.variable_scope("tower"):
    result = model.create_model(model_input,
                                num_frames=num_frames,
                                vocab_size=reader.num_classes,
                                labels=labels_batch,
                                layers_keep_probs=tf.constant([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], tf.float32, name="layers_keep_probs"),
                                is_training=False)
    predictions = result["predictions"]
    tf.summary.histogram("model_activations", predictions)
    if "loss" in result.keys():
      label_loss = result["loss"]
    else:
      label_loss = label_loss_fn.calculate_loss(predictions, labels_batch,
                                                FLAGS.loss_epsilon,
                                                wgts_4_lossfn)

  tf.add_to_collection("global_step", global_step)
  tf.add_to_collection("loss", label_loss)
  tf.add_to_collection("predictions", predictions)
  tf.add_to_collection("input_batch", model_input)
  tf.add_to_collection("video_id_batch", video_id_batch)
  tf.add_to_collection("num_frames", num_frames)
  tf.add_to_collection("labels", tf.cast(labels_batch, tf.float32))
  tf.add_to_collection("summary_op", tf.summary.merge_all())

def evaluation_loop(video_id_batch, prediction_batch, label_batch, loss,
                    summary_op, saver, summary_writer, evl_metrics,
                    last_global_step_val):
  """Run the evaluation loop once.

  Args:
    video_id_batch: a tensor of video ids mini-batch.
    prediction_batch: a tensor of predictions mini-batch.
    label_batch: a tensor of label_batch mini-batch.
    loss: a tensor of loss for the examples in the mini-batch.
    summary_op: a tensor which runs the tensorboard summary operations.
    saver: a tensorflow saver to restore the model.
    summary_writer: a tensorflow summary_writer
    evl_metrics: an EvaluationMetrics object.
    last_global_step_val: the global step used in the previous evaluation.

  Returns:
    The global_step used in the latest model.
  """

  global_step_val = -1
  with tf.Session() as sess, gfile.Open(FLAGS.output_file, "w+") as out_file:
    if FLAGS.check_point != '':
      latest_checkpoint = FLAGS.train_dir + '/model.ckpt-' + FLAGS.check_point
    else:
      latest_checkpoint = tf.train.latest_checkpoint(FLAGS.train_dir)
    if latest_checkpoint:
      logging.info("Loading checkpoint for eval: " + latest_checkpoint)
      # Restores from checkpoint
      saver.restore(sess, latest_checkpoint)
      # Assuming model_checkpoint_path looks something like:
      # /my-favorite-path/yt8m_train/model.ckpt-0, extract global_step from it.
      global_step_val = latest_checkpoint.split("/")[-1].split("-")[-1]
    else:
      logging.info("No checkpoint file found.")
      return global_step_val

    if global_step_val == last_global_step_val:
      logging.info("skip this checkpoint global_step_val=%s "
                   "(same as the previous one).", global_step_val)
      return global_step_val

    sess.run([tf.local_variables_initializer()])
    out_file.write("VideoId,LabelConfidencePairs\n")

    # Start the queue runners.
    fetches = [video_id_batch, prediction_batch, label_batch, loss, summary_op]
    coord = tf.train.Coordinator()
    try:
      threads = []
      for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
        threads.extend(qr.create_threads(
            sess, coord=coord, daemon=True,
            start=True))
      logging.info("enter eval_once loop global_step_val = %s. ",
                   global_step_val)

      evl_metrics.clear()

      examples_processed = 0
      while not coord.should_stop():
        batch_start_time = time.time()
        #_, predictions_val, labels_val, loss_val, summary_val = sess.run(
        video_id_batch_val, predictions_val, labels_val, loss_val, summary_val = sess.run(
            fetches)
        seconds_per_batch = time.time() - batch_start_time
        example_per_second = labels_val.shape[0] / seconds_per_batch
        examples_processed += labels_val.shape[0]

        # output the results
        for line in format_lines(video_id_batch_val, predictions_val, FLAGS.top_k):
            out_file.write(line)
        out_file.flush()

        iteration_info_dict = evl_metrics.accumulate(predictions_val,
                                                     labels_val, loss_val)
        iteration_info_dict["examples_per_second"] = example_per_second

        iterinfo = utils.AddGlobalStepSummary(
            summary_writer,
            global_step_val,
            iteration_info_dict,
            summary_scope="Eval")
        logging.info("examples_processed: %d | %s", examples_processed,
                     iterinfo)

    except tf.errors.OutOfRangeError as e:
      logging.info(
          "Done with batched inference. Now calculating global performance "
          "metrics.")
      # calculate the metrics for the entire epoch
      epoch_info_dict = evl_metrics.get()
      epoch_info_dict["epoch_id"] = global_step_val

      summary_writer.add_summary(summary_val, global_step_val)
      epochinfo = utils.AddEpochSummary(
          summary_writer,
          global_step_val,
          epoch_info_dict,
          summary_scope="Eval")
      logging.info(epochinfo)
      evl_metrics.clear()
    except Exception as e:  # pylint: disable=broad-except
      logging.info("Unexpected exception: " + str(e))
      coord.request_stop(e)

    coord.request_stop()
    coord.join(threads, stop_grace_period_secs=10)

    return global_step_val

def evaluate():
  tf.set_random_seed(0)  # for reproducibility
  with tf.Graph().as_default():
    # convert feature_names and feature_sizes to lists of values
    feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes(
        FLAGS.feature_names, FLAGS.feature_sizes)

    if FLAGS.frame_features:
      reader = readers.YT8MFrameFeatureReader(
        num_classes = FLAGS.truncated_num_classes,
        decode_zlib = FLAGS.decode_zlib,
        feature_names=feature_names, feature_sizes=feature_sizes)
    else:
      reader = readers.YT8MAggregatedFeatureReader(
        num_classes = FLAGS.truncated_num_classes,
        decode_zlib = FLAGS.decode_zlib,
        feature_names=feature_names, feature_sizes=feature_sizes)

    model = find_class_by_name(FLAGS.model,
        [frame_level_models, video_level_models,
         xp_frame_level_models, xp_video_level_models])()
    label_loss_fn = find_class_by_name(FLAGS.label_loss, [losses])()

    if FLAGS.eval_data_pattern is "":
      raise IOError("'eval_data_pattern' was not specified. " +
                     "Nothing to evaluate.")

    build_graph(
        reader=reader,
        model=model,
        eval_data_pattern=FLAGS.eval_data_pattern,
        label_loss_fn=label_loss_fn,
        num_readers=FLAGS.num_readers,
        batch_size=FLAGS.batch_size)
    logging.info("built evaluation graph")
    video_id_batch = tf.get_collection("video_id_batch")[0]
    prediction_batch = tf.get_collection("predictions")[0]
    label_batch = tf.get_collection("labels")[0]
    loss = tf.get_collection("loss")[0]
    summary_op = tf.get_collection("summary_op")[0]

    saver = tf.train.Saver(tf.global_variables())
    summary_writer = tf.summary.FileWriter(
        FLAGS.train_dir, graph=tf.get_default_graph())

    evl_metrics = eval_util.EvaluationMetrics(reader.num_classes, FLAGS.top_k)

    last_global_step_val = -1
    while True:
      last_global_step_val = evaluation_loop(video_id_batch, prediction_batch,
                                             label_batch, loss, summary_op,
                                             saver, summary_writer, evl_metrics,
                                             last_global_step_val)
      if FLAGS.run_once:
        break

def main(unused_argv):
  logging.set_verbosity(tf.logging.INFO)
  print("tensorflow version: %s" % tf.__version__)
  evaluate()

if __name__ == "__main__":
  app.run()


text:
Render-to-texture loop with custom mipmap generation.
        The depth renderbuffer is not a mipmap.

        glGenFramebuffers(1, &fb);
        glGenTextures(1, &color_tex);
        glGenRenderbuffers(1, &depth_rb);

        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb);

        // initialize color texture and establish mipmap chain
        glBindTexture(GL_TEXTURE_2D, color_tex);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 512, 512, 0,
                     GL_RGB, GL_INT, NULL);
        glGenerateMipmap(GL_TEXTURE_2D);
        glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
                                  GL_COLOR_ATTACHMENT0,
                                  GL_TEXTURE_2D, color_tex, 0);

        // initialize depth renderbuffer
        glBindRenderbuffer(GL_RENDERBUFFER, depth_rb);
        glRenderbufferStorage(GL_RENDERBUFFER,
                                 GL_DEPTH_COMPONENT24, 512, 512);
        glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER,
                                     GL_DEPTH_ATTACHMENT,
                                     GL_RENDERBUFFER, depth_rb);

        // Check framebuffer completeness at the end of initialization.
        CHECK_FRAMEBUFFER_STATUS();

        loop {
            glBindTexture(GL_TEXTURE_2D, 0);

            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb);
            glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
                                      GL_COLOR_ATTACHMENT0,
                                      GL_TEXTURE_2D, color_tex, 0);
            glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER,
                                         GL_DEPTH_ATTACHMENT,
                                         GL_RENDERBUFFER, depth_rb);

            <draw to the base level of the color texture>

            // custom-generate successive mipmap levels
            glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER,
                                         GL_DEPTH_ATTACHMENT,
                                         GL_RENDERBUFFER, 0);
            glBindTexture(GL_TEXTURE_2D, color_tex);
            foreach (level > 0, in order of increasing values of level) {
                glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
                                          GL_COLOR_ATTACHMENT0,
                                          GL_TEXTURE_2D, color_tex, level);
                glTexParameteri(TEXTURE_2D, TEXTURE_BASE_LEVEL, level-1);
                glTexParameteri(TEXTURE_2D, TEXTURE_MAX_LEVEL, level-1);

                <draw to level>
            }
            glTexParameteri(TEXTURE_2D, TEXTURE_BASE_LEVEL, 0);
            glTexParameteri(TEXTURE_2D, TEXTURE_MAX_LEVEL, max);

            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
            <draw to the window, reading from the color texture>
        }


text:
package io.github.factoryfx.docu.permission;

public class Printer {
    private final String text;

    public Printer(String text) {
        this.text = text;
    }

    public void print() {
        System.out.println(text);
    }
}