text:
<?php

namespace Everon\Test;

class RequestTest extends \Everon\TestCase
{
    protected static $pass = 0;

    /**
     * @var array
     */
    protected $server = [
        'SERVER_PROTOCOL'=> 'HTTP/1.1',
        'REQUEST_METHOD'=> 'GET',
        'REQUEST_URI'=> '/v1/foobars',
        'QUERY_STRING'=> '?foo=bar',
        'SERVER_NAME'=> 'api.localhost',
        'SERVER_PORT'=> 80,
        'SERVER_ADDR'=> '127.0.0.1',
        'REMOTE_ADDR'=> '127.0.0.1',
        'HTTPS'=> 'off'
    ];

    /**
     * @var array
     */
    protected $get = [
        'foo' => 'bar'
    ];

    /**
     * @var array
     */
    protected $post = [
        'id' => null,
        'email' => 'test@grofas.com',
        'password' => 'foobar'
    ];

    /**
     * @var array
     */
    protected $files = [];

    public function setUp()
    {
        ++static::$pass;
    }

    public function testConstructor()
    {
        $Request = new \Everon\Test\MyRequest($this->server, $this->get, $this->post, $this->files);

        $this->assertInstanceOf('\Everon\Interfaces\Request', $Request);
        $this->assertInternalType('array', $Request->getGetCollection()->toArray());
        $this->assertInternalType('array', $Request->getPostCollection()->toArray());
        $this->assertInternalType('array', $Request->getFileCollection()->toArray());
    }

    /**
     * @dataProvider dataProvider
     */
    public function testSettersAndGetters(\Everon\Interfaces\Request $Request, array $expected)
    {
        $this->assertEquals($expected['method'], $Request->getMethod());
        $this->assertEquals($expected['url'], $Request->getUrl());
        $this->assertEquals($expected['location'], $Request->getLocation());
        $this->assertEquals($expected['query_string'], $Request->getQueryString());
        $this->assertEquals($expected['path'], $Request->getPath());
        $this->assertEquals($expected['port'], $Request->getPort());
        $this->assertEquals($expected['protocol'], $Request->getProtocol());
        $this->assertFalse($Request->isSecure());

        $Request->setMethod($expected['method']);
        $Request->setUrl($expected['url']);
        $Request->setQueryString($expected['query_string']);
        $Request->setPath($expected['path']);
        $Request->setPort($expected['port']);
        $Request->setProtocol($expected['protocol']);

        $this->assertEquals($expected['method'], $Request->getMethod());
        $this->assertEquals($expected['url'], $Request->getUrl());
        $this->assertEquals($expected['query_string'], $Request->getQueryString());
        $this->assertEquals($expected['path'], $Request->getPath());
        $this->assertEquals($expected['port'], $Request->getPort());
        $this->assertEquals($expected['protocol'], $Request->getProtocol());
        $this->assertFalse($Request->isSecure());

        $Request->setPostCollection($Request->getPostCollection()->toArray());
        $Request->setGetCollection($Request->getGetCollection()->toArray());
        $Request->setFileCollection($Request->getFileCollection()->toArray());
    }

    /**
     * @dataProvider dataProvider
     */
    public function testIsSecure(\Everon\Interfaces\Request $Request, array $expected)
    {
        $this->assertFalse($Request->isSecure());

        $Server = $Request->getServerCollection()->toArray();
        $Server['HTTPS'] = 'on';
        $Server['SERVER_PORT'] = 443;
        $Request->setServerCollection($Server);
        $this->assertTrue($Request->isSecure());

        $Server = $Request->getServerCollection()->toArray();
        unset($Server['HTTPS']);
        $Server['SSL_HTTPS'] = 'on';
        $Request->setServerCollection($Server);
        $this->assertTrue($Request->isSecure());

        $Server = $Request->getServerCollection()->toArray();
        unset($Server['HTTPS']);
        unset($Server['SSL_HTTPS']);
        $Server['SERVER_PORT'] = 443;
        $Request->setServerCollection($Server);
        $this->assertTrue($Request->isSecure());
    }

    /**
     * @dataProvider dataProvider
     * @expectedException \Everon\Exception\Request
     * @expectedExceptionMessage Missing required parameter: "location"
     */
    public function testValidateShouldThrowExceptionWhenWrongData(\Everon\Interfaces\Request $Request, array $expected)
    {
        $method = $this->getProtectedMethod('\Everon\Request', 'validate');
        $this->assertEquals('', $method->invoke($Request, []));
    }

    /**
     * @dataProvider dataProvider
     * @expectedException \Everon\Exception\Request
     * @expectedExceptionMessage Unrecognized http method: "WRONG"
     */
    public function testValidateShouldThrowExceptionWhenWrongMethod(\Everon\Interfaces\Request $Request, array $expected)
    {
        $method = $this->getProtectedMethod('\Everon\Request', 'validate');
        $this->assertEquals('', $method->invoke($Request, [
            'location' => 'wrong',
            'method'=>'wrong',
            'url'=>'/',
            'query_string'=> '',
            'path' => '',
            'protocol' => '',
            'port' => '',
            'is_secure' => false,
            'is_ajax' => false
        ]));
    }

    /**
     * @dataProvider dataProvider
     */
    public function testGetSetParameters(\Everon\Interfaces\Request $Request, array $expected)
    {
        if (static::$pass === 1) {
            $this->assertEquals($expected['url'], $Request->getUrl());
            $this->assertEquals($expected['post'], $Request->getPostCollection()->toArray());
            $this->assertEquals($expected['post']['login'], $Request->getPostParameter('login'));
            $this->assertEquals($expected['post']['password'], $Request->getPostParameter('password'));
        }

        if (static::$pass === 2) {
            $this->assertEquals($expected['url'], $Request->getUrl());
            $this->assertEquals($expected['get'], $Request->getGetCollection()->toArray());
            $this->assertEquals($expected['get']['param1'], $Request->getQueryParameter('param1'));
            $this->assertEquals($expected['get']['param2'], $Request->getQueryParameter('param2'));
        }

        $this->assertEquals(null, $Request->getQueryParameter('wrong one'));
        $this->assertEquals(null, $Request->getPostParameter('wrong one'));

        $Request->setQueryParameter('test', 1);
        $this->assertEquals(1, $Request->getQueryParameter('test'));

        $Request->setPostParameter('test', 2);
        $this->assertEquals(2, $Request->getPostParameter('test'));
    }

    /**
     * @dataProvider dataProvider
     */
    public function testSanitizeInput(\Everon\Interfaces\Request $Request, array $expected)
    {
        $Server = $Request->getServerCollection()->toArray();
        $Server['REQUEST_URI'] = '<?php //this is wrong; ?>';
        $files = ['test'=> [
            'true' => '<?php phpinfo(); ?>',
            'something' => '//@sadfasd ',
        ]];

        $Request->setFileCollection($files);
        $files = $Request->getFileCollection()->toArray();
        $this->assertInternalType('array', $files);

        $method = $this->getProtectedMethod('\Everon\Request', 'sanitizeInput');
        $this->assertEquals('', $method->invoke($Request, '<?php //test ;?>'));

        $this->assertEquals('', $files['test']['true']);
    }

    /**
     * @dataProvider dataProvider
     */
    public function testGetHostNameFromGlobals(\Everon\Interfaces\Request $Request, array $expected)
    {
        $Server = $Request->getServerCollection()->toArray();
        $Server['HTTP_HOST'] = $Server['SERVER_NAME'];
        unset($Server['SERVER_NAME']);
        $Request->setServerCollection($Server);
        $this->assertEquals($expected['path'], $Request->getPath());

        $Server = $Request->getServerCollection()->toArray();
        unset($Server['HTTP_HOST']);
        unset($Server['SERVER_NAME']);
        $Request->setServerCollection($Server);
        $this->assertEquals($expected['location_fallback'], $Request->getLocation());
    }

    /**
     * @dataProvider dataProvider
     */
    public function testToArray(\Everon\Interfaces\Request $Request, array $expected)
    {
        $this->assertInternalType('array', $Request->toArray());
    }

    /**
     * @dataProvider dataProvider
     */
    public function testIsAjax(\Everon\Interfaces\Request $Request, array $expected)
    {
        $this->assertFalse($Request->isAjax());

        $Server = $Request->getServerCollection()->toArray();
        $Server['X_REQUESTED_WITH'] = 'XmlHttpRequest';
        $Request->setServerCollection($Server);

        $this->assertTrue($Request->isAjax());
    }

    public function dataProvider()
    {
        return [[
            new MyRequest($this->getServerDataForRequest([
                'REQUEST_METHOD' => 'POST',
                'REQUEST_URI' => '/login',
                'QUERY_STRING' => '']),
                [],
                ['login' => 'test',
                    'password' => 'test'],
                []),
            //expected
            [
                'location' => 'http://everon.nova',
                'location_fallback' => 'http://127.0.0.1',
                'url' => 'http://everon.nova/login',
                'path' => '/login',
                'method' => 'POST',
                'query_string' => '',
                'port' => 80,
                'protocol' => 'HTTP/1.1',
                'get' => [],
                'post' => ['login' => 'test', 'password' => 'test'],
                'files' => []
            ]
        ],[
            new MyRequest($this->getServerDataForRequest([
                'REQUEST_METHOD' => 'GET',
                'REQUEST_URI' => '/search?param1=val1&param2=val2',
                'QUERY_STRING' => 'param1=val1&param2=val2']),
                ['param1' => 'val1',
                    'param2' => 'val2'],
                [],
                []),
            //expected
            [
                'location' => 'http://everon.nova',
                'location_fallback' => 'http://127.0.0.1',
                'url' => 'http://everon.nova/search?param1=val1&param2=val2',
                'path' => '/search?param1=val1&param2=val2',
                'method' => 'GET',
                'query_string' => 'param1=val1&param2=val2',
                'port' => 80,
                'protocol' => 'HTTP/1.1',
                'get' => ['param1' => 'val1', 'param2' => 'val2'],
                'post' => [],
                'files' => []
            ]
        ]];
    }

}


text:
package org.ardverk.dht.io;

import java.util.concurrent.TimeUnit;

import org.ardverk.dht.lang.DHTException;
import org.ardverk.dht.rsrc.Key;
import org.ardverk.dht.rsrc.Value;

/**
 * The {@link StoreException} is thrown if a {@link Value} couldn't
 * be stored in the DHT at all.
 */
public class StoreException extends DHTException {

  private static final long serialVersionUID = -1874658787780091708L;

  private final Key key;

  private final Value value;

  public StoreException(Key key, Value value,
      long time, TimeUnit unit) {
    super(time, unit);

    this.key = key;
    this.value = value;
  }

  /**
   * Returns the {@link Key} that failed to be stored.
   */
  public Key getKey() {
    return key;
  }

  /**
   * Returns the {@link Value} that failed to be stored.
   */
  public Value getValue() {
    return value;
  }
}

redpajama_set_name: RedPajamaGithub


text:
app.controller('PlaylistController', ['$scope', '$modal', 'PlaylistProvider', 'ngToast',  function($scope, $modal, PlaylistProvider, ngToast) {
	$scope.playlists = PlaylistProvider.query();
	$scope.new = true;

	$scope.attrs = {
		update: function(e, ui) {
			$scope.new = false;
		}
	};

	$scope.modify = function(playlist) {
		var modifyObject = angular.copy(playlist);
		delete modifyObject.files;
		PlaylistProvider.update({id: playlist.id}, modifyObject);
	};

	/*
	Saves current playlist paths
	*/
	$scope.save = function(playlist) {
		var newOrder = [];
		for (var i = 0; i < playlist.files.length; i++) {
			var e = playlist.files[i];
			newOrder.push(e.id);
		}

		PlaylistProvider.update({id: playlist.id, action: 'paths'}, newOrder);
		$scope.new = true;
	};

	/*
	Adds playlist to queue
	*/
	$scope.add = function(playlist, mode) {
		PlaylistProvider.queue({id: playlist.id, mode: parseInt(mode)}).$promise.then(function(response){
			ngToast.create('Playlist added to queue');
		}, function(error) {
			ngToast.create({
				content: error.data.message,
				className: 'danger'
			});
		});
	};

	$scope.newPlaylist = function() {
		var modal = $modal.open({
			templateUrl: templateUrl + 'newPlaylist_modal.html',
			controller: 'NewPlaylistController',
		});

		modal.result.then(function(playlist) {
			if (undefined !== playlist) {
				$scope.playlists.push(playlist);
			}
		});
	};

	$scope.shuffle = function(playlist) {
		PlaylistProvider.shuffle({id: playlist.id}).$promise.then(function(response) {
			playlist.files = response.files;
		}, function(error) {
			console.error(error);
		});
	};

	$scope.remove = function(playlist, song) {
		PlaylistProvider.removeSong({id: playlist.id, param: song.id}).$promise.then(function(response) {
			var index = playlist.files.indexOf(song);
			playlist.files.splice(index, 1);
		}, function(error) {
			console.error(error);
		});
	};
}]);


text:
package com.github.camaral.sheeco.type.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;

public class SpreadsheetDateAdapter
    implements
        SpreadsheetTypeAdapter<Date>
{
    public static final SimpleDateFormat[] DATE_PATTERNS = {
        new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" ),
        new SimpleDateFormat( "dd/MM/yyyy HH:mm:ss.SSS" )
    };

    @Override
    public Date fromSpreadsheet(
        final Cell cell )
    {
        switch( cell.getCellType() ) {
            case Cell.CELL_TYPE_NUMERIC:
                if( DateUtil.isCellDateFormatted( cell ) ) {
                    return cell.getDateCellValue();
                } else {
                    throw new InvalidCellValueException();
                }
            case Cell.CELL_TYPE_STRING:

                for( final SimpleDateFormat format : DATE_PATTERNS ) {
                    try {
                        return format.parse( cell.getRichStringCellValue().getString().trim() );
                    } catch( final ParseException e ) {
                        continue;
                    }
                }
                throw new InvalidCellValueException();
            case Cell.CELL_TYPE_BLANK:
                return null;
            case Cell.CELL_TYPE_BOOLEAN:
                throw new InvalidCellValueException();
            case Cell.CELL_TYPE_ERROR:
            case Cell.CELL_TYPE_FORMULA:
            default:
                throw new InvalidCellFormatException( "The cell type: " + cell.getCellType()
                    + " is either not supported or not possible" );
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Bundle\ThemeBundle\Templating\Locator;

use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ThemeBundle\Locator\ResourceLocatorInterface;
use Sylius\Bundle\ThemeBundle\Locator\ResourceNotFoundException;
use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;
use Sylius\Bundle\ThemeBundle\Templating\Locator\TemplateLocatorInterface;
use Symfony\Component\Templating\TemplateReferenceInterface;

final class TemplateLocatorSpec extends ObjectBehavior
{
    function let(ResourceLocatorInterface $resourceLocator): void
    {
        $this->beConstructedWith($resourceLocator);
    }

    function it_implements_template_locator_interface(): void
    {
        $this->shouldImplement(TemplateLocatorInterface::class);
    }

    function it_proxies_locating_template_to_resource_locator(
        ResourceLocatorInterface $resourceLocator,
        TemplateReferenceInterface $template,
        ThemeInterface $theme
    ): void {
        $template->getPath()->willReturn('@AcmeBundle/Resources/views/index.html.twig');

        $resourceLocator->locateResource('@AcmeBundle/Resources/views/index.html.twig', $theme)->willReturn('/acme/index.html.twig');

        $this->locateTemplate($template, $theme)->shouldReturn('/acme/index.html.twig');
    }

    function it_does_not_catch_exceptions_thrown_while_locating_template_to_resource_locator_even(
        ResourceLocatorInterface $resourceLocator,
        TemplateReferenceInterface $template,
        ThemeInterface $theme
    ): void {
        $template->getPath()->willReturn('@AcmeBundle/Resources/views/index.html.twig');

        $resourceLocator->locateResource('@AcmeBundle/Resources/views/index.html.twig', $theme)->willThrow(ResourceNotFoundException::class);

        $this->shouldThrow(ResourceNotFoundException::class)->during('locateTemplate', [$template, $theme]);
    }
}


text:
{{ define "main" }}

    <svg class="icon">
        <use xlink:href="{{ .Site.BaseURL }}/img/icons.svg#exclamation-mark"/>
    </svg>

        We're sorry, the page you requested cannot be found

        The URL may be misspelled or the page you're looking for is no longer available

{{ end }}


text:
                    ID
                    {{ Translate::recursive('portfolio::members.name') }}
                    {{ Translate::recursive('portfolio::members.vat_nr') }}
                    {{ Translate::recursive('portfolio::models.address.singular') }}
                    {{ Translate::recursive('portfolio::members.representative') }}
                    {{ Translate::recursive('common.actions') }}

            @foreach( $companies as $company )

                    {{ $company->id }}
                    {!! HTML::linkRoute('admin.companies.show', $company->name, array($company->id)) !!}
                    {!! HTML::linkRoute('admin.companies.show', $company->vat_nr, array($company->id)) !!}
                    {!! HTML::linkRoute('admin.companies.show', $company->corporateAddress->present()->name, array($company->id)) !!}
                    {!! HTML::linkRoute('admin.companies.show', $company->representative->present()->fullName, array($company->id)) !!}

                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                {{ Translate::recursive('common.actions') }}
                            </button>

{!! HTML::iconRoute('admin.companies.edit', Translate::recursive('common.edit'), 'edit', array($company->id), array('class' => 'btn btn-actions pull-left')) !!}

{!! HTML::iconRoute('admin.companies.show', Translate::recursive('common.delete'), 'trash', array($company->id, '_token' => csrf_token()), array('class' => 'btn btn-actions pull-left rest', 'data-method' => 'DELETE')) !!}

            @endforeach

        {!! $companies->render() !!}


text:
module Locomotive
  module Mounter
    module Writer
      module Api

        # Push theme assets to a remote LocomotiveCMS engine.
        #
        # New assets are automatically pushed.
        # Existing ones are not pushed unless the :force option is
        # passed OR if the size of the asset (if not a javascript or stylesheet) has changed.
        #
        class ThemeAssetsWriter < Base

          # Other local attributes
          attr_accessor :tmp_folder

          # store checksums of remote assets. needed to check if an asset has to be updated or not
          attr_accessor :checksums

          # the assets stored in the engine have the same base url
          attr_accessor :remote_base_url

          # cache the compiled theme assets to avoid to perform compilation more than once
          attr_accessor :cached_compiled_assets

          def prepare
            super

            self.checksums = {}

            self.cached_compiled_assets = {}

            # prepare the place where the assets will be stored temporarily.
            self.create_tmp_folder

            # assign an _id to a local content type if possible
            self.get(:theme_assets, nil, true).each do |attributes|
              remote_path = File.join(attributes['folder'], File.basename(attributes['local_path']))

              if theme_asset = self.theme_assets[remote_path]
                theme_asset._id                 = attributes['id']
                self.checksums[theme_asset._id] = attributes['checksum']
              end

              if remote_base_url.nil?
                attributes['url'] =~ /(.*\/sites\/[0-9a-f]+\/theme)/
                self.remote_base_url = $1
              end
            end
          end

          def write
            self.theme_assets_by_priority.each do |theme_asset|
              # track it in the logs
              self.output_resource_op theme_asset

              status  = :skipped
              errors  = []
              file    = self.build_temp_file(theme_asset)
              params  = theme_asset.to_params.merge(source: file, performing_plain_text: false)

              begin
                if theme_asset.persisted?
                  # we only update it if the size has changed or if the force option has been set.
                  if self.force? || self.theme_asset_changed?(theme_asset)
                    response  = self.put :theme_assets, theme_asset._id, params
                    status    = self.response_to_status(response)
                  else
                    status = :same
                  end
                else
                  response  = self.post :theme_assets, params, nil, true
                  status    = self.response_to_status(response)
                end
              rescue Exception => e
                if self.force?
                  status, errors = :error, e.message
                else
                  raise e
                end
              end

              # very important. we do not want a huge number of non-closed file descriptor.
              file.close

              # track the status
              self.output_resource_op_status theme_asset, status, errors
            end

            # make the stuff like they were before
            self.remove_tmp_folder
          end

          protected

          # Create the folder to store temporarily the files.
          #
          def create_tmp_folder
            self.tmp_folder = self.runner.parameters[:tmp_dir] || File.join(Dir.getwd, '.push-tmp')

            FileUtils.mkdir_p(self.tmp_folder)
          end

          # Clean the folder which had stored temporarily the files.
          #
          def remove_tmp_folder
            FileUtils.rm_rf(self.tmp_folder) if self.tmp_folder
          end

          # Build a temp file from a theme asset.
          #
          # @param [ Object ] theme_asset The theme asset
          #
          # @return [ File ] The file descriptor
          #
          def build_temp_file(theme_asset)
            path = File.join(self.tmp_folder, theme_asset.path)

            FileUtils.mkdir_p(File.dirname(path))

            File.open(path, 'w') do |file|
              file.write(self.content_of(theme_asset))
            end

            File.new(path)
          end

          # Shortcut to get all the theme assets.
          #
          # @return [ Hash ] The hash whose key is the slug and the value is the snippet itself
          #
          def theme_assets
            return @theme_assets if @theme_assets

            @theme_assets = {}.tap do |hash|
              self.mounting_point.theme_assets.each do |theme_asset|
                hash[theme_asset.path] = theme_asset
              end
            end
          end

          # List of theme assets sorted by their priority.
          #
          # @return [ Array ] Sorted list of the theme assets
          #
          def theme_assets_by_priority
            self.theme_assets.values.sort { |a, b| a.priority <=> b.priority }
          end

          # Tell if the theme_asset has been changed in order to update it
          # if so or simply skip it.
          #
          # @param [ Object ] theme_asset The theme asset
          #
          # @return [ Boolean ] True if the checksums of the local and remote files are different.
          #
          def theme_asset_changed?(theme_asset)
            content = self.content_of(theme_asset)

            if theme_asset.stylesheet_or_javascript?
              # we need to compare compiled contents (sass, coffeescript) with the right urls inside
              content = content.gsub(/[("'](\/(stylesheets|javascripts|fonts|images|media|others)\/(([^;.]+)\/)*([a-zA-Z_\-0-9]+)\.[a-z]{2,3})[)"']/) do |path|
                sanitized_path = path.gsub(/[("')]/, '').gsub(/^\//, '')
                sanitized_path = File.join(self.remote_base_url, sanitized_path)

                "#{path.first}#{sanitized_path}#{path.last}"
              end
            end

            # compare local checksum with the remote one
            Digest::MD5.hexdigest(content) != self.checksums[theme_asset._id]
          end

          # Return the content of a theme asset.
          # If the theme asset is either a stylesheet or javascript file,
          # it uses Sprockets to compile it.
          # Otherwise, it returns the raw content of the asset.
          #
          # @return [ String ] The content of the theme asset
          #
          def content_of(theme_asset)
            if theme_asset.stylesheet_or_javascript?
              if self.cached_compiled_assets[theme_asset.path].nil?
                self.cached_compiled_assets[theme_asset.path] = self.sprockets[theme_asset.short_path].to_s
              end

              self.cached_compiled_assets[theme_asset.path]
            else
              theme_asset.content
            end
          end

          def sprockets
            Locomotive::Mounter::Extensions::Sprockets.environment(self.mounting_point.path, true)
          end

        end
      end
    end
  end
end


text:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/activity_horizontal_margin"
    android:layout_marginRight="@dimen/activity_horizontal_margin"
    android:layout_marginTop="15dp"
    card_view:cardCornerRadius="1dp"
    card_view:cardElevation="2dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:fontFamily="sans-serif-light"
            android:text="Tank types"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ff6b6b6b" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="20dp">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif-light"
                    android:gravity="center"
                    android:text="Light tanks"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000" />

                <TextView
                    android:id="@+id/wot_tanks_light"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif"
                    android:gravity="center"
                    android:text="XXXX (X%)"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginTop="7dp">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif-light"
                    android:gravity="center"
                    android:text="Medium tanks"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000" />

                <TextView
                    android:id="@+id/wot_tanks_medium"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif"
                    android:gravity="center"
                    android:text="XXXX (X%)"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginTop="7dp">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif-light"
                    android:gravity="center"
                    android:text="Heavy tanks"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000" />

                <TextView
                    android:id="@+id/wot_tanks_heavy"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif"
                    android:gravity="center"
                    android:text="XXXX (X%)"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginTop="7dp">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif-light"
                    android:gravity="center"
                    android:text="Tank Destroyers"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000" />

                <TextView
                    android:id="@+id/wot_tanks_td"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif"
                    android:gravity="center"
                    android:text="XXXX (X%)"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginTop="7dp">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif-light"
                    android:gravity="center"
                    android:text="Artillery"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000" />

                <TextView
                    android:id="@+id/wot_tanks_arty"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:fontFamily="sans-serif"
                    android:gravity="center"
                    android:text="XXXX (X%)"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </TableRow>
        </TableLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Biga, Sydowia 9(1-6): 356 (1955)

#### Original name
Albugo tragopogonis var. pyrethri Cif. & Biga

### Remarks
null


text:
- Intro
	- Static type analysis.. nice build errors!
	- Just typings NOT runtime!
	- Transpiles (Compiles) down to JS
	- Allows us to use JS features of tomorrow
	- If you're familiar with C# or Java you will love it :)
- Typings - boolean, number, void, array, any
	- Optional properties
- Access Modifiers - private, public
- Methods
	- Optional parameters
- Lambda
- Class, interface, enums
	- Creating new object
	- Models
- Template Strings
- For..of
- ES6 Modules
	- Import, export and defaults (default as)
- Properties - get/set
- TypeDoc

## Definitly Typed
NPM module used to download typescript definitions for libraries.
	- Install a package `tsd install jquery --save`
	- Update all  `tsd update -so`
	- Update frequently
	- Commit TSD to source control
	- Custom e.g. _cachefactory

# Advanced/Extra
- Generics
- Union Types
- Type guards
```
export function isAuthError(error: any): error is IAuthError {
	if (error && error.authError) {
		return true;
	}
		return false;
	}
```
- Explain `this`
- String Literals types

# Resources
- Typescript handbook - http://www.typescriptlang.org/Handbook
- Whats New - https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript
- Roadmap (for nerds like me) - https://github.com/Microsoft/TypeScript/wiki/Roadmap


text:
SRC_DIR = src
API_DIR = api
BUILD_DIR = build
IMAGE_DIR = src/images
PYTHON_API_DIR = src/python-api
GH_PAGES_DIR = output

SPHINX_BUILD = sphinx-build
SPHINX_AUTOBUILD = sphinx-autobuild
SPHINX_OPTS = -d $(BUILD_DIR)/doctrees $(SRC_DIR)

# Main targets -----------------------------------------------------------------

.PHONY: all build clean

all: build

build: html

clean:
	rm -rf $(BUILD_DIR) $(PYTHON_API_DIR) $(GH_PAGES_DIR)

# Build specific types of doc---------------------------------------------------

.PHONY: html pdf gh-pages

spelling: api
	$(SPHINX_BUILD) -b spelling $(SPHINX_OPTS) $(BUILD_DIR)/spelling

html: api
	$(SPHINX_BUILD) -b html $(SPHINX_OPTS) $(BUILD_DIR)/html

pdf: api
	$(SPHINX_BUILD) -b latex $(SPHINX_OPTS) $(BUILD_DIR)/pdf
	make -C $(BUILD_DIR)/pdf

gh-pages: api
	rm -rf $(GH_PAGES_DIR)
	$(SPHINX_BUILD) -b html $(SPHINX_OPTS) $(GH_PAGES_DIR)

# API docs ---------------------------------------------------------------------

.PHONY: api python-api

api: check-api python-api

check-api:
	./check-api.py $(API_DIR) services.yaml

python-api:
	./build-api.py $(API_DIR) $(PYTHON_API_DIR)

# Sphinx server on localhost ---------------------------------------------------

.PHONY: serve wait-api-changed sphinx-autobuild

serve: html
	python serve.py

wait-api-changed:
	inotifywait -r -e modify,move,create,delete $(API_DIR)

sphinx-autobuild:
	$(SPHINX_AUTOBUILD) -b html $(SPHINX_OPTS) $(BUILD_DIR)/html


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

namespace Nancy.KeyRockAuthenticationProvider.KeyRock
{
    public class UserInfoResult : UserInformation
    {
        public new int Id { get; set; }
        public int ActorId { get; set; }
        public string NickName { get; set; }
        public string DisplayName { get; set; }
        public new string Email { get; set; }
        public List<Role> Roles { get; set; }
        public List<Organization> Organizations { get; set; }
    }

    public class Role
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Organization
    {
        public int Id { get; set; }
        public int ActorId { get; set; }
        public string DisplayName { get; set; }
        public List<Role> Roles { get; set; }
    }
}


text:
# UINavigationController

- 设置背景图片

```objc
#pragma mark - 设置导航栏默认背景
- (void)setNavigationBarBackgroundImage
{
    UIImage *img;
    if(IOS7_OR_LATER)
    {
        img = [UIImage imageNamed:@"userinfo_navBg128"];
    }
    else
    {
        img = [UIImage imageNamed:@"userinfo_navBg88"];
    }

    UIEdgeInsets edge = UIEdgeInsetsMake(0, 0, 0, 0);
    img = [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeTile];
    [self.navigationController.navigationBar setBackgroundImage:img
                                                  forBarMetrics:UIBarMetricsDefault];
}
```

## 导航控制器跨级跳转
- O -> A -> B 变成 O -> B
- 意思就是在通过A中创建B,然后把A pop,再通过导航控制器push B
- 在O中通过代理监听B的创建时刻,将事件传递到O,在O中先pop,然后pushB

- A/B

```objc
//
//  ChatpanelViewController.h
//  SLQScrollView
//
//  Created by Christian on 15/11/12.
//  Copyright © 2015年 songlq. All rights reserved.
//

#import "ViewController.h"

@class ChatpanelViewController;
@protocol ChatpanelViewControllerDelegate <NSObject>

@optional
- (void)chatpanelViewControllerDidClickPushBtn:(ChatpanelViewController *)newVc andPreviousVC:(ChatpanelViewController *)preVC;
- (void)chatpanelViewControllerDidClickPushBtn:(ChatpanelViewController *)newVc;
@end

@interface ChatpanelViewController : ViewController
/***/
@property (nonatomic, weak) id<ChatpanelViewControllerDelegate> delegate;
/**c*/

@end

//
//  ChatpanelViewController.m
//  SLQScrollView
//
//  Created by Christian on 15/11/12.
//  Copyright © 2015年 songlq. All rights reserved.
//

#import "ChatpanelViewController.h"
#import "SLQScrollView.h"

@implementation ChatpanelViewController

- (void)dealloc
{
    NSLog(@"dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
    SLQScrollView *fatherView = [[SLQScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 44)];
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 100 + 1;
//    btn.enabled = NO;
//    btn.userInteractionEnabled = NO;
    [fatherView addSubview:btn];
    [self.view addSubview:fatherView];

}

- (void)btnClick:(UIButton *)btn
{
    if ([self.delegate respondsToSelector:@selector(chatpanelViewControllerDidClickPushBtn:)]) {
        ChatpanelViewController *newVC = [[ChatpanelViewController alloc] init];
        [self.delegate chatpanelViewControllerDidClickPushBtn:newVC];
    }
}

@end
```

```objc
//
//  ViewController.m
//  SLQScrollView
//
//  Created by songlq on 15/10/27.
//  Copyright (c) 2015年 songlq. All rights reserved.
//

#import "ViewController.h"
#import "SLQScrollView.h"
#import "ChatpanelViewController.h"

@interface ViewController () <ChatpanelViewControllerDelegate>

@property (nonatomic,strong) CADisplayLink *displayLink;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic, weak) ChatpanelViewController *currentVC;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    SLQScrollView *fatherView = [[SLQScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    fatherView.backgroundColor = [UIColor redColor];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 44)];
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 100 + 1;
//    btn.enabled = NO;
//    btn.userInteractionEnabled = NO;
    [fatherView addSubview:btn];
    [self.view addSubview:fatherView];

}
- (void)btnClick:(UIButton *)btn
{
    NSLog(@"btnClick");
    ChatpanelViewController *vc = [[ChatpanelViewController alloc] init];
//    self.currentVC = vc;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)chatpanelViewControllerDidClickPushBtn:(ChatpanelViewController *)newVc
{
    [self.navigationController popViewControllerAnimated:YES];
    newVc.delegate = self;
    [self.navigationController pushViewController:newVc animated:YES];
}
//- (void)chatpanelViewControllerDidClickPushBtn:(ChatpanelViewController *)newVc andPreviousVC:(ChatpanelViewController *)preVC
//{
//    [self.navigationController popViewControllerAnimated:YES];
//    newVc.delegate = self;
//    [self.navigationController pushViewController:newVc animated:YES];
////    self.currentVC = newVc;
//}

@end
```

## 重构导航栈

```objc
NSMutableArray * viewControllers = [self.navigationController.viewControllers mutableCopy];
[viewControllers removeLastObject];
[viewControllers addObject:newController];

[self.navigationController setViewControllers:viewControllers animated:YES];
```


text:
/**
 * @flow
 */

'use strict';

import Realm from 'realm';
import Schema from './schema';

function configureRealm() {
  var schema = new Schema();

  var next = Realm.schemaVersion(Realm.defaultPath);
  if (next > 0) {
    while (next < schema.schemas.length) {
      var migratedSchema = schema.schemas[next++];
      var migratedRealm = new Realm(migratedSchema);
      migratedRealm.close();
    }
  }

  var current = schema.current();
  var realm = new Realm(current);
  realm.close();
}

module.exports = configureRealm;


text:
<mvc:View
	controllerName="sap.m.sample.IconTabBarDragDrop.C"
	xmlns="sap.m"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:f="sap.ui.layout.form">
	<f:SimpleForm
		layout="ResponsiveGridLayout"
		editable="true"
		adjustLabelSpan="false"
		labelSpanXL="2"
		labelSpanL="2"
		labelSpanM="3"
		labelSpanS="5">
		<Label text="Maximum Nesting Level" />
		<StepInput
			value="0"
			min="0"
			max="100"
			step="1"
			width="120px"
			change=".onMaxNestingLevelChange" />
	</f:SimpleForm>

	<IconTabBar
		id="idIconTabBar"
		enableTabReordering="true"
		class="sapUiResponsiveContentPadding">
	</IconTabBar>
</mvc:View>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2021 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<!-- 'Yes' button -->
<org.chromium.ui.widget.ButtonCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button_init_ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:gravity="center"
    android:text="@string/init_ok"
    android:contentDescription="@string/init_ok"
    style="@style/FilledButton.Flat" />


text:
define(function (require) {
    var suite = require('intern!object');
    var parameterConverter = require('intern/dojo/node!../../src/parameterConverter');
    var expect = require('intern/chai!expect');

    suite({
        'should convert to integer parameter': function () {
            expect(parameterConverter.convert('12345', {type:'integer', format:'int32'})).to.eql(12345);
        },
        'should convert to long parameter': function () {
            expect(parameterConverter.convert('12345', {type:'integer', format:'int64'})).to.eql(12345);
        },
        'should convert to float parameter': function () {
            expect(parameterConverter.convert('12.345', {type:'number', format:'float'})).to.eql(12.345);
        },
        'should convert to double parameter': function () {
            expect(parameterConverter.convert('12.345', {type:'number', format:'double'})).to.eql(12.345);
        },
        'should convert string parameter': function () {
            expect(parameterConverter.convert('abc', {type:'string'})).to.eql("abc");
        },
        'should convert byte parameter': function () {
            expect(parameterConverter.convert('abc', {type:'string', format:'byte'})).to.eql("abc");
        },
        'should convert boolean parameter': function () {
            expect(parameterConverter.convert('true', {type:'boolean'})).to.eql(true);
        },
        'should convert date parameter': function () {
            expect(parameterConverter.convert('2015-09-29', {type:'string', format:'date'})).to.eql(new Date('2015-09-29'));
        },
        'should convert dateTime parameter': function () {
            expect(parameterConverter.convert('2015-09-29T23:59:59', {type:'string', format:'date-time'})).to.eql(new Date('2015-09-29T23:59:59'));
        },
        'should throw exception when configuration not found': function () {
            try {
                parameterConverter.convert('abc', {type:'aaa', format:'bbb'});
            } catch (e) {
                expect(e).is.eql('Could not convert value: abc, for type: aaa, format: bbb, items: undefined, collectionFormat: undefined');
            }
        },
        'should convert csv array': function () {
            expect(parameterConverter.convert("foo,bar", {
                "name": "tags",
                "in": "query",
                "type": "array",
                "items": {
                    "type": "string"
                }
            })).to.eql(['foo', 'bar']);
        },
        'should convert ssv array': function () {
            expect(parameterConverter.convert("foo bar", {
                "name": "tags",
                "in": "query",
                "type": "array",
                "items": {
                    "type": "string"
                },
                collectionFormat: 'ssv'
            })).to.eql(['foo', 'bar']);
        },
        'should convert tsv array': function () {
            expect(parameterConverter.convert("foo\tbar", {
                "name": "tags",
                "in": "query",
                "type": "array",
                "items": {
                    "type": "string"
                },
                collectionFormat: 'tsv'
            })).to.eql(['foo', 'bar']);
        },
        'should convert pipes array': function () {
            expect(parameterConverter.convert("foo|bar", {
                "name": "tags",
                "in": "query",
                "type": "array",
                "items": {
                    "type": "string"
                },
                collectionFormat: 'pipes'
            })).to.eql(['foo', 'bar']);
        },
        'should throw exception when unknown collectionFormatwhile converting array': function () {
            try {
                parameterConverter.convert("foo|bar", {
                    "name": "tags",
                    "in": "query",
                    "type": "array",
                    "items": {
                        "type": "string"
                    },
                    collectionFormat: 'aaa'
                });
                expect.fail('expect exception to be thrown');
            }catch(e){
                expect(e).to.not.null;
            }
        },
        'should convert to integer array': function () {
            expect(parameterConverter.convert("123,456", {
                "name": "tags",
                "in": "query",
                "type": "array",
                "items": {
                    "type": "integer",
                    "format": "int32"
                }
            })).to.eql([123, 456]);
        }
    });
});


text:
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        heights.push_back(0);
        int max = 0;
        stack<int> indexStack;
        for (int index = 0; index < heights.size(); index++) {
            while (!indexStack.empty() && heights[indexStack.top()] >= heights[index]) {
                int high = heights[indexStack.top()];
                indexStack.pop();
                int res = indexStack.empty() ? -1 : indexStack.top();
                max = max > high * (index - res - 1) ? max : high * (index - res - 1);
            }
            indexStack.push(index);
        }
        return max;
    }
};


text:
<title>Editing Test</title>

a lincoln


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>fredhopper-ecommerce-connector</artifactId>

    <parent>
        <artifactId>ecommerce-connectors</artifactId>
        <groupId>com.sdl</groupId>
        <version>1.1.0</version>
	<relativePath>../pom.xml</relativePath>
    </parent>

    <properties>
        <fredhopper-api-version>7.5.2.9</fredhopper-api-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.sdl</groupId>
            <artifactId>ecommerce-framework-api</artifactId>
            <version>${project.version}</version>
        </dependency>

        <!-- Fredhopper API -->
        <dependency>
            <groupId>com.fredhopper</groupId>
            <artifactId>ws-client</artifactId>
            <version>${fredhopper-api-version}</version>
        </dependency>

        <dependency>
            <groupId>com.fredhopper</groupId>
            <artifactId>query-lang</artifactId>
            <version>${fredhopper-api-version}</version>
        </dependency>

        <!-- Servlet API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>integration-test</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <includes>
                                <include>**/*IT.java</include>
                            </includes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
<?
# $Id: index2.php,v 1.9 2005/10/28 17:59:41 thomasek Exp $ index2.php,v 1.8 2001/12/02 09:19:50 thomasek Exp $
# Based on EasyComposer technology
# Copyright Thomas Ekdahl, 1994-2005, thomas@ekdahl.no, http://www.ekdahl.no

#sleep(2);

$interf = $_REQUEST['interf'];
?>
<? print $_lib['sess']->doctype ?>

    <title>Empatix - <? print $_SESSION['DB_NAME'] ?> - <? print "$interface"; ?> - <? print $_lib['sess']->get_person('UserName') ?></title>
    <meta name="cvs"                content="$Id: index2.php,v 1.9 2005/10/28 17:59:41 thomasek Exp $" />
    <? require_once $_SETUP['HOME_DIR'] . "/code/lib/html/head.inc"; ?>

Teknisk grensesnitt

<a href="<? print $_lib['sess']->dispatch ?>t=confdbfield.list">Confdbfield

<a href="<? print $_lib['sess']->dispatch ?>t=urlalias.list">URLAlias

<a href="<? print $_lib['sess']->dispatch ?>t=language.interface">Language

<a href="<? print $_lib['sess']->dispatch ?>t=conflayout.list">Conflayout

<a href="<? print $_lib['sess']->dispatch ?>t=sync.list">Sync

<a href="<? print $_lib['sess']->dispatch ?>t=menu.list">Menu

<a href="<? print $_lib['sess']->dispatch ?>t=tab.list">Tab

<a href="<? print $_lib['sess']->dispatch ?>t=database.list">Database management

<a href="<? print $_lib['sess']->dispatch ?>t=integration.list">Integrations

Ikke IMPLEMENTERT:

<a href="<? print $_lib['sess']->dispatch ?>t=fileupload.list">Fileupload

<a href="<? print $_lib['sess']->dispatch ?>t=log.list">Log

<a href="<? print $_lib['sess']->dispatch ?>t=misc.list">Misc

<a href="<? print $_lib['sess']->dispatch ?>t=rules.list">Rules

<a href="<? print $_lib['sess']->dispatch ?>t=signatures.list">Signatures

<a href="<? print $_lib['sess']->dispatch ?>t=templaterestrictioons">Templaterestrictions

<a href="<? print $_lib['sess']->dispatch ?>t=conditions.index">Conditions


text:
#include "../ecdaa-test-utils.h"
#include "tpm_ZZZ-test-utils.h"

#include "amcl-extensions/big_XXX.h"
#include "amcl-extensions/ecp_ZZZ.h"
#include "amcl-extensions/ecp2_ZZZ.h"
#include "schnorr-tpm/schnorr_TPM_ZZZ.h"
#include "schnorr/schnorr_ZZZ.h"

#include <ecdaa-tpm/member_keypair_TPM_ZZZ.h>
#include <ecdaa/credential_ZZZ.h>
#include <ecdaa/issuer_keypair_ZZZ.h>
#include <ecdaa-tpm/signature_TPM_ZZZ.h>
#include <ecdaa/group_public_key_ZZZ.h>
#include <ecdaa/revocations_ZZZ.h>
#include <ecdaa-tpm/tpm_context.h>

#include <string.h>

#include <sys/time.h>

static void sign_then_verify_good();
static void sign_then_verify_bad_basename_fails();
static void sign_then_verify_no_basename();
static void sign_then_verify_unlinkable();

typedef struct sign_and_verify_fixture {
    uint8_t *msg;
    uint32_t msg_len;
    uint8_t *basename;
    uint32_t basename_len;
    struct ecdaa_revocations_ZZZ revocations;
    struct ecdaa_member_public_key_ZZZ pk;
    struct ecdaa_member_secret_key_ZZZ sk;
    struct ecdaa_issuer_public_key_ZZZ ipk;
    struct ecdaa_issuer_secret_key_ZZZ isk;
    struct ecdaa_credential_ZZZ cred;
    struct tpm_test_context tpm_ctx;
} sign_and_verify_fixture;

static void setup(sign_and_verify_fixture* fixture);
static void teardown(sign_and_verify_fixture *fixture);

int main()
{
    sign_then_verify_good();
    sign_then_verify_bad_basename_fails();
    sign_then_verify_no_basename();
    sign_then_verify_unlinkable();
}

static void setup(sign_and_verify_fixture* fixture)
{
    TEST_ASSERT(0 == tpm_initialize(&fixture->tpm_ctx));

    ecp_ZZZ_random_mod_order(&fixture->isk.x, test_randomness);
    ecp2_ZZZ_set_to_generator(&fixture->ipk.gpk.X);
    ECP2_ZZZ_mul(&fixture->ipk.gpk.X, fixture->isk.x);

    ecp_ZZZ_random_mod_order(&fixture->isk.y, test_randomness);
    ecp2_ZZZ_set_to_generator(&fixture->ipk.gpk.Y);
    ECP2_ZZZ_mul(&fixture->ipk.gpk.Y, fixture->isk.y);

    uint8_t *nonce = (uint8_t*)"nonce";
    uint32_t nonce_len = 5;
    TEST_ASSERT(0 == ecdaa_member_key_pair_TPM_ZZZ_generate(&fixture->pk, fixture->tpm_ctx.serialized_public_key, nonce, nonce_len, &fixture->tpm_ctx.tpm_ctx));

    struct ecdaa_credential_ZZZ_signature cred_sig;
    ecdaa_credential_ZZZ_generate(&fixture->cred, &cred_sig, &fixture->isk, &fixture->pk, test_randomness);

    fixture->msg = (uint8_t*) "Test message";
    fixture->msg_len = (uint32_t)strlen((char*)fixture->msg);

    fixture->basename = (uint8_t*) "BASENAME";
    fixture->basename_len = (uint32_t)strlen((char*)fixture->basename);

    fixture->revocations.sk_length=0;
    fixture->revocations.sk_list=NULL;
    fixture->revocations.bsn_length=0;
    fixture->revocations.bsn_list=NULL;
}

static void teardown(sign_and_verify_fixture *fixture)
{
    (void)fixture;
    tpm_cleanup(&fixture->tpm_ctx);
}

static void sign_then_verify_good()
{
    printf("Starting signature_TPM_ZZZ::sign_then_verify_good...\n");

    sign_and_verify_fixture fixture;
    setup(&fixture);

    struct ecdaa_signature_ZZZ sig;
    TEST_ASSERT(0 == ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, fixture.basename, fixture.basename_len, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));

    TEST_ASSERT(0 == ecdaa_signature_ZZZ_verify(&sig, &fixture.ipk.gpk, &fixture.revocations, fixture.msg, fixture.msg_len, fixture.basename, fixture.basename_len));

    teardown(&fixture);

    printf("\tsuccess\n");
}

static void sign_then_verify_bad_basename_fails()
{
    printf("Starting signature_TPM_ZZZ::sign_then_verify_bad_basename_fails...\n");

    sign_and_verify_fixture fixture;
    setup(&fixture);

    uint8_t *wrong_basename = (uint8_t*) "WRONGBASENAME";
    uint32_t wrong_basename_len = strlen((char*)wrong_basename);

    struct ecdaa_signature_ZZZ sig;
    TEST_ASSERT(0 == ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, fixture.basename, fixture.basename_len, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));

    TEST_ASSERT(0 != ecdaa_signature_ZZZ_verify(&sig, &fixture.ipk.gpk, &fixture.revocations, fixture.msg, fixture.msg_len, wrong_basename, wrong_basename_len));

    teardown(&fixture);

    printf("\tsuccess\n");
}

static void sign_then_verify_no_basename()
{
    printf("Starting signature_TPM_ZZZ::sign_then_verify_no_basename...\n");

    sign_and_verify_fixture fixture;
    setup(&fixture);

    struct ecdaa_signature_ZZZ sig;
    TEST_ASSERT(0 == ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, fixture.basename, fixture.basename_len, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));

    TEST_ASSERT(0 != ecdaa_signature_ZZZ_verify(&sig, &fixture.ipk.gpk, &fixture.revocations, fixture.msg, fixture.msg_len, NULL, 0));

    teardown(&fixture);

    printf("\tsuccess\n");
}

static void sign_then_verify_unlinkable()
{
    printf("Starting signature_TPM_ZZZ::sign_then_verify_unlinkable...\n");

    sign_and_verify_fixture fixture;
    setup(&fixture);

    struct ecdaa_signature_ZZZ sig;
    // non-NULL basename, 0 basename_length
    TEST_ASSERT(0 != ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, fixture.basename, 0, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));
    // NULL basename, non-0 basename_length
    TEST_ASSERT(0 != ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, NULL, fixture.basename_len, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));

    // NULL basename, 0 basename_length
    TEST_ASSERT(0 == ecdaa_signature_TPM_ZZZ_sign(&sig, fixture.msg, fixture.msg_len, NULL, 0, &fixture.cred, test_randomness, &fixture.tpm_ctx.tpm_ctx));

    TEST_ASSERT(0 == ecdaa_signature_ZZZ_verify(&sig, &fixture.ipk.gpk, &fixture.revocations, fixture.msg, fixture.msg_len, NULL, 0));

    // NULL basename, non-0 basename_length
    TEST_ASSERT(0 != ecdaa_signature_ZZZ_verify(&sig, &fixture.ipk.gpk, &fixture.revocations, fixture.msg, fixture.msg_len, NULL, fixture.basename_len));

    teardown(&fixture);

    printf("\tsuccess\n");
}


text:
<?php

namespace Predis\Command;

/**
 * @link http://redis.io/commands/slaveof
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ServerSlaveOf extends AbstractCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'SLAVEOF';
    }

    /**
     * {@inheritdoc}
     */
    protected function filterArguments(Array $arguments)
    {
        if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
            return array('NO', 'ONE');
        }

        return $arguments;
    }
}


text:
#include "policy/update_status_manager.h"
#include "gtest/gtest.h"
#include "policy/mock_policy_listener.h"
#include "policy/policy_manager_impl.h"

namespace test {
namespace components {
namespace policy_test {

using namespace ::policy;
using ::testing::_;
using ::testing::Return;

class UpdateStatusManagerTest : public ::testing::Test {
 protected:
  std::shared_ptr<UpdateStatusManager> manager_;
  std::shared_ptr<MockPolicyListener> listener_;

 public:
  UpdateStatusManagerTest()
      : manager_(std::make_shared<UpdateStatusManager>())
      , listener_(std::make_shared<MockPolicyListener>()) {}

  void SetUp() OVERRIDE {
    manager_->set_listener(listener_.get());
    ON_CALL(*listener_, OnUpdateStatusChanged(_)).WillByDefault(Return());
  }

  void TearDown() OVERRIDE {}
};

TEST_F(UpdateStatusManagerTest,
       OnAppSearchStartedCompleted_ExpectAppSearchCorrectStatus) {
  // Arrange
  manager_->OnAppsSearchStarted();
  // Check
  EXPECT_TRUE(manager_->IsAppsSearchInProgress());
  // Arrange
  manager_->OnAppsSearchCompleted();
  // Check
  EXPECT_FALSE(manager_->IsAppsSearchInProgress());
}

}  // namespace policy_test
}  // namespace components
}  // namespace test


text:
<?php
namespace Ilcfrance\StagiairePassportBundle\Form\Role;

use Ilcfrance\DataBundle\OrmRepository\RoleRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Ilcfrance\DataBundle\OrmEntity\Role;

/**
 *
 * @author sasedev <seif.salah@gmail.com>
 */
class UpdateParentsTForm extends AbstractType
{

	/**
	 *
	 * @var Role
	 */
	private $role;

	/**
	 * Form builder
	 *
	 * @param FormBuilderInterface $builder
	 * @param array $options
	 *
	 * @return null
	 */
	public function buildForm(FormBuilderInterface $builder, array $options)
	{
		$this->role = $options['role'];
		$role = $this->role;

		$builder->add('parents', EntityType::class, array(
			'label' => 'Role.parents.label',
			'class' => 'IlcfranceDataBundle:Role',
			'query_builder' => function (RoleRepository $rr) use ($role) {
				return $rr->createQueryBuilder('r')->where('r.id != :id')->setParameter('id', $role->getId())->orderBy('r.id', 'ASC');
			},
			'choice_label' => 'id',
			'multiple' => true,
			'by_reference' => false,
			'required' => false
		));
	}

	/**
	 *
	 * {@inheritdoc} @see FormTypeInterface::getName()
	 * @return string
	 */
	public function getName()
	{
		return 'RoleUpdateParentsForm';
	}

	/**
	 *
	 * {@inheritdoc} @see AbstractType::getBlockPrefix()
	 */
	public function getBlockPrefix()
	{
		return $this->getName();
	}

	/**
	 * get the default options
	 *
	 * @return multitype:string multitype:string
	 */
	public function getDefaultOptions()
	{
		return array(
			'validation_groups' => array(
				'id',
				'description'
			),
			'role' => null
		);
	}

	/**
	 *
	 * {@inheritdoc} @see AbstractType::configureOptions()
	 */
	public function configureOptions(OptionsResolver $resolver)
	{
		$resolver->setDefaults($this->getDefaultOptions());
	}
}


text:
/**
 * Angular scrollin
 * An angularjs directive to add a class as the user scrolls down the page
 *
 *
 */
angular.module('angular-scrollin', [])
    .directive('ilnScrollIn', [
        '$window',
        function ( $window ) {
        return {
            restrict: 'A',
            link:   function ( scope, elm, attrs ) {

                var elementPositionTop      = elm[0].getBoundingClientRect().top;
                var elementPositionOffset   = attrs.scrollInOffset || 0.75;
                var elementPositionClass    = attrs.scrollInClass || 'active';

                // bind scroll listner to the window
                angular.element($window).bind('scroll', function () {

                    elementPositionTop      = elm[0].getBoundingClientRect().top;

                    if( elementPositionTop <= $window.innerHeight * elementPositionOffset ){
                        elm.addClass( elementPositionClass );
                    }

                    scope.$apply();
                });

            }
        };
    }]);


text:
package gui.tabs;

import static syncrop.Syncrop.logger;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import gui.SyncropGUI;
import listener.FileWatcher;
import listener.actions.RemoveSyncropConflictsAction;

public class Optimization extends JPanel implements SyncropTab,ActionListener{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	JButton removeFileInfo=new JButton("Remove metadata for disabled and deleted files");
	JButton removeConflicts=new JButton("Remove conflicts locally ");
	JButton forceSync=new JButton("Force Sync");

	public Optimization(){
		setName("Optimization");
		initialize();
	}
	private void initialize(){
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		JButton[] optimizations={removeFileInfo,removeConflicts,forceSync};

		for(JButton optimization:optimizations){
			add(optimization);
			optimization.addActionListener(this);
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(removeFileInfo))
			try {
				FileWatcher.checkMetadataForAllFiles(false);
			} catch (IOException e1) {
				logger.logError(e1);
			}
		else if(e.getSource().equals(removeConflicts))
			try {
				new FileWatcher(null).checkAllFiles(new RemoveSyncropConflictsAction());
			} catch (IOException e1) {
				logger.logError(e1);
			}
		else if(e.getSource().equals(forceSync))
			try {
				SyncropGUI.getSyncropCommunicationThread().sync(true);
			} catch (IOException e1) {
				e1.printStackTrace();
			}

	}

	@Override
	public void reload() {
		forceSync.setEnabled(SyncropGUI.getSyncropCommunicationThread().isSyncropRunning());
	}
}


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>se.litsec.eidas.opensaml.ext (eIDAS extension for OpenSAML 3.x - 1.3.2)</title>
<meta name="date" content="2019-01-10">
<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 Package

Next Package

Frames

No Frames

All Classes

Package se.litsec.eidas.opensaml.ext

Interfaces and classes representing eIDAS extension elements.

See: Description

Interface Summary

Interface
Description

NodeCountry

* The eIDAS <eidas:NodeCountry> element.

RequestedAttribute

The eIDAS <eidas:RequestedAttribute> element.

RequestedAttributes

The eIDAS <eidas:RequestedAttributes> element.

SPType

The eIDAS <eidas:SPType> element.

Class Summary

Class
Description

RequestedAttributeTemplates

Utility methods for use when RequestedAttribute elements are inserted in an AuthnRequest extension.

SPTypeEnumeration

A type safe enumeration of the <eidas:SPType> element.

Package se.litsec.eidas.opensaml.ext Description

Interfaces and classes representing eIDAS extension elements.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2019 Litsec AB. All rights reserved.


text:
package edu.mit.media.funf.storage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import edu.mit.media.funf.opp.OppProbe;

public class NameValueProbeDataListener extends BroadcastReceiver {

	private final String databaseName;
	private final Class<? extends DatabaseService> databaseServiceClass;
	private final BundleSerializer bundleSerializer;

	public NameValueProbeDataListener(String databaseName, Class<? extends DatabaseService> databaseServiceClass, BundleSerializer bundleSerializer) {
		this.databaseName = databaseName;
		this.databaseServiceClass = databaseServiceClass;
		this.bundleSerializer = bundleSerializer;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (OppProbe.isDataAction(action)) {
			String dataJson = bundleSerializer.serialize(intent.getExtras());
			String probeName = OppProbe.getProbeName(action);
			long timestamp = intent.getLongExtra("TIMESTAMP", 0L);
			Bundle b = new Bundle();
			b.putString(NameValueDatabaseService.DATABASE_NAME_KEY, databaseName);
			b.putLong(NameValueDatabaseService.TIMESTAMP_KEY, timestamp);
			b.putString(NameValueDatabaseService.NAME_KEY, probeName);
			b.putString(NameValueDatabaseService.VALUE_KEY, dataJson);
			Intent i = new Intent(context, databaseServiceClass);
			i.setAction(DatabaseService.ACTION_RECORD);
			i.putExtras(b);
			context.startService(i);
		}
	}
}


text:
Database Basics: How to Make Boring Data Awesome (or at least, less boring)
  The main players,
  online servers,
  your Excel box and Google spreadsheets, numbers
  rows and columns excel
  data formats: float, string, JSON CSV etc.


text:
package de.logicline.splash.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ApiOriginFilter implements Filter {

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse) response;
		res.addHeader("Access-Control-Allow-Origin", "*");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		res.addHeader("Access-Control-Allow-Headers", "Content-Type, token");
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException { }

	public void destroy() { }

}


text:
Tworzenie formularzy
====================

Formularze oparte na ActiveRecord: ActiveForm
---------------------------------------------
Podstawowym sposobem korzystania z formularzy w Yii jest użycie [[yii\widgets\ActiveForm|ActiveForm]]. Ten sposób powinien być używany, jeśli formularz jest bazowany na modelu.
Dodatkowo, klasa [[yii\helpers\Html|Html]] zawiera sporo użytecznych metod, które zazwyczaj używane są do dodawania przycisków i tekstów pomocniczych do każdego formularza.

Formularz, który jest wyświetlany po stronie klienta, w większości przypadków, posiada odpowiedni [model](structure-models.md), który jest używany do walidacji danych wejściowych po
stronie serwera (sprawdź sekcję [Walidacja danych wejściowych](input-validation.md) aby uzyskać więcej szczegółów).
Podczas tworzenia formularza na podstawie modelu, pierwszym krokiem jest zdefiniowanie samego modelu.
Model może być bazowany na klasie [Active Record](db-active-record.md), reprezentując dane z bazy danych, lub może być też bazowany na klasie generycznej [[yii\base\Model|Model]],
aby przechwytywać dowolne dane wejściowe, np. formularz logowania.

> Tip: Jeśli pola formularza są różne od kolumn tabeli w bazie danych lub też występuje tu formatowanie i logika specyficzna tylko dla tego formularza,
> zaleca się stworzenie oddzielnego modelu rozszerzającego [[yii\base\Model]].

W poniższym przykładzie pokażemy, jak model generyczny może być użyty do stworzenia formularza logowania:

```php
<?php

class LoginForm extends \yii\base\Model
{
    public $username;
    public $password;

    public function rules()
    {
        return [
            // zasady walidacji
        ];
    }
}
```

W kontrolerze przekażemy instancję tego modelu do widoku, gdzie widżet [[yii\widgets\ActiveForm|ActiveForm]] zostanie użyty do wyświetlenia formularza:

```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>
```

### Otaczanie kodu przez `begin()` i `end()`
W powyższym kodzie, [[yii\widgets\ActiveForm::begin()|begin()]] nie tylko tworzy instancję formularza, ale zaznacza też jego początek.
Cała zawartość położona pomiędzy [[yii\widgets\ActiveForm::begin()|begin()]] i [[yii\widgets\ActiveForm::end()|end()]] zostanie otoczona tagiem HTML'owym `<form>`.
Jak w przypadku każdego widżetu, możesz określić kilka opcji z jakimi widżet powinien być skonfigurowany przez przekazanie tablicy do metody `begin`.
W tym przypadku dodatkowa klasa CSS i identyfikator ID zostały przekazane do otwierającego tagu `<form>`.
Aby zobaczyć wszystkie dostępne opcje, zajrzyj do dokumentacji API [[yii\widgets\ActiveForm|ActiveForm]].

Do utworzenia formularza, wraz z elementami etykiet oraz wszelkimi walidacjami JavaScript, wywoływana jest metoda [[yii\widgets\ActiveForm::field()|field()]], która zwraca instancję
obiektu [[yii\widgets\ActiveField|ActiveField]].
Kiedy rezultat tej metody jest bezpośrednio wyświetlany, tworzone jest regularne pole tekstowe.
Aby dostosować pola, możesz używać dodatkowych metod łączonych [[yii\widgets\ActiveField|ActiveField]]:

```php
// pole hasła
<?= $form->field($model, 'password')->passwordInput() ?>
// dodanie podpowiedzi oraz zmiana etykiety
<?= $form->field($model, 'username')->textInput()->hint('Please enter your name')->label('Name') ?>
// utworzenie pola email w formacie HTML5
<?= $form->field($model, 'email')->input('email') ?>
```

Powyższy kod utworzy tagi `<label>`, `<input>` oraz wszystkie inne, według pól formularza zdefiniowanych w [[yii\widgets\ActiveField::$template|template]].
Nazwa pola określana jest automatycznie z modelu [[yii\base\Model::formName()|formName()]] i nazwy atrybutu.
Dla przykładu, nazwą pola dla atrybutu `username` w powyższym przykładzie będzie `LoginForm[username]`.
Ta zasada nazewnictwa spowoduje, że tablica wszystkich atrybutów z formularza logowania będzie dostępna w zmiennej `$_POST['LoginForm']` po stronie serwera.

Określanie atrybutów modelu może być wykonane w bardziej wyrafinowany sposób.
Dla przykładu, kiedy atrybut będzie potrzebował pobierać tablicę wartości, podczas przesyłania wielu plików lub wybrania wielu pozycji, możesz określić go jako tablicę dodając `[]` do
nazwy atrybutu:

```php
// pozwól na przesłanie wielu plików
echo $form->field($model, 'uploadFile[]')->fileInput(['multiple'=>'multiple']);

// pozwól na zaznaczenie wielu pozycji
echo $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
```

Bądź ostrożny podczas nazywania elementów formularza takich jak przyciski wysyłania.
Odnosząc się do [dokumentacji jQuery](https://api.jquery.com/submit), istnieje kilka zarezerwowanych nazw, które mogą powodować konflikty.

> Formularz i jego elementy podrzędne powinny nie używać nazw pól lub nazw identyfikatorów które tworzą konflikt z właściwościami formularza,
> takich jak `submit`, `length` lub `method`. Konflikty nazw mogą powodować mylące błędy.
> Kompletna lista zasad oraz walidator znaczników dla tych problemów znajduje się na stronie [DOMLint](http://kangax.github.io/domlint).

Dodatkowe tagi HTML mogą zostać dodane do formularza używając czystego HTML'a lub używając metody z klasy pomocniczej - [[yii\helpers\Html|Html]],
tak jak było to zrobione w przykładzie wyżej z [[yii\helpers\Html::submitButton()|submitButton()]].

> Tip: Jeśli używasz Twitter Bootstrap CSS w Twojej aplikacji, możesz użyć [[yii\bootstrap\ActiveForm]] zamiast [[yii\widgets\ActiveForm]].
> Rozszerza on [[yii\widgets\ActiveForm|ActiveForm]] i podczas generowania pól formularza używa stylu specyficznego dla Bootstrap.

> Tip: Jeśli chcesz oznaczyć wymagane pola gwiazdką, możesz uzyć poniższego kodu CSS:
>
> ```css
> div.required label:after {
>     content: " *";
>     color: red;
> }
> ```

Tworzenie list
--------------

Wyróżniamy trzy typy list:
* Listy rozwijane
* Listy opcji typu radio
* Listy opcji typu checkbox

Aby stworzyć listę, musisz najpierw przygotować jej elementy. Można to zrobić ręcznie:

```php
$items = [
    1 => 'item 1',
    2 => 'item 2'
]
```

lub też pobierając elementy z bazy danych:

```php
$items = Category::find()
        ->select(['label'])
        ->indexBy('id')
        ->column();
```

Elementy `$items` muszą być następnie przetworzone przez odpowiednie widżety list.
Wartość pola formularza (i aktualnie aktywny element) będzie automatycznie ustawiony przez aktualną wartość atrybutu `$model`.

#### Tworzenie listy rozwijanej

Możemy użyć metody klasy ActiveForm [[yii\widgets\ActiveForm::dropDownList()|dropDownList()]] do utworzenia rozwijanej listy:

```php
/* @var $form yii\widgets\ActiveForm */

echo $form->field($model, 'category')->dropdownList([
        1 => 'item 1',
        2 => 'item 2'
    ],
    ['prompt'=>'Wybierz kategorię']
);
```

#### Tworzenie radio listy

Do stworzenia takiej listy możemy użyć metody ActiveField [[\yii\widgets\ActiveField::radioList()]]:

```php
/* @var $form yii\widgets\ActiveForm */

echo $form->field($model, 'category')->radioList([
    1 => 'radio 1',
    2 => 'radio 2'
]);
```

#### Tworzenie checkbox listy

Do stworzenia takiej listy możemy użyć metody ActiveField [[\yii\widgets\ActiveField::checkboxList()]]:

```php
/* @var $form yii\widgets\ActiveForm */

echo $form->field($model, 'category')->checkboxList([
    1 => 'checkbox 1',
    2 => 'checkbox 2'
]);
```

Praca z Pjaxem
-----------------------

Widżet [[yii\widgets\Pjax|Pjax]] pozwala na aktualizację określonej sekcji strony,
zamiast przeładowywania jej całkowicie. Możesz użyć go do odświeżenia formularza
i podmienić jego zawartość po wysłaniu danych.

Możesz skonfigurować [[yii\widgets\Pjax::$formSelector|$formSelector]], aby wskazać,
które formularze powinny wyzwalać użycie pjaxa. Jeśli nie zostanie to ustawione inaczej,
wszystkie formularze z atrybutem `data-pjax` objęte widżetem Pjax będą wyzwalały jego użycie.

```php
use yii\widgets\Pjax;
use yii\widgets\ActiveForm;

Pjax::begin([
    // opcje Pjaxa
]);
    $form = ActiveForm::begin([
        'options' => ['data' => ['pjax' => true]],
        // więcej opcji ActiveForm
    ]);

        // zawartość ActiveForm

    ActiveForm::end();
Pjax::end();
```
> Tip: Należy być ostrożnym z użyciem linków wewnątrz widżetu [[yii\widgets\Pjax|Pjax]], ponieważ
> ich cel również zostanie wyrenderowany wewnątrz widżetu. Aby temu zapobiec, należy użyć atrybutu HTML `data-pjax="0"`.

#### Wartości w przyciskach submit i przesyłanie plików

Znane są problemy z użyciem `jQuery.serializeArray()` podczas obsługi
[[https://github.com/jquery/jquery/issues/2321|plików]] i
[[https://github.com/jquery/jquery/issues/2321|wartości przycisku submit]], które nie
będą jednak rozwiązane i zamiast tego zostały porzucone na rzecz klasy `FormData`
wprowadzonej w HTML5.

Oznacza to, że oficjalne wsparcie dla plików i wartości przycisku submit używanych w połączeniu
z ajaxem lub widżetem [[yii\widgets\Pjax|Pjax]] zależy od
[[https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility|wsparcia przeglądarki]]
dla klasy `FormData`.

Dalsza lektura
---------------

Następna sekcja [Walidacja danych wejściowych](input-validation.md) dotyczy walidacji przesłanych przed formularz danych po stronie serwera, przy użyciu ajax oraz walidacji po stronie
klienta.

Aby przeczytać o bardziej złożonych użyciach formularzy możesz zajrzeć do poniższych sekcji:

- [Odczytywanie tablicowych danych wejściowych](input-tabular-input.md) - do pobierania danych dla wielu modeli tego samego rodzaju.
- [Pobieranie danych dla wielu modeli](input-multiple-models.md) - do obsługi wielu różnych modeli w tym samym formularzu.
- [Wysyłanie plików](input-file-upload.md) - jak używać formularzy do przesyłania plików.


text:
package com.tns.gen.android.app;

public class Application_ActivityLifecycleCallbacks_ftns_modules_application_application_l33_c30__ implements android.app.Application.ActivityLifecycleCallbacks {
	public Application_ActivityLifecycleCallbacks_ftns_modules_application_application_l33_c30__() {
		com.tns.Runtime.initInstance(this);
	}

	public void onActivityCreated(android.app.Activity param_0, android.os.Bundle param_1)  {
		java.lang.Object[] args = new java.lang.Object[2];
		args[0] = param_0;
		args[1] = param_1;
		com.tns.Runtime.callJSMethod(this, "onActivityCreated", void.class, args);
	}

	public void onActivityStarted(android.app.Activity param_0)  {
		java.lang.Object[] args = new java.lang.Object[1];
		args[0] = param_0;
		com.tns.Runtime.callJSMethod(this, "onActivityStarted", void.class, args);
	}

	public void onActivityResumed(android.app.Activity param_0)  {
		java.lang.Object[] args = new java.lang.Object[1];
		args[0] = param_0;
		com.tns.Runtime.callJSMethod(this, "onActivityResumed", void.class, args);
	}

	public void onActivityPaused(android.app.Activity param_0)  {
		java.lang.Object[] args = new java.lang.Object[1];
		args[0] = param_0;
		com.tns.Runtime.callJSMethod(this, "onActivityPaused", void.class, args);
	}

	public void onActivityStopped(android.app.Activity param_0)  {
		java.lang.Object[] args = new java.lang.Object[1];
		args[0] = param_0;
		com.tns.Runtime.callJSMethod(this, "onActivityStopped", void.class, args);
	}

	public void onActivitySaveInstanceState(android.app.Activity param_0, android.os.Bundle param_1)  {
		java.lang.Object[] args = new java.lang.Object[2];
		args[0] = param_0;
		args[1] = param_1;
		com.tns.Runtime.callJSMethod(this, "onActivitySaveInstanceState", void.class, args);
	}

	public void onActivityDestroyed(android.app.Activity param_0)  {
		java.lang.Object[] args = new java.lang.Object[1];
		args[0] = param_0;
		com.tns.Runtime.callJSMethod(this, "onActivityDestroyed", void.class, args);
	}

}


text:
{{<layout}}

{{$pageTitle}}
Performance platform
{{/pageTitle}}

{{$content}}

Performance platform dashboards

	Name
	Last edited

	31 August
	          Monday
	          Summer bank holiday

	25 December
	          Friday
	          Christmas Day

	28 December
	          Monday
	          Boxing Day (substitute day)

Public dashboards

Your applications

	                Performance Platform admin

	                Administer the Performance Platform

	                •
	                Roles: Signin and Dashboard-editor

	                Support

	                Wraps Zendesk API

Sign out

{{/content}}

{{/layout}}


text:
// ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================

package org.talend.dataprep.transformation.aggregation.api.json;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.talend.dataprep.transformation.aggregation.api.AggregationResult;
import org.talend.dataprep.transformation.aggregation.api.WorkingContext;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * Serialize Aggregation in json.
 */
public class AggregationResultSerializer extends JsonSerializer<AggregationResult> {

    /**
     * @see JsonSerializer#serialize(Object, JsonGenerator, SerializerProvider)
     */
    @Override
    public void serialize(AggregationResult result, JsonGenerator gen, SerializerProvider provider) throws IOException {

        // sort the results first
        Comparator<Map.Entry<String, WorkingContext>> comparator =
                (e1, e2) -> Double.compare(e2.getValue().getValue(), e1.getValue().getValue());
        final List<Map.Entry<String, WorkingContext>> entries =
                result.entries().stream().sorted(comparator).collect(Collectors.toList());

        // then write it
        gen.writeStartArray();
        for (Map.Entry<String, WorkingContext> entry : entries) {
            String key = entry.getKey();
            gen.writeStartObject();
            gen.writeStringField("data", key);
            gen.writeNumberField(result.getOperator().name(), entry.getValue().getValue());
            gen.writeEndObject();
        }
        gen.writeEndArray();
    }

}


text:
<?php

namespace Yajra\Datatables\Contracts;

interface DataTableContract
{
    /**
     * Render view.
     *
     * @param $view
     * @param array $data
     * @param array $mergeData
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function render($view, $data = [], $mergeData = []);

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajax();

    /**
     * @return \Yajra\Datatables\Html\Builder
     */
    public function html();

    /**
     * @return \Yajra\Datatables\Html\Builder
     */
    public function builder();

    /**
     * @return \Yajra\Datatables\Request
     */
    public function request();

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query();
}


text:
package org.jenkinsci.plugins.ParameterizedRemoteTrigger.utils;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;

// Trust every server
public class NaiveTrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) {}

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) {}

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}