text:
package io.cattle.platform.core.util;

import io.cattle.platform.core.model.Port;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PortSpec {

    public static final String WRONG_FORMAT = "PortWrongFormat";
    public static final String INVALID_PUBLIC_PORT = "PortInvalidPublicPort";
    public static final String INVALID_PRIVATE_PORT = "PortInvalidPrivatePort";
    public static final String INVALID_PROTOCOL = "PortInvalidProtocol";

    private static final Pattern PATTERN = Pattern.compile("(([0-9]+):)?([0-9]+)(/(.*))?");
    private static final List<String> PROTOCOLS = Arrays.asList("tcp", "udp");

    int privatePort;
    String ipAddress;
    Integer publicPort;
    String protocol;

    public PortSpec() {
    }

    public PortSpec(String ipAddress, int publicPort, Port port) {
        this.ipAddress = ipAddress;
        this.publicPort = publicPort;
        this.privatePort = port.getPrivatePort();
        this.protocol = port.getProtocol();
    }

    public PortSpec(String spec) {
        Matcher m = PATTERN.matcher(spec);

        if ( ! m.matches() ) {
            throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, WRONG_FORMAT);
        }

        int privatePort = Integer.parseInt(m.group(3));
        Integer publicPort = m.group(2) == null ? null : Integer.parseInt(m.group(2));
        String protocol = m.group(5);

        if ( privatePort <= 0 || privatePort > 65535 ) {
            throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, INVALID_PRIVATE_PORT);
        }

        if ( publicPort != null && ( publicPort <= 0 || publicPort > 65535 ) ) {
            throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, INVALID_PUBLIC_PORT);
        }

        if ( protocol == null ) {
            protocol = "tcp";
        }

        if ( ! PROTOCOLS.contains(protocol) ) {
            throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, INVALID_PROTOCOL);
        }

        this.publicPort = publicPort;
        this.privatePort = privatePort;
        this.protocol = protocol;
    }

    public Integer getPublicPort() {
        return publicPort;
    }

    public int getPrivatePort() {
        return privatePort;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public void setPrivatePort(int privatePort) {
        this.privatePort = privatePort;
    }

    public void setPublicPort(Integer publicPort) {
        this.publicPort = publicPort;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. 15: 112 (1901)

#### Original name
Dendryphion leptaleum Ellis

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
    {{$ctrl.user.email}}

        <button
            ng-repeat="btn in $ctrl.buttons"
            ng-if="btn.show($ctrl.user)"
            class="{{btn.class}}"
            ng-click="btn.action($ctrl.user)">
            {{btn.text}}
        </button>
        <button class="btn--clear" ng-click="$ctrl.openRemoveModal()">×</button>


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Navision</title>

	<link type="text/css" rel="stylesheet" href="css/style.css">

    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen"/>

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

			Navision

logout

		<form class="col l12 offset-l4" id="container2">

					<select name="etage" id="id">
						<?php
							foreach(get_bats() as $bat){
								echo "<optgroup label=\"".$bat['NOM_BAT']."\"value=\"".$bat['NOM_BAT']."\">";
								echo $bat['NOM_BAT'];
								foreach(get_etages($bat['NOM_BAT']) as $etage){
									echo "<option class=\"red red-text\" value=\"".$etage['NIVEAU'].",".$bat['CODE_BAT']."\">".$etage['NOM']."</option>";
								}
								echo "</optgroup>";
							}
						?>
					</select>
					Choisissez un étage

					<button class="btn waves-effect waves-light red" type="submit" name="page" value="etage">Sélectionnersend</button>

		</form>


text:
import ngModule from '../module';
import '../../core/api/logs';

ngModule.factory('avSplunkAnalytics', ($log, avLogMessagesResource, $location) => {

  class SplunkAnalyticsService {

    trackEvent(properties) {

      properties.url = $location.$$absUrl || 'N/A';
      properties.level = properties.level || 'info';

      return avLogMessagesResource[properties.level](properties);
    }

    trackPageView(url) {

      const properties = {
        event: 'page',
        level: 'info',
        url: url || $location.$$absUrl()
      };

      return avLogMessagesResource[properties.level](properties);
    }

    isEnabled() {
      return true;
    }

  }

  return new SplunkAnalyticsService();

});

export default ngModule;


text:
module.exports = {
    extends: ['scratch/node', 'scratch/es6']
};


text:
Java Library containing useful often used methods.

[Documentation](doc/index.html)


text:
'use strict';

let fs       = require('fs');
let co       = require('co');
let check    = require('../lib/checkStream');

const VALID_HEX = '25504446,FFD8FFE1, FFD8FFE0, FFD8FFFE, 89504E47';

let start = function () {
  co( function *() {
    let streamJPG        = fs.createReadStream('./example.jpg');
    let isValid          = yield check.checkIfValidHeader(VALID_HEX, streamJPG);

    let streamTXT        = fs.createReadStream('./bad.txt');
    let shouldNotBeValed = yield check.checkIfValidHeader(VALID_HEX, streamTXT);

    console.log('example.jpg:', isValid);
    console.log('bad.txt:', shouldNotBeValed);

  }).catch(function (err) {
    console.error(err);
  });

};

start();


text:
imagedir = "ref/"
command += oiiotool ("-pattern fill:topleft=0.1:topright=0.5:bottomleft=1.0:bottomright=0.3 64x64 1 -chnames Z -d float -o out.zfile")
command += info_command ("out.zfile", extraargs="-stats")
outputs += [ "out.zfile" ]


text:
	#include <numeric>
	#include <algorithm>
	#include <cmath>
	#include <vector>
	double utils_mean(std::vector<double> v);
	double utils_stddev(std::vector<double> v);
#endif


text:
package com.dianping.cat.report.page.logview;

import java.util.Arrays;

import org.unidal.web.mvc.ActionContext;
import org.unidal.web.mvc.payload.annotation.FieldMeta;
import org.unidal.web.mvc.payload.annotation.PathMeta;

import com.dianping.cat.mvc.AbstractReportPayload;
import com.dianping.cat.report.ReportPage;

public class Payload extends AbstractReportPayload<Action, ReportPage> {
	@FieldMeta("op")
	private Action m_action = Action.VIEW;

	@PathMeta("path")
	private String[] m_path;

	@FieldMeta("header")
	private boolean m_showHeader = true;

	@FieldMeta("waterfall")
	private boolean m_waterfall = false;

	public Payload() {
		super(ReportPage.LOGVIEW);
	}

	@Override
	public Action getAction() {
		return m_action;
	}

	public void setAction(String action) {
		m_action = Action.getByName(action, m_action);
	}

	public String[] getPath() {
		return m_path;
	}

	public void setPath(String[] path) {
		if (path == null) {
			m_path = new String[0];
		} else {
			m_path = Arrays.copyOf(path, path.length);
		}
	}

	public boolean isShowHeader() {
		return m_showHeader;
	}

	public void setShowHeader(String showHeader) {
		m_showHeader = !"no".equals(showHeader);
	}

	public boolean isWaterfall() {
		return m_waterfall;
	}

	public void setWaterfall(boolean waterfall) {
		m_waterfall = waterfall;
	}

	@Override
	public void setPage(String page) {
		m_page = ReportPage.getByName(page, ReportPage.LOGVIEW);
	}

	@Override
	public void validate(ActionContext<?> ctx) {
	}
}


text:
ALTER TABLE NOTIFICATION
  ADD CONSTRAINT FK_NOTIFICATION FOREIGN KEY (NOTIFICATION_TYPE_ID)
  REFERENCES NOTIFICATION_TYPE (NOTIFICATION_TYPE_ID);


text:
package com.pungwe.cms.themes.test;

import com.pungwe.cms.core.annotations.util.Hook;
import com.pungwe.cms.core.annotations.stereotypes.Theme;
import com.pungwe.cms.core.block.services.BlockManagementService;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ian on 13/02/2016.
 */
@Theme(name = "test_theme", label = "Test Theme", description = "This is a test theme with no parent")
public class TestTheme {

    @Autowired
    BlockManagementService blockManagementService;

    @Hook("install")
    public void install() {

        // Create a list of the default blocks that will be used...
        blockManagementService.addBlockToTheme("test_theme_page_title_block", "test_theme", "header", "page_title_block", -100, new HashMap<>());
        blockManagementService.addBlockToTheme("test_theme_breadcrumb_block", "test_theme", "breadcrumb", "breadcrumb_block", -100, breadcrumbBlockSettings());
        blockManagementService.addBlockToTheme("test_theme_status_message_block", "test_theme", "highlighted", "status_message_block", -100, new HashMap<>());
        blockManagementService.addBlockToTheme("test_theme_menu_block", "test_theme", "sidebar_first", "menu_block", -100, primaryMenuSettings());
        blockManagementService.addBlockToTheme("test_theme_system_tasks_block", "test_theme", "content", "system_tasks_block", -101, taskBlockSettings());
        blockManagementService.addBlockToTheme("test_theme_main_content_block", "test_theme", "content", "main_content_block", -100, new HashMap<>());
    }

    private Map<String, Object> primaryMenuSettings() {
        Map<String, Object> settings = new HashMap<String, Object>();
        settings.put("menu_class", "nav navbar-nav");
        settings.put("active_item_class", "active");
        settings.put("menu", "main_navigation");
        return settings;
    }

    private Map<String, Object> taskBlockSettings() {
        Map<String, Object> map = new HashMap<>();
        map.put("menu", "main_navigation");
        return map;
    }

    private Map<String, Object> breadcrumbBlockSettings() {
        Map<String, Object> map = new HashMap<>();
        map.put("menu", "main_navigation");
        return map;
    }

    @Hook("theme")
    public Map<String, String> themeHook() {
        HashMap<String, String> theme = new HashMap<>();
        theme.put("my_view", "my_theme/my_view");
        return theme;
    }
}


text:
@interface PXLViewController ()

@end

@implementation PXLViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	self.title = @"PXLActionSheet";

	self.view.backgroundColor = [UIColor colorWithRed:0.082 green:0.541 blue:0.792 alpha:1];

	UILabel *label = [[UILabel alloc] init];
	label.translatesAutoresizingMaskIntoConstraints = NO;
	label.text = @"Tap to show";
	label.font = [UIFont fontWithName:@"Avenir" size:20];
	label.textColor = [UIColor whiteColor];
	label.userInteractionEnabled = YES;
	[self.view addSubview:label];

	UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
	[label addGestureRecognizer:tap];

	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
	[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
}

- (void)tap:(UITapGestureRecognizer *)gestureRecognizer {
	if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {

		[PXLActionSheet showInView:self.view withTheme:[PXLActionSheetTheme defaultTheme] title:@"A new customizable replacement for UIActionSheet." cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@[@"Custom Fonts", @"Custom Colors", @"And More!"] tapBlock:^(PXLActionSheet *actionSheet, NSInteger tappedButtonIndex) {
			NSLog(@"tapped at %ld", (long)tappedButtonIndex);
		}];

	}
}

@end


text:
<?php

defined('ROOT_DIR') || define('ROOT_DIR', __DIR__);

/* @var $loader \Composer\Autoload\ClassLoader */
$loader = require ROOT_DIR . '/vendor/autoload.php';
$loader->add('Dynamo', ROOT_DIR . '/tests/');
$loader->add('Dynamo', ROOT_DIR . '/src/');


text:
package profile

import (
	"context"
)

type Service interface {
	ApplyProfile(ctx context.Context, p *Profile) error
	GetProfiles(ctx context.Context, opt GetProfilesOption) ([]Profile, error)
	RemoveProfiles(ctx context.Context, ids []string) error
}

type GetProfilesOption struct {
	Identifier string `json:"id"`
}

type Store interface {
	ProfileById(id string) (*Profile, error)
	Save(p *Profile) error
	List() ([]Profile, error)
	Delete(id string) error
}

func New(store Store) *ProfileService {
	return &ProfileService{store: store}
}

type ProfileService struct {
	store Store
}

func IsNotFound(err error) bool {
	type notFoundError interface {
		error
		NotFound() bool
	}

	_, ok := err.(notFoundError)
	return ok
}


text:
package jqian.util.graph;

import java.util.*;

/** General graph structure for display.
 *  Used as an intermediate representation to separate from 'dot' graph 'jgraph' graph, and etc.
 */
public class Graph extends GraphElement{
	private String _title;
    private Collection<GraphNode> _nodes;
    private Map<GraphNode,Collection<GraphEdge>> _edgesOut;     //edges out of each node
    private Map<GraphNode,Collection<GraphEdge>> _edgesIn;      //edges into each node

    private int _edgeCount;

    public Graph(String title){
        this._title = title;

        _nodes =  new HashSet<GraphNode>();
        _edgesOut = new HashMap<GraphNode,Collection<GraphEdge>>();
        _edgesIn = new HashMap<GraphNode,Collection<GraphEdge>>();
    }

    public String getTitle(){
    	return _title;
    }

    public void setTitle(String title){
    	this._title = title;
    }

    public Collection<GraphNode> getNodes(){
        return _nodes;
    }

     public boolean addNode(GraphNode node){
         return _nodes.add(node);
    }

     public boolean addEdge(GraphEdge edge) {
    	GraphNode from = edge.src();
    	GraphNode to = edge.dest();

    	boolean exist = true;
    	Collection<GraphEdge> outs = _edgesOut.get(from);
    	if(outs==null){
    		outs = createEdgeSet();
    		_edgesOut.put(from,outs);
    		exist = false;
    	}

    	Collection<GraphEdge> ins = _edgesIn.get(to);
    	if(ins==null){
    		ins = createEdgeSet();
    		_edgesIn.put(to,ins);
    		exist = false;
    	}

    	exist = exist && outs.contains(edge);
    	if(!exist){
    		outs.add(edge);
    		ins.add(edge);
    		_edgeCount++;
    	}

        return !exist;
    }

    public int getEdgeCount(){
        return _edgeCount++;
    }

    public int getNodeCount(){
        return _nodes.size();
    }

    public Collection<GraphEdge> edgesInto(GraphNode node){
    	Collection<GraphEdge> edges = _edgesIn.get(node);
    	if(edges!=null)
    		return edges;
    	else
    		return Collections.emptySet();
    }

    public Collection<GraphEdge> edgesOutOf(GraphNode node){
    	Collection<GraphEdge> edges = _edgesOut.get(node);
    	if(edges!=null)
    		return edges;
    	else
    		return Collections.emptySet();
    }

    public String toString(){
        StringBuffer str = new StringBuffer("Graph: "+_title+"\n");
        for(GraphNode node: _nodes){
        	str.append("\n\nNode: "+node.toString());
        	str.append("\nIn edges ");
        	Collection<GraphEdge> ins = _edgesIn.get(node);
        	if(ins!=null){
        		str.append("("+ins.size()+")\n");
        		edgesToString(ins, str);
        	}
        	else{
        		str.append("(0)\n");
        	}

        	str.append("\nOut edges:");
        	Collection<GraphEdge> outs = _edgesOut.get(node);
        	if(outs!=null){
        		str.append("("+outs.size()+")\n");
        		edgesToString(outs, str);
        	}
        	else{
        		str.append("(0)\n");
        	}
        }

        return str.toString();
    }

    private Set<GraphEdge> createEdgeSet(){
    	return new HashSet<GraphEdge>();
    }

    private void edgesToString(Collection<GraphEdge> edges, StringBuffer str){
    	for(GraphEdge e: edges){
    		str.append("   " + e + "\n");
    	}
    }
}


text:
import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { UserMenuEnum, UserVouchersDataForSearch, UserVouchersQueryFilters, VoucherCreationTypeEnum, VoucherStatusEnum } from 'app/api/models';
import { SvgIcon } from 'app/core/svg-icon';
import { HeadingAction } from 'app/shared/action';
import { FieldOption } from 'app/shared/field-option';
import { empty } from 'app/shared/helper';
import { BaseSearchVouchersComponent, VoucherSearchParams } from 'app/ui/banking/vouchers/base-search-vouchers.component';
import { ExportHelperService } from 'app/ui/core/export-helper.service';
import { Menu } from 'app/ui/shared/menu';

type UserVoucherSearchParams = VoucherSearchParams & UserVouchersQueryFilters & {
  user: string;
  fields?: Array<string>;
};

@Component({
  selector: 'search-user-vouchers',
  templateUrl: 'search-user-vouchers.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchUserVouchersComponent
  extends BaseSearchVouchersComponent<UserVouchersDataForSearch, UserVoucherSearchParams> implements OnInit {

  VoucherStatusEnum = VoucherStatusEnum;

  param: string;
  self: boolean;

  constructor(injector: Injector) {
    super(injector);
  }

  ngOnInit() {
    super.ngOnInit();
    this.param = this.route.snapshot.paramMap.get('user');
    this.addSub(this.vouchersService.getUserVouchersDataForSearch({
      user: this.param
    }).subscribe(dataForSearch => {
      this.data = dataForSearch;
    }));
  }

  onDataInitialized(data: UserVouchersDataForSearch) {
    super.onDataInitialized(data);
    this.self = this.authHelper.isSelf(data.user);
    const headingActions: HeadingAction[] = [];
    if (data.canBuy) {
      headingActions.push(new HeadingAction(SvgIcon.TicketArrowLeft, this.i18n.voucher.buy.buy, () => this.buy(), true));
    }
    if (data.canSend) {
      headingActions.push(new HeadingAction(SvgIcon.TicketArrowRight, this.i18n.voucher.send.send, () => this.send(), true));
    }
    if (empty(this.form.controls.creationType.value)) {
      this.form.patchValue({ creationType: 'all' });
    }
    headingActions.push(...this.exportActions(data));
    this.headingActions = headingActions;
    this.form.get('creationType')?.valueChanges.subscribe(() => {
      this.headingActions$.next(this.headingActions.filter(action => action.id !== ExportHelperService.EXPORT_ACTION));
      if (this.form.get('creationType')?.value !== VoucherCreationTypeEnum.SENT) {
        this.headingActions.push(...this.exportActions(data));
      }
    });
  }

  private exportActions(data: UserVouchersDataForSearch): HeadingAction[] {
    return this.exportHelper.headingActions(data.exportFormats,
      f => this.vouchersService.exportUserVouchers$Response({
        format: f.internalName,
        ...this.toSearchParams(this.form.value)
      }));
  }

  protected toSearchParams(value: any): UserVoucherSearchParams {
    const params: UserVoucherSearchParams = super.toSearchParams(value);
    params.user = this.param;
    if ((params.creationType as string) === 'all') {
      params.creationType = null;
    }
    params.fields = [
      'id', 'amount', 'balance', 'status', 'creationDate', 'expirationDate',
      'type.image', 'type.voucherTitle', 'type.configuration.currency'
    ];
    return params;
  }

  protected doSearch(value: UserVoucherSearchParams) {
    return this.vouchersService.searchUserVouchers$Response(value);
  }

  protected getFormControlNames(): string[] {
    return ['types', 'token', 'statuses', 'creationType'];
  }

  private buy() {
    this.router.navigate(['/banking', this.param, 'vouchers', 'buy']);
  }

  private send() {
    this.router.navigate(['/banking', this.param, 'vouchers', 'send']);
  }

  get creationTypeOptions(): FieldOption[] {
    const statuses = [
      'all',
      VoucherCreationTypeEnum.BOUGHT,
      VoucherCreationTypeEnum.SENT
    ];
    return statuses.map(st => ({
      value: st,
      text: st === 'all'
        ? this.i18n.general.all
        : this.apiI18n.voucherCreationType(st as VoucherCreationTypeEnum)
    }));
  }

  useInactiveStatus() {
    // There's no point on searching for inactive vouchers with a user
    return false;
  }

  resolveMenu(data: UserVouchersDataForSearch) {
    return this.menu.userMenu(data.user, this.dataForFrontendHolder.dataForFrontend.voucherBuyingMenu == UserMenuEnum.MARKETPLACE ?
      Menu.SEARCH_MY_VOUCHERS_MARKETPLACE : Menu.SEARCH_MY_VOUCHERS_BANKING);
  }
}


text:
module Api
  module V1
    module Indc
      class ValueOverviewSerializer < ActiveModel::Serializer
        attribute :slug
        attribute :name
        attribute :value
        attribute :document_slug

        def name
          object.indicator.name
        end

        def slug
          object.indicator.slug
        end

        def document_slug
          object.document&.slug
        end
      end
    end
  end
end


text:
var requestAnimFrame = (function(){
    return window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
})();

var resources = new sh.Resources();
var stats;
var w = window.innerWidth;
var h = window.innerHeight;
var renderer;
var gl;
var root;

var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;

var DEFAULT_ATTRIB_ARRAYS = [
  { name: "a_position",
    size: 3,
    stride: 8,
    offset: 0,
    decodeOffset: -4095,
    decodeScale: 1/8191
  },
  { name: "a_texcoord",
    size: 2,
    stride: 8,
    offset: 3,
    decodeOffset: 0,
    decodeScale: 1/1023
  },
  { name: "a_normal",
    size: 3,
    stride: 8,
    offset: 3,
    decodeOffset: -511,
    decodeScale: 1/1023
  }
];

function convertToWireframe(indices) {
    var arr = new Uint16Array(indices.length / 3 * 6);
    var idx = 0;

    for(var i=0; i<indices.length; i+=3) {
        arr[idx++] = indices[i];
        arr[idx++] = indices[i+1];
        arr[idx++] = indices[i+1];
        arr[idx++] = indices[i+2];
        arr[idx++] = indices[i+2];
        arr[idx++] = indices[i];
    }

    return arr;
}

var Player = sh.SceneNode.extend({});

function init() {
    gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

    renderer = new sh.Renderer();

    var camera = new sh.Camera([200, 200, -500]);
    renderer.setRoot(camera);

    root = new sh.SceneNode();
    camera.addObject(root);

    for(var i=0; i<1000; i++) {
        var cube = new sh.Cube([Math.random() * 500 - 250,
                                Math.random() * 500 - 250,
                                Math.random() * 500 - 250],
                               [Math.random() * Math.PI * 2,
                                Math.random() * Math.PI * 2,
                                0],
                              [15, 15, 15]);
        cube.setMaterial(sh.Shaders.getProgram('default'));
        root.addObject(cube);
    }

    var pers = mat4.create();
    mat4.perspective(45, w / h, 1.0, 5000.0, pers);

    sh.Shaders.iterPrograms(function(program) {
        gl.useProgram(program);
        var persLoc = gl.getUniformLocation(program, "pers");
        gl.uniformMatrix4fv(persLoc, false, pers);
    });

    document.getElementById('loading').style.display = 'none';

    gl.enable(gl.DEPTH_TEST);
    //gl.enable(gl.CULL_FACE);
    heartbeat();
}

var last = Date.now();
function heartbeat() {
    var now = Date.now();
    var dt = (now - last) / 1000.;

	var time = Date.now() * 0.001;

	var rx = Math.sin(time * 0.7) * 0.5;
	var ry = Math.sin(time * 0.3) * 0.5;
	var rz = Math.sin(time * 0.2) * 0.5;

    root.setRot(rx, ry, rz);
    renderer.update(dt);

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    renderer.render();

    last = now;
    requestAnimFrame(heartbeat);

    stats.update();
}

window.addEventListener('load', function() {
    stats = new Stats();
    //stats.setMode(1);
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.right = '0px';
    stats.domElement.style.top = '0px';
    document.body.appendChild(stats.domElement);

    resources.onReady(init);
});


text:
package org.apache.poi.hmef;

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

import org.apache.poi.hmef.attribute.MAPIAttribute;
import org.apache.poi.hmef.attribute.MAPIStringAttribute;
import org.apache.poi.hmef.attribute.TNEFAttribute;
import org.apache.poi.hmef.attribute.TNEFDateAttribute;
import org.apache.poi.hmef.attribute.TNEFMAPIAttribute;
import org.apache.poi.hmef.attribute.TNEFProperty;
import org.apache.poi.hmef.attribute.TNEFStringAttribute;
import org.apache.poi.hsmf.datatypes.MAPIProperty;

/**
 * An attachment within a {@link HMEFMessage}. Provides both helper
 *  methods to get at common parts and attributes of the attachment,
 *  and list methods to get all of them.
 */
public final class Attachment {
   private final List<TNEFAttribute> attributes = new ArrayList<TNEFAttribute>();
   private final List<MAPIAttribute> mapiAttributes = new ArrayList<MAPIAttribute>();

   protected void addAttribute(TNEFAttribute attr) {
      attributes.add(attr);

      if(attr instanceof TNEFMAPIAttribute) {
         TNEFMAPIAttribute tnefMAPI = (TNEFMAPIAttribute)attr;
         mapiAttributes.addAll( tnefMAPI.getMAPIAttributes() );
      }
   }

   /**
    * Return the attachment attribute with the given ID,
    *  or null if there isn't one.
    */
   public TNEFAttribute getAttribute(TNEFProperty id) {
      for(TNEFAttribute attr : attributes) {
         if(attr.getProperty() == id) {
            return attr;
         }
      }
      return null;
   }

   /**
    * Return the attachment MAPI Attribute with the given ID,
    *  or null if there isn't one.
    */
   public MAPIAttribute getMAPIAttribute(MAPIProperty id) {
      for(MAPIAttribute attr : mapiAttributes) {
         if(attr.getProperty() == id) {
            return attr;
         }
      }
      return null;
   }

   /**
    * Returns all HMEF/TNEF attributes of the attachment,
    *  such as filename, icon and contents
    */
   public List<TNEFAttribute> getAttributes() {
      return attributes;
   }

   /**
    * Returns all MAPI attributes of the attachment,
    *  such as extension, encoding, size and position
    */
   public List<MAPIAttribute> getMAPIAttributes() {
      return mapiAttributes;
   }

   /**
    * Return the string value of the mapi property, or null
    *  if it isn't set
    */
   private String getString(MAPIProperty id) {
      return MAPIStringAttribute.getAsString( getMAPIAttribute(id) );
   }
   /**
    * Returns the string value of the TNEF property, or
    *  null if it isn't set
    */
   private String getString(TNEFProperty id) {
      return TNEFStringAttribute.getAsString( getAttribute(id) );
   }

   /**
    * Returns the short filename
    */
   public String getFilename() {
      return getString(TNEFProperty.ID_ATTACHTITLE);
   }
   /**
    * Returns the long filename
    */
   public String getLongFilename() {
      return getString(MAPIProperty.ATTACH_LONG_FILENAME);
   }
   /**
    * Returns the file extension
    */
   public String getExtension() {
      return getString(MAPIProperty.ATTACH_EXTENSION);
   }

   /**
    * Return when the file was last modified, if known.
    */
   public Date getModifiedDate() {
      return TNEFDateAttribute.getAsDate(
            getAttribute(TNEFProperty.ID_ATTACHMODIFYDATE)
      );
   }

   /**
    * Returns the contents of the attachment.
    *
    * @throws IllegalArgumentException if there is no AttachmentData available in this Attachment
    */
   public byte[] getContents() {
      TNEFAttribute contents = getAttribute(TNEFProperty.ID_ATTACHDATA);
      if(contents == null) {
         throw new IllegalArgumentException("Attachment corrupt - no Data section");
      }
      return contents.getData();
   }

   /**
    * Returns the Meta File rendered representation
    *  of the attachment, or null if not set.
    */
   public byte[] getRenderedMetaFile() {
      TNEFAttribute meta = getAttribute(TNEFProperty.ID_ATTACHMETAFILE);
      if(meta == null) return null;
      return meta.getData();
   }
}


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.packages;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.syntax.Type;
import javax.annotation.Nullable;

/**
 * An {@link AttributeMap} that delegates all behavior to another {@link AttributeMap}. Useful
 * for custom mappers that just want to override specific scenarios.
 */
public class DelegatingAttributeMapper implements AttributeMap {
  private final AttributeMap delegate;

  public DelegatingAttributeMapper(AttributeMap delegate) {
    this.delegate = Preconditions.checkNotNull(delegate);
  }

  @Override
  public String getName() {
    return delegate.getName();
  }

  @Override
  public Label getLabel() {
    return delegate.getLabel();
  }

  @Override
  public String getRuleClassName() {
    return delegate.getRuleClassName();
  }

  @Override
  public <T> T get(String attributeName, Type<T> type) {
    return delegate.get(attributeName, type);
  }

  @Override
  public boolean isConfigurable(String attributeName) {
    return delegate.isConfigurable(attributeName);
  }

  @Override
  public Iterable<String> getAttributeNames() {
    return delegate.getAttributeNames();
  }

  @Nullable
  @Override
  public Type<?> getAttributeType(String attrName) {
    return delegate.getAttributeType(attrName);
  }

  @Nullable
  @Override
  public Attribute getAttributeDefinition(String attrName) {
    return delegate.getAttributeDefinition(attrName);
  }

  @Override
  public boolean isAttributeValueExplicitlySpecified(String attributeName) {
    return delegate.isAttributeValueExplicitlySpecified(attributeName);
  }

  @Override
  public void visitLabels(AcceptsLabelAttribute observer) throws InterruptedException {
    delegate.visitLabels(observer);
  }

  @Override
  public String getPackageDefaultHdrsCheck() {
    return delegate.getPackageDefaultHdrsCheck();
  }

  @Override
  public Boolean getPackageDefaultTestOnly() {
    return delegate.getPackageDefaultTestOnly();
  }

  @Override
  public String getPackageDefaultDeprecation() {
    return delegate.getPackageDefaultDeprecation();
  }

  @Override
  public ImmutableList<String> getPackageDefaultCopts() {
    return delegate.getPackageDefaultCopts();
  }

  @Override
  public boolean has(String attrName) {
    return delegate.has(attrName);
  }

  @Override
  public <T> boolean has(String attrName, Type<T> type) {
    return delegate.has(attrName, type);
  }

  @Override
  public Location getAttributeLocation(String attrName) {
    return delegate.getAttributeLocation(attrName);
  }
}


text:
{% extends "admin/index.html" %}
{% load i18n admin_tools_dashboard_tags %}

{% if not is_popup %}

    {% block dashboard_css %}{% admin_tools_render_dashboard_css 'app_index' %}{% endblock %}
    {% block breadcrumbs %}

            {% trans "Home" %} ›
            {% for app in app_list %}
                {% blocktrans with app.name as name %}{{ name }}{% endblocktrans %}
            {% endfor %}
{% endblock %}

{% endif %}

{% block content %}
    {% admin_tools_render_dashboard 'app_index' %}
{% endblock %}
{% block sidebar %}{% endblock %}


text:
package korean

import (
	"testing"

	"github.com/insionng/yougam/libraries/x/text/encoding"
	"github.com/insionng/yougam/libraries/x/text/encoding/internal"
	"github.com/insionng/yougam/libraries/x/text/transform"
)

func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) {
	return "Decode", e.NewDecoder(), nil
}
func enc(e encoding.Encoding) (dir string, t transform.Transformer, err error) {
	return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement
}

func TestNonRepertoire(t *testing.T) {
	testCases := []struct {
		init      func(e encoding.Encoding) (string, transform.Transformer, error)
		e         encoding.Encoding
		src, want string
	}{
		{dec, EUCKR, "\xfe\xfe", "\ufffd"},
		// {dec, EUCKR, "א", "\ufffd"}, // TODO: why is this different?

		{enc, EUCKR, "א", ""},
		{enc, EUCKR, "aא", "a"},
		{enc, EUCKR, "\uac00א", "\xb0\xa1"},
		// TODO: should we also handle Jamo?
	}
	for _, tc := range testCases {
		dir, tr, wantErr := tc.init(tc.e)

		dst, _, err := transform.String(tr, tc.src)
		if err != wantErr {
			t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, wantErr)
		}
		if got := string(dst); got != tc.want {
			t.Errorf("%s %v(%q):\ngot  %q\nwant %q", dir, tc.e, tc.src, got, tc.want)
		}
	}
}


text:
package finder.socialmediacontactfinder.http.Service.Response;

import java.io.Serializable;
import java.util.List;

/**
 * Created by previousdeveloper on 16.08.2015.
 */
public class ContactInfo implements Serializable {

    private List<Website> websites;
    private String familyName;
    private String fullName;
    private String givenName;

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public List<Website> getWebsites() {
        return websites;
    }

    public void setWebsites(List<Website> websites) {
        this.websites = websites;
    }

    public String getFamilyName() {
        return familyName;
    }

    public void setFamilyName(String familyName) {
        this.familyName = familyName;
    }

    public String getGivenName() {
        return givenName;
    }

    public void setGivenName(String givenName) {
        this.givenName = givenName;
    }

}


text:
package container

import (
	"strings"
	"testing"

	"github.com/stretchr/testify/mock"
)

type mockContainerHandlerFactory struct {
	mock.Mock
	Name string
}

func (self *mockContainerHandlerFactory) String() string {
	return self.Name
}

func (self *mockContainerHandlerFactory) NewContainerHandler(name string) (ContainerHandler, error) {
	args := self.Called(name)
	return args.Get(0).(ContainerHandler), args.Error(1)
}

func testExpectedFactory(root *factoryTreeNode, path, expectedFactory string, t *testing.T) {
	elems := dropEmptyString(strings.Split(path, "/")...)
	factory := root.find(elems...)
	if factory.String() != expectedFactory {
		t.Errorf("factory %v should be used to create container %v. but %v is selected",
			expectedFactory,
			path,
			factory)
	}
}

func testAddFactory(root *factoryTreeNode, path string) *factoryTreeNode {
	elems := dropEmptyString(strings.Split(path, "/")...)
	if root == nil {
		root = &factoryTreeNode{
			defaultFactory: nil,
		}
	}
	f := &mockContainerHandlerFactory{
		Name: path,
	}
	root.add(f, elems...)
	return root
}

func TestFactoryTree(t *testing.T) {
	root := testAddFactory(nil, "/")
	root = testAddFactory(root, "/docker")
	root = testAddFactory(root, "/user")
	root = testAddFactory(root, "/user/special/containers")

	testExpectedFactory(root, "/docker/container", "/docker", t)
	testExpectedFactory(root, "/docker", "/docker", t)
	testExpectedFactory(root, "/", "/", t)
	testExpectedFactory(root, "/user/deep/level/container", "/user", t)
	testExpectedFactory(root, "/user/special/containers", "/user/special/containers", t)
	testExpectedFactory(root, "/user/special/containers/container", "/user/special/containers", t)
	testExpectedFactory(root, "/other", "/", t)
}


text:
<?php

namespace app\models;

/**
 * This is the ActiveQuery class for [[Status]].
 *
 * @see Status
 */
class StatusQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        return $this->andWhere('[[status]]=1');
    }*/

    /**
     * @inheritdoc
     * @return Status[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return Status|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
package de.predic8.util;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class LogFileDownload implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {

        HttpServletResponse response = exchange.getIn().getBody(HttpServletResponse.class);
        File log = new File("document-archive/logs/log.txt");
        InputStream in = new FileInputStream(log);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-Disposition", "attachment; filename=" + log.getName());
        response.setHeader("Content-Length", String.valueOf(log.length()));
        FileCopyUtils.copy(in, response.getOutputStream());
    }
}


text:
package com.amazonservices.mws.reports.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

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

 * <complexType name="FeedSubmissionInfo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="FeedSubmissionId" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="FeedType" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="SubmittedDate" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="FeedProcessingStatus" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="StartedProcessingDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element name="CompletedProcessingDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 * Generated by AWS Code Generator
 *

 * Wed Feb 18 13:28:59 PST 2009
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FeedSubmissionInfo", propOrder = {
    "feedSubmissionId",
    "feedType",
    "submittedDate",
    "feedProcessingStatus",
    "startedProcessingDate",
    "completedProcessingDate"
})
public class FeedSubmissionInfo {

    @XmlElement(name = "FeedSubmissionId", required = true)
    protected String feedSubmissionId;
    @XmlElement(name = "FeedType", required = true)
    protected String feedType;
    @XmlElement(name = "SubmittedDate", required = true)
    protected String submittedDate;
    @XmlElement(name = "FeedProcessingStatus", required = true)
    protected String feedProcessingStatus;
    @XmlElement(name = "StartedProcessingDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar startedProcessingDate;
    @XmlElement(name = "CompletedProcessingDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar completedProcessingDate;

    /**
     * Default constructor
     *
     */
    public FeedSubmissionInfo() {
        super();
    }

    /**
     * Value constructor
     *
     */
    public FeedSubmissionInfo(final String feedSubmissionId, final String feedType, final String submittedDate, final String feedProcessingStatus, final XMLGregorianCalendar startedProcessingDate, final XMLGregorianCalendar completedProcessingDate) {
        this.feedSubmissionId = feedSubmissionId;
        this.feedType = feedType;
        this.submittedDate = submittedDate;
        this.feedProcessingStatus = feedProcessingStatus;
        this.startedProcessingDate = startedProcessingDate;
        this.completedProcessingDate = completedProcessingDate;
    }

    /**
     * Gets the value of the feedSubmissionId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFeedSubmissionId() {
        return feedSubmissionId;
    }

    /**
     * Sets the value of the feedSubmissionId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFeedSubmissionId(String value) {
        this.feedSubmissionId = value;
    }

    public boolean isSetFeedSubmissionId() {
        return (this.feedSubmissionId!= null);
    }

    /**
     * Gets the value of the feedType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFeedType() {
        return feedType;
    }

    /**
     * Sets the value of the feedType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFeedType(String value) {
        this.feedType = value;
    }

    public boolean isSetFeedType() {
        return (this.feedType!= null);
    }

    /**
     * Gets the value of the submittedDate property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSubmittedDate() {
        return submittedDate;
    }

    /**
     * Sets the value of the submittedDate property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSubmittedDate(String value) {
        this.submittedDate = value;
    }

    public boolean isSetSubmittedDate() {
        return (this.submittedDate!= null);
    }

    /**
     * Gets the value of the feedProcessingStatus property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFeedProcessingStatus() {
        return feedProcessingStatus;
    }

    /**
     * Sets the value of the feedProcessingStatus property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFeedProcessingStatus(String value) {
        this.feedProcessingStatus = value;
    }

    public boolean isSetFeedProcessingStatus() {
        return (this.feedProcessingStatus!= null);
    }

    /**
     * Gets the value of the startedProcessingDate property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getStartedProcessingDate() {
        return startedProcessingDate;
    }

    /**
     * Sets the value of the startedProcessingDate property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setStartedProcessingDate(XMLGregorianCalendar value) {
        this.startedProcessingDate = value;
    }

    public boolean isSetStartedProcessingDate() {
        return (this.startedProcessingDate!= null);
    }

    /**
     * Gets the value of the completedProcessingDate property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getCompletedProcessingDate() {
        return completedProcessingDate;
    }

    /**
     * Sets the value of the completedProcessingDate property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setCompletedProcessingDate(XMLGregorianCalendar value) {
        this.completedProcessingDate = value;
    }

    public boolean isSetCompletedProcessingDate() {
        return (this.completedProcessingDate!= null);
    }

    /**
     * Sets the value of the FeedSubmissionId property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withFeedSubmissionId(String value) {
        setFeedSubmissionId(value);
        return this;
    }

    /**
     * Sets the value of the FeedType property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withFeedType(String value) {
        setFeedType(value);
        return this;
    }

    /**
     * Sets the value of the SubmittedDate property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withSubmittedDate(String value) {
        setSubmittedDate(value);
        return this;
    }

    /**
     * Sets the value of the FeedProcessingStatus property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withFeedProcessingStatus(String value) {
        setFeedProcessingStatus(value);
        return this;
    }

    /**
     * Sets the value of the StartedProcessingDate property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withStartedProcessingDate(XMLGregorianCalendar value) {
        setStartedProcessingDate(value);
        return this;
    }

    /**
     * Sets the value of the CompletedProcessingDate property.
     *
     * @param value
     * @return
     *     this instance
     */
    public FeedSubmissionInfo withCompletedProcessingDate(XMLGregorianCalendar value) {
        setCompletedProcessingDate(value);
        return this;
    }

    /**
     *
     * XML fragment representation of this object
     *
     * @return XML fragment for this object. Name for outer
     * tag expected to be set by calling method. This fragment
     * returns inner properties representation only
     */
    protected String toXMLFragment() {
        StringBuffer xml = new StringBuffer();
        if (isSetFeedSubmissionId()) {
            xml.append("<FeedSubmissionId>");
            xml.append(escapeXML(getFeedSubmissionId()));
            xml.append("</FeedSubmissionId>");
        }
        if (isSetFeedType()) {
            xml.append("<FeedType>");
            xml.append(escapeXML(getFeedType()));
            xml.append("</FeedType>");
        }
        if (isSetSubmittedDate()) {
            xml.append("<SubmittedDate>");
            xml.append(escapeXML(getSubmittedDate()));
            xml.append("</SubmittedDate>");
        }
        if (isSetFeedProcessingStatus()) {
            xml.append("<FeedProcessingStatus>");
            xml.append(escapeXML(getFeedProcessingStatus()));
            xml.append("</FeedProcessingStatus>");
        }
        if (isSetStartedProcessingDate()) {
            xml.append("<StartedProcessingDate>");
            xml.append(getStartedProcessingDate() + "");
            xml.append("</StartedProcessingDate>");
        }
        if (isSetCompletedProcessingDate()) {
            xml.append("<CompletedProcessingDate>");
            xml.append(getCompletedProcessingDate() + "");
            xml.append("</CompletedProcessingDate>");
        }
        return xml.toString();
    }

    /**
     *
     * Escape XML special characters
     */
    private String escapeXML(String string) {
        StringBuffer sb = new StringBuffer();
        int length = string.length();
        for (int i = 0; i < length; ++i) {
            char c = string.charAt(i);
            switch (c) {
            case '&':
                sb.append("&");
                break;
            case '<':
                sb.append("<");
                break;
            case '>':
                sb.append(">");
                break;
            case '\'':
                sb.append("'");
                break;
            case '"':
                sb.append(""");
                break;
            default:
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     *
     * JSON fragment representation of this object
     *
     * @return JSON fragment for this object. Name for outer
     * object expected to be set by calling method. This fragment
     * returns inner properties representation only
     *
     */
    protected String toJSONFragment() {
        StringBuffer json = new StringBuffer();
        boolean first = true;
        if (isSetFeedSubmissionId()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("FeedSubmissionId"));
            json.append(" : ");
            json.append(quoteJSON(getFeedSubmissionId()));
            first = false;
        }
        if (isSetFeedType()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("FeedType"));
            json.append(" : ");
            json.append(quoteJSON(getFeedType()));
            first = false;
        }
        if (isSetSubmittedDate()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("SubmittedDate"));
            json.append(" : ");
            json.append(quoteJSON(getSubmittedDate()));
            first = false;
        }
        if (isSetFeedProcessingStatus()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("FeedProcessingStatus"));
            json.append(" : ");
            json.append(quoteJSON(getFeedProcessingStatus()));
            first = false;
        }
        if (isSetStartedProcessingDate()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("StartedProcessingDate"));
            json.append(" : ");
            json.append(quoteJSON(getStartedProcessingDate() + ""));
            first = false;
        }
        if (isSetCompletedProcessingDate()) {
            if (!first) json.append(", ");
            json.append(quoteJSON("CompletedProcessingDate"));
            json.append(" : ");
            json.append(quoteJSON(getCompletedProcessingDate() + ""));
            first = false;
        }
        return json.toString();
    }

    /**
     *
     * Quote JSON string
     */
    private String quoteJSON(String string) {
        StringBuffer sb = new StringBuffer();
        sb.append("\"");
        int length = string.length();
        for (int i = 0; i < length; ++i) {
            char c = string.charAt(i);
            switch (c) {
            case '"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '/':
                sb.append("\\/");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            default:
                if (c <  ' ') {
                    sb.append("\\u" + String.format("%03x", Integer.valueOf(c)));
                } else {
                sb.append(c);
            }
        }
        }
        sb.append("\"");
        return sb.toString();
    }

}


text:
package consul

import (
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

const (
	SecretTokenType = "token"
)

func secretToken(b *backend) *framework.Secret {
	return &framework.Secret{
		Type: SecretTokenType,
		Fields: map[string]*framework.FieldSchema{
			"token": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "Request token",
			},
		},

		Renew:  b.secretTokenRenew,
		Revoke: secretTokenRevoke,
	}
}

func (b *backend) secretTokenRenew(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {

	return framework.LeaseExtend(0, 0, b.System())(req, d)
}

func secretTokenRevoke(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	c, err := client(req.Storage)
	if err != nil {
		return logical.ErrorResponse(err.Error()), nil
	}

	_, err = c.ACL().Destroy(d.Get("token").(string), nil)
	if err != nil {
		return logical.ErrorResponse(err.Error()), nil
	}

	return nil, nil
}


text:
/* global define, _ */

define(['form/App', 'form/templates/editors/numberEditor.html', './BaseEditorView'],
    function (App, template, EditorBaseView) {
        'use strict';

        var changeMode = {
            blur: 'blur',
            keydown: 'keydown'
        };

        var defaultOptions = {
            changeMode: 'blur'
        };

        return EditorBaseView.extend({
            initialize: function (options) {
                _.extend(this.options, defaultOptions, _.pick(options || {}, _.keys(defaultOptions)));
            },

            focusElement: '.js-input',

            ui: {
                input: '.js-input'
            },

            className: '',

            template: Handlebars.compile(template, {noEscape: true}),

            mixinTemplateHelpers: function (data) {
                data = this.setPlaceholder(data);
                return data;
            },

            events: {
                'change @ui.input': '__change',
                'focus @ui.input': '__focus',
                'keypress @ui.input': '__keydown'
            },

            __focus: function(){
                this.ui.input.closest('div[data-editors]').removeClass('field-invalid');
            },

            __keyup: function () {
                if (this.options.changeMode === changeMode.keydown) {
                    var updateUi = false;
                    var value = this.ui.input.val();
                    if(!this.isValidNumber(value)){
                        value = 0;
                        updateUi = true;
                    }
                    this.__value(value, updateUi);
                }
            },

            __keydown: function (e) {
                if ((e.which !== 44 && e.which !== 46) && (e.which < 48 || e.which > 57)) {
                    e.preventDefault();
                }
            },

            __change: function () {
                var updateUi = false;
                var value = this.ui.input.val();
                if(!this.isValidNumber(value) && value !== ''){
                    value = 0;
                    updateUi = true;
                } else if(value === '') {
                    value = null;
                }
                this.__value(value, updateUi);
                this.showValidationNotifications();

            },

            setValue: function (value, silent) {
                var data;
                if(value){
                    if(value.data && value.data.length){
                        data = value.data[0].dataValue;
                    } else {
                        data = null;
                    }
                    if(!this.isValidNumber(data) && data !== null){
                        data = 0;
                    }
                    this.__value(data, true, silent);
                }
            },

            onRender: function () {
                var value = this.getValue();
                this.ui.input.val(value || '');
            },

            __value: function (value, updateUi, silent) {
                if(value !== "" && value !== null){
                    value = +value;
                }
                this.value.data = [{dataValue: value}];

                updateUi && this.updateUIValue(value);

                !silent && this.__triggerChange();
            },

            getValidationErrors: function (value) {
                this.validationErrors = [];
                value = +value;
                if(_.isNaN(value)){
                      this.validationErrors.push('isNaN');
                }
                if(this.key === 'percentComplete'){
                    if(value > 100){
                        this.validationErrors.push('percentError');
                    }
                    if(value < 0){
                        this.validationErrors.push('percentError');
                    }
                }
                return this.validationErrors;
            },

            isValidNumber: function(value){
                if(value === null){
                    return false;
                }
                value = +value;
                this.getValidationErrors(value);
                return (this.validationErrors.length == 0);
            },

            showValidationNotifications: function(){
                var errorsL = this.validationErrors.length;
                if(errorsL){
                    this.ui.input.closest('div[data-editors]').addClass('field-invalid');
                    for(var i = 0; i < errorsL; i++){
                        if(this.validationErrors[i] == 'percentError'){
                            App.NotificationsMediator.showWarning(App.Localizer.get('ELEGANCE.FORM.WIDGETS.FIELDS.NUMBER.GTLTPERIOD'));
                        }
                        if(this.validationErrors[i] == 'isNaN'){
                            App.NotificationsMediator.showWarning(App.Localizer.get('ELEGANCE.FORM.WIDGETS.FIELDS.NUMBER.WRONGSYMBLOS'));
                        }
                    }
                }
                this.validationErrors = [];
            }
        });
    });


text:
module TrackerCorreosCl
  class Delivery
    attr_reader :number, :to, :rut, :date

    def initialize(number, to, date, rut)
      @number = number
      @to = to
      @date = date
      @rut = rut
    end

    def to_s
      "number #{number}, to #{to}, rut #{rut}, date #{date}"
    end

  end
end


text:
package de.fau.cs.mad.kwikshop.common.rest.responses;

import com.fasterxml.jackson.annotation.JsonProperty;

public class SharingResponse {

    private String shoppingListName;

    @JsonProperty
    public String getShoppingListName() {
        return shoppingListName;
    }

    public void setShoppingListName(String shoppingListName) {
        this.shoppingListName = shoppingListName;
    }
}


text:
import {Ruleset} from "../rulesets/ruleset";

export interface IDisplayNameCache
{
    cacheDisplayNamesFor(rootRuleset: Ruleset): void;
    getDisplayNameFor(propertyRoute: string): string;
}


text:
package com.apps.pyr.pyrtools.core.storage;

public interface Store<Params, Result> {
  Result load(Params params);

  void save(Result data);
}


text:
example-aop
===========

Example project on using AOP with Springframework and custom annotations that can be processed at runtime to modify the aspect behaviour


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2014 Esup Portail http://www.esup-portail.org
    @Author (C) 2012 Julien Gribonvald <julien.gribonvald@recia.fr>

    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.

-->

<configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <charset>utf-8</charset>
            <Pattern>[%p] %c - %m%n</Pattern>
        </encoder>
    </appender>

<!-- The FILE and ASYNC appenders are here as examples for a production configuration -->

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logFile.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>90</maxHistory>
        </rollingPolicy>
        <encoder>
            <charset>utf-8</charset>
            <Pattern>%d %-5level [%thread] %logger: %msg%n</Pattern>
        </encoder>
    </appender>
<!--
    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <queueSize>512</queueSize>
        <appender-ref ref="FILE"/>
    </appender>
-->

    <logger name="org.esupportail.publisher" level="${logback.loglevel:-INFO}"/>
    <logger name="org.esupportail.publisher.web.filter.CrossOriginFilter" level="WARN"/>
    <logger name="org.esupportail.publisher.service.factories" level="WARN"/>
    <logger name="org.esupportail.publisher.repository.externals.ldap" level="WARN"/>
    <logger name="org.esupportail.publisher.repository.externals.ldap.LdapGroupDaoImpl" level="${logback.loglevel:-INFO}"/>
    <logger name="org.esupportail.publisher.repository.externals.ldap.LdapUserDaoImpl" level="${logback.loglevel:-INFO}"/>
    <logger name="org.esupportail.publisher.security.UserContextLoaderServiceImpl" level="${logback.loglevel:-INFO}"/>
    <logger name="org.esupportail.publisher.security.PermissionServiceImpl" level="${logback.loglevel:-INFO}"/>

    <logger name="org.hibernate.stat" level="${logback.loglevel:-INFO}"/>

    <logger name="com.mysema" level="${logback.loglevel:-INFO}"/>

    <logger name="javax.activation" level="WARN"/>
    <logger name="javax.validation" level="WARN"/>
    <logger name="javax.mail" level="WARN"/>
    <logger name="ch.qos.logback" level="WARN"/>
    <logger name="com.codahale.metrics" level="WARN"/>
    <logger name="com.ryantenney" level="WARN"/>
    <logger name="com.sun.xml.internal.bind" level="INFO"/>
    <logger name="com.zaxxer" level="WARN"/>
    <logger name="io.undertow" level="WARN"/>
    <logger name="org.ehcache" level="WARN"/>
    <logger name="org.apache" level="WARN"/>
    <logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>
    <logger name="org.bson" level="WARN"/>
    <logger name="org.hibernate.validator" level="WARN"/>
    <logger name="org.hibernate" level="WARN"/>
    <logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
    <logger name="org.atmosphere" level="WARN"/>
    <logger name="org.springframework" level="WARN"/>
    <logger name="org.springframework.web" level="DEBUG"/>
    <logger name="org.springframework.boot" level="DEBUG"/>
    <logger name="org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener" level="INFO"/>
    <logger name="org.springframework.security" level="INFO"/>
    <logger name="org.springframework.security.web" level="INFO"/>
    <logger name="org.springframework.security.web.util.matcher" level="INFO"/>
    <logger name="org.springframework.security.cas" level="INFO"/>
    <logger name="org.springframework.cache" level="WARN"/>
    <logger name="org.thymeleaf" level="WARN"/>
    <logger name="org.xnio" level="WARN"/>
    <logger name="com.mangofactory.swagger" level="WARN"/>
    <logger name="com.wordnik.swagger" level="WARN"/>
    <logger name="liquibase" level="WARN"/>
    <logger name="sun.rmi.transport" level="WARN"/>

<!--    <logger name="javax.xml.bind" level="DEBUG"/>-->
<!--    <logger name="com.fasterxml.jackson" level="TRACE"/>-->

    <!-- for REST request debug -->
    <!--<logger name="org.springframework.security.web.util.matcher" level="DEBUG" />-->
    <!--<logger name="org.springframework.security.web" level="DEBUG"/>-->
    <!--<logger name="org.springframework.security.web.FilterChainProxy" level="DEBUG" />-->
    <!--<logger name="org.springframework.http" level="DEBUG" />-->
    <!--<logger name="org.springframework.security.cas" level="DEBUG"/>-->

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    <root level="${logback.loglevel:-INFO}">
        <appender-ref ref="CONSOLE"/>
    </root>

    <logger name="org.esupportail.publisher.security" level="${logback.loglevel:-INFO}">
        <appender-ref ref="FILE" />
    </logger>

</configuration>


text:
package com.intellij.codeInspection.lambdaToExplicit;

import com.intellij.codeInspection.*;
import com.intellij.java.JavaBundle;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.java.PsiEmptyExpressionImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

public class ExplicitArgumentCanBeLambdaInspection extends AbstractBaseJavaLocalInspectionTool {

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if (!PsiUtil.isLanguageLevel8OrHigher(holder.getFile())) {
      return PsiElementVisitor.EMPTY_VISITOR;
    }
    return new JavaElementVisitor() {
      @Override
      public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) {
        for(LambdaAndExplicitMethodPair info : LambdaAndExplicitMethodPair.INFOS) {
          PsiExpression arg = info.getLambdaCandidateFromExplicitCall(call);
          if(arg != null && !(arg instanceof PsiEmptyExpressionImpl) && !ExpressionUtils.isSafelyRecomputableExpression(arg)) {
            holder.registerProblem(arg, JavaBundle.message("inspection.explicit.argument.can.be.lambda.message"),
                                   new ConvertExplicitCallToLambdaFix(info, info.getLambdaMethodName(call)));
            return;
          }
        }
      }
    };
  }

  private static class ConvertExplicitCallToLambdaFix implements LocalQuickFix {
    @SafeFieldForPreview
    private final LambdaAndExplicitMethodPair myInfo;
    private final String myName;

    ConvertExplicitCallToLambdaFix(LambdaAndExplicitMethodPair info, String name) {
      myInfo = info;
      myName = name;
    }

    @Nls
    @NotNull
    @Override
    public String getName() {
      return JavaBundle.message("inspection.explicit.argument.can.be.lambda.fix.name", myName);
    }

    @Nls
    @NotNull
    @Override
    public String getFamilyName() {
      return JavaBundle.message("inspection.explicit.argument.can.be.lambda.fix.family.name");
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      PsiExpression arg = ObjectUtils.tryCast(descriptor.getStartElement(), PsiExpression.class);
      if (arg == null) return;
      PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(arg, PsiMethodCallExpression.class);
      if (call == null) return;
      PsiExpression[] args = call.getArgumentList().getExpressions();
      int idx = ArrayUtil.indexOf(args, arg);
      if(idx < 0) return;
      ExpressionUtils.bindCallTo(call, myName);
      String lambdaText = myInfo.makeLambda(arg);
      PsiLambdaExpression lambda =
        (PsiLambdaExpression)arg.replace(JavaPsiFacade.getElementFactory(project).createExpressionFromText(lambdaText, arg));
      LambdaCanBeMethodReferenceInspection.replaceLambdaWithMethodReference(lambda);
    }
  }
}


text:
module Autoparts
  module Packages
    class Apr < Package
      name 'apr'
      version '1.5.1'
      description 'Apache Portable Runtime: Software libraries that provide a predictable and consistent interface to underlying platform-specific implementations'
      category Category::LIBRARIES

      source_url 'http://mirrors.gigenet.com/apache/apr/apr-1.5.1.tar.gz'
      source_sha1 '9caa83e3f50f3abc9fab7c4a3f2739a12b14c3a3'
      source_filetype 'tar.gz'

      def compile
        Dir.chdir('apr-1.5.1') do
          args = [
            "--prefix=#{prefix_path}",
            "--bindir=#{bin_path}",
            "--sbindir=#{bin_path}",
            "--sysconfdir=#{Path.etc}",
            "--libdir=#{lib_path}",
            "--includedir=#{include_path}",
            "--datarootdir=#{share_path}/#{name}",
            "--datadir=#{share_path}/#{name}",
            "--mandir=#{man_path}",
            "--docdir=#{doc_path}",
          ]

          execute './configure', *args
          execute 'make'
        end
      end

      def install
        Dir.chdir('apr-1.5.1') do
          execute 'make install'
        end
      end
    end
  end
end


text:
<?php

namespace TrustFully\Api;

interface ContactInterface
{
    /**
     * @param array $params
     *
     * @return array
     */
    public function create(array $params = []);

    /**
     * @param string $id
     * @param array  $params
     *
     * @return array
     */
    public function update($id, array $params = []);
}


text:
package martin.mogrid.p2pdl.api;

import java.util.Vector;

import martin.mogrid.common.network.Payload;
import martin.mogrid.common.util.SystemUtil;

public class CollaboratorReplyList implements Payload {

   /** Comment for serialVersionUID */
   private static final long serialVersionUID = -5273366917070867011L;

   private Vector replyList;

   public CollaboratorReplyList() {
      replyList = new Vector();
   }

   public boolean addElement(CollaboratorReply value) {
      if ( value != null ) {
         replyList.addElement(value);
         return true;
      }
      return false;
   }

   public boolean addAll(CollaboratorReply[] value) {
      if ( value != null && value.length > 0 ) {
         replyList.clear();
         for ( int i=0; i<value.length; i++ ) {
            replyList.addElement(value[i]);
         }
         return true;
      }
      return false;
   }

   public CollaboratorReply get(int key) {
      if ( isEmpty() ) { return null; }

      CollaboratorReply reply = null;
      reply = (CollaboratorReply) replyList.get(key);

      return reply;
   }

   public CollaboratorReply[] getAll() {
      if ( isEmpty() ) { return null; }

      Object[] values = replyList.toArray();
      int      size   = values.length;
      CollaboratorReply[] reply = new CollaboratorReply[size];
      for ( int i=0; i<size; i++ ) {
         reply[i] = (CollaboratorReply)values[i];
      }

      return reply;
   }

   public CollaboratorReply remove(int key) {
      if ( isEmpty() ) { return null; }

      CollaboratorReply reply = null;
      reply = (CollaboratorReply) replyList.remove(key);

      return reply;
   }

   public CollaboratorReply[] removeAll() {
      if ( isEmpty() ) { return null; }

      CollaboratorReply[] reply = getAll();
      replyList.clear();

      return reply;
   }

   public boolean containsKey(CollaboratorReply value) {
      return replyList.contains(value);
   }

   public boolean containsValue(String collabAddr) {
      if ( SystemUtil.strIsNotNull(collabAddr) ) {
         //Se jah armazenei uma resposta de um collab, não posso armazenar outra
         for ( int i=0; i<replyList.size(); i++ ) {
            CollaboratorReply repValue = (CollaboratorReply)replyList.get(i);
            if ( repValue.getCollaboratorIPAddr().equalsIgnoreCase(collabAddr) )
               return true;
         }
      }
      return false;
   }

   public int size() {
      return replyList.size();
   }

   public boolean isEmpty() {
      return replyList.isEmpty();
   }

   public void clear() {
      replyList.clear();
   }

   public String toString() {
      String listStr = "\nCollaborator Reply List:";
      for ( int key=0; key<size(); key++ ) {
         CollaboratorReply cr = get(key);
         listStr += cr.toString();
      }
      return listStr;
   }
}


text:
layout: default
---
{% include home.html %}

      {{ content }}


text:
import * as React from 'react'
import { EntitySettings } from '@framework/Navigator'
import * as Navigator from '@framework/Navigator'
import { DynamicApiEntity, DynamicApiEval } from './Signum.Entities.Dynamic'
import { SearchControl, ValueSearchControlLine } from '@framework/Search'
import * as Finder from '@framework/Finder'
import * as Constructor from '@framework/Constructor'
import * as DynamicClientOptions from './DynamicClientOptions'

export function start(options: { routes: JSX.Element[] }) {
  Navigator.addSettings(new EntitySettings(DynamicApiEntity, w => import('./Api/DynamicApi')));
  Constructor.registerConstructor(DynamicApiEntity, () => DynamicApiEntity.New({ eval: DynamicApiEval.New() }));
  DynamicClientOptions.Options.onGetDynamicLineForPanel.push(ctx => <ValueSearchControlLine ctx={ctx} findOptions={{ queryName: DynamicApiEntity }} />);
  DynamicClientOptions.Options.registerDynamicPanelSearch(DynamicApiEntity, t => [
    { token: t.append(p => p.name), type: "Text" },
    { token: t.append(p => p.entity.eval!.script), type: "Code" },
  ]);

}


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>org.elkoserver.foundation.actor (neohabitat 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-01-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.elkoserver.foundation.actor

Interfaces

BasicProtocolActor

Classes

Actor

BasicProtocolHandler

JSONHTTPFramer

NonRoutingActor

RefTable

RoutingActor


text:
package com.sequenceiq.cloudbreak.domain.stack.cluster;

import java.util.stream.Stream;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class ClusterTest {
    @Test
    public void testTrustStorePwdWhenNothingIsGiven() {
        // GIVEN
        Cluster cluster = new Cluster();
        // WHEN
        String actualPwd = cluster.getTrustStorePwd();
        // THEN
        Assertions.assertNull(actualPwd);
    }

    @ParameterizedTest
    @MethodSource("passwords")
    public void testTrustStorePwds(String ambariPwd, String cmPwd, String truststorePwd, String expectedPwd) {
        // GIVEN
        Cluster cluster = new Cluster();
        cluster.setCloudbreakAmbariPassword(ambariPwd);
        cluster.setCloudbreakClusterManagerPassword(cmPwd);
        cluster.setTrustStorePwd(truststorePwd);
        // WHEN
        String actualPwd = cluster.getTrustStorePwd();
        // THEN
        Assertions.assertEquals(expectedPwd, actualPwd);
    }

    @Test
    public void testKeyStorePwdWhenNothingIsGiven() {
        // GIVEN
        Cluster cluster = new Cluster();
        // WHEN
        String actualPwd = cluster.getKeyStorePwd();
        // THEN
        Assertions.assertNull(actualPwd);
    }

    @ParameterizedTest
    @MethodSource("passwords")
    public void testKeyStorePwds(String ambariPwd, String cmPwd, String truststorePwd, String expectedPwd) {
        // GIVEN
        Cluster cluster = new Cluster();
        cluster.setCloudbreakAmbariPassword(ambariPwd);
        cluster.setCloudbreakClusterManagerPassword(cmPwd);
        cluster.setKeyStorePwd(truststorePwd);
        // WHEN
        String actualPwd = cluster.getKeyStorePwd();
        // THEN
        Assertions.assertEquals(expectedPwd, actualPwd);
    }

    private static Stream<Arguments> passwords() {
        return Stream.of(
                Arguments.arguments(null, null, null, null),
                Arguments.arguments("ambari", null, null, "ambari"),
                Arguments.arguments(null, "cm", null, "cm"),
                Arguments.arguments("ambari", "cm", "pwd", "pwd"),
                Arguments.arguments("ambari", "cm", null, "cm"),
                Arguments.arguments(null, "cm", null, "cm"),
                Arguments.arguments(null, null, "pwd", "pwd"));
    }
}


text:
package com.amazonaws.services.neptune.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.neptune.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * RemoveRoleFromDBClusterRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveRoleFromDBClusterRequestMarshaller implements Marshaller<Request<RemoveRoleFromDBClusterRequest>, RemoveRoleFromDBClusterRequest> {

    public Request<RemoveRoleFromDBClusterRequest> marshall(RemoveRoleFromDBClusterRequest removeRoleFromDBClusterRequest) {

        if (removeRoleFromDBClusterRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<RemoveRoleFromDBClusterRequest> request = new DefaultRequest<RemoveRoleFromDBClusterRequest>(removeRoleFromDBClusterRequest, "AmazonNeptune");
        request.addParameter("Action", "RemoveRoleFromDBCluster");
        request.addParameter("Version", "2014-10-31");
        request.setHttpMethod(HttpMethodName.POST);

        if (removeRoleFromDBClusterRequest.getDBClusterIdentifier() != null) {
            request.addParameter("DBClusterIdentifier", StringUtils.fromString(removeRoleFromDBClusterRequest.getDBClusterIdentifier()));
        }

        if (removeRoleFromDBClusterRequest.getRoleArn() != null) {
            request.addParameter("RoleArn", StringUtils.fromString(removeRoleFromDBClusterRequest.getRoleArn()));
        }

        if (removeRoleFromDBClusterRequest.getFeatureName() != null) {
            request.addParameter("FeatureName", StringUtils.fromString(removeRoleFromDBClusterRequest.getFeatureName()));
        }

        return request;
    }

}


text:
package com.pengyifan.leetcode;

import static org.junit.Assert.*;

import org.junit.Test;

public class ValidParenthesesTest {

  ValidParentheses t = new ValidParentheses();

  @Test
  public void test() {
    assertTrue(t.isValid("()"));
    assertTrue(t.isValid("()[]{}"));
    assertFalse(t.isValid("(]"));
    assertFalse(t.isValid("([)]"));
  }

}


text:
from app_data.admin import AppDataModelAdmin
from django.contrib import admin
from django.forms import models as modelforms

from ella.core.models import Author, Source, Category, Listing, Related

class ListingForm(modelforms.ModelForm):
    class Meta:
        model = Listing
        fields = [
            'publishable',
            'category',
            'publish_from',
            'publish_to',
            'commercial',
        ]

class ListingInlineAdmin(admin.TabularInline):
    model = Listing
    extra = 2
    fieldsets = ((None, {'fields': ('category', 'publish_from', 'publish_to', 'commercial',)}),)

class RelatedInlineAdmin(admin.TabularInline):
    model = Related
    extra = 3
#    raw_id_fields = ('publishable_id',)

class CategoryAdmin(AppDataModelAdmin):
    list_filter = ('site',)
    list_display = ('draw_title', 'tree_path', '__str__')
    search_fields = ('title', 'slug',)
    #ordering = ('site', 'tree_path',)
    prepopulated_fields = {'slug': ('title',)}
    fieldsets = (
        (None, {'fields': ('title', 'slug')}),
        (None, {'fields': (('description', 'content'),)}),
        (None, {'fields': ('template', ('site', 'tree_parent'))}),
        (None, {'fields': ('ella.paginate_by',)}),
        (None, {'fields': ('ella.first_page_count',)}),
        (None, {'fields': ('ella.propagate_listings',)}),
    )

class AuthorAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    search_fields = ('name',)
    raw_id_fields = ('photo',)

class SourceAdmin(admin.ModelAdmin):
    list_display = ('name', 'url',)
    search_fields = ('name',)

class PublishableAdmin(AppDataModelAdmin):
    """ Default admin options for all publishables """

    list_display = ('title', 'category', 'publish_from')
    list_filter = ('category', 'authors',)
    search_fields = ('title', 'description', 'slug', 'authors__name', 'authors__slug',) # FIXME: 'tags__tag__name',)
    raw_id_fields = ('photo',)
    prepopulated_fields = {'slug': ('title',)}
    rich_text_fields = {None: ('description',)}

    suggest_fields = {
        'category': ('tree_path', 'title', 'slug',),
        'authors': ('name', 'slug', 'email',),
        'source': ('name', 'url',),
    }

class ListingAdmin(admin.ModelAdmin):
    date_hierarchy = 'publish_from'
    list_display = ('__str__', 'publish_from', 'publish_to',)
    list_filter = ('category',)
    search_fields = ('publishable__title', 'publishable__slug',
                     'publishable__description',)

admin.site.register(Category, CategoryAdmin)
admin.site.register(Source, SourceAdmin)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Listing, ListingAdmin)