text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Acta R. Soc. Scient. upsal. 8(2): 291 (1932)

#### Original name
Phialea bicolor Starbäck

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.rice.kew.xml.export;

import org.junit.Test;
import org.kuali.rice.core.api.CoreApiServiceLocator;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kew.rule.RuleTemplateOptionBo;
import org.kuali.rice.kew.rule.bo.RuleTemplateAttributeBo;
import org.kuali.rice.kew.rule.bo.RuleTemplateBo;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.test.BaselineTestCase;
import org.kuali.rice.test.ClearDatabaseLifecycle;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
import java.util.List;

import static org.junit.Assert.*;

@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class RuleTemplateXmlExporterTest extends XmlExporterTestCase {

    @Test public void testExport() throws Exception {
        loadXmlFile("RuleTemplateExportConfig.xml");
        assertExport();
    }

    protected void assertExport() throws Exception {
        // export all existing rule templates and their dependencies (rule attributes)
        List oldRuleTemplates = KEWServiceLocator.getRuleTemplateService().findAll();
        KewExportDataSet dataSet = new KewExportDataSet();
        dataSet.getRuleTemplates().addAll(oldRuleTemplates);
        dataSet.getRuleAttributes().addAll(KEWServiceLocator.getRuleAttributeService().findAll());
        byte[] xmlBytes = CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
        assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0);

        // now clear the tables
        new ClearDatabaseLifecycle(getPerTestTablesToClear(), getPerTestTablesNotToClear()).start();

        // import the exported xml
        loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes)));

        List newRuleTemplates = KEWServiceLocator.getRuleTemplateService().findAll();
        assertEquals("Should have same number of old and new RuleTemplates.", oldRuleTemplates.size(), newRuleTemplates.size());
        for (Iterator iterator = oldRuleTemplates.iterator(); iterator.hasNext();) {
            RuleTemplateBo oldRuleTemplate = (RuleTemplateBo) iterator.next();
            boolean foundTemplate = false;
            for (Iterator iterator2 = newRuleTemplates.iterator(); iterator2.hasNext();) {
                RuleTemplateBo newRuleTemplate = (RuleTemplateBo) iterator2.next();
                if (oldRuleTemplate.getName().equals(newRuleTemplate.getName())) {
                    assertRuleTemplateExport(oldRuleTemplate, newRuleTemplate);
                    foundTemplate = true;
                }
            }
            assertTrue("Could not locate the new rule template for name " + oldRuleTemplate.getName(), foundTemplate);
        }
    }

    private void assertRuleTemplateExport(RuleTemplateBo oldRuleTemplate, RuleTemplateBo newRuleTemplate) {
        assertFalse("Ids should be different.", oldRuleTemplate.getId().equals(newRuleTemplate.getId()));
        assertEquals(oldRuleTemplate.getDescription(), newRuleTemplate.getDescription());
        assertEquals(oldRuleTemplate.getName(), newRuleTemplate.getName());
        if (oldRuleTemplate.getDelegationTemplate() != null) {
            assertRuleTemplateExport(oldRuleTemplate.getDelegationTemplate(), newRuleTemplate.getDelegationTemplate());
        } else {
            assertNull(newRuleTemplate.getDelegationTemplate());
        }
        assertAttributes(oldRuleTemplate.getRuleTemplateAttributes(), newRuleTemplate.getRuleTemplateAttributes(), "attribute");
        assertAttributes(oldRuleTemplate.getActiveRuleTemplateAttributes(), newRuleTemplate.getActiveRuleTemplateAttributes(), "active attribute");
        assertOptions(oldRuleTemplate.getRuleTemplateOptions(), newRuleTemplate.getRuleTemplateOptions());
    }

    private void assertAttributes(List oldAttributes, List newAttributes, String errorMessageAttributeLabel) {
        assertEquals(oldAttributes.size(), newAttributes.size());
        for (Iterator iterator = oldAttributes.iterator(); iterator.hasNext();) {
            RuleTemplateAttributeBo oldAttribute = (RuleTemplateAttributeBo) iterator.next();
            boolean foundAttribute = false;
            for (Iterator iterator2 = newAttributes.iterator(); iterator2.hasNext();) {
                RuleTemplateAttributeBo newAttribute = (RuleTemplateAttributeBo) iterator2.next();
                if (oldAttribute.getRuleAttribute().getName().equals(newAttribute.getRuleAttribute().getName())) {
                    assertEquals(oldAttribute.getRequired(), newAttribute.getRequired());
                    foundAttribute = true;
                }
            }
            assertTrue("Could not locate " + errorMessageAttributeLabel + " with name '" + oldAttribute.getRuleAttribute().getName() + "' in new attributes list.", foundAttribute);
        }
    }

    private void assertOptions(List oldTemplateOptions, List newTemplateOptions) {
        assertEquals(oldTemplateOptions.size(), newTemplateOptions.size());
        for (Iterator iterator = oldTemplateOptions.iterator(); iterator.hasNext();) {
            RuleTemplateOptionBo oldOption = (RuleTemplateOptionBo) iterator.next();
            boolean foundOption = false;
            for (Iterator iterator2 = newTemplateOptions.iterator(); iterator2.hasNext();) {
                RuleTemplateOptionBo newOption = (RuleTemplateOptionBo) iterator2.next();
                if (oldOption.getCode().equals(newOption.getCode())) {
                    assertEquals(oldOption.getValue(), newOption.getValue());
                    foundOption = true;
                }
            }
            assertTrue("Could not locate rule template option.", foundOption);
        }
    }

}


text:
namespace dai {

std::shared_ptr<RawBuffer> ImageManipConfig::serialize() const {
    return raw;
}

ImageManipConfig::ImageManipConfig() : Buffer(std::make_shared<RawImageManipConfig>()), cfg(*dynamic_cast<RawImageManipConfig*>(raw.get())) {}
ImageManipConfig::ImageManipConfig(std::shared_ptr<RawImageManipConfig> ptr) : Buffer(std::move(ptr)), cfg(*dynamic_cast<RawImageManipConfig*>(raw.get())) {}

// helpers
// Functions to set properties
ImageManipConfig& ImageManipConfig::setCropRect(float xmin, float ymin, float xmax, float ymax) {
    // Enable crop stage
    cfg.enableCrop = true;

    // Disable center crop
    cfg.cropConfig.enableCenterCropRectangle = false;

    // Set crop rect - limit to bounds beforehand
    cfg.cropConfig.cropRect.xmin = std::max(xmin, 0.0f);
    cfg.cropConfig.cropRect.ymin = std::max(ymin, 0.0f);
    cfg.cropConfig.cropRect.xmax = std::min(xmax, 1.0f);
    cfg.cropConfig.cropRect.ymax = std::min(ymax, 1.0f);
    return *this;
}

ImageManipConfig& ImageManipConfig::setCropRect(std::tuple<float, float, float, float> coordinates) {
    setCropRect(std::get<0>(coordinates), std::get<1>(coordinates), std::get<2>(coordinates), std::get<3>(coordinates));
    return *this;
}

ImageManipConfig& ImageManipConfig::setCropRotatedRect(RotatedRect rr, bool normalizedCoords) {
    // Enable crop stage and extended flags
    cfg.enableCrop = true;
    cfg.cropConfig.enableRotatedRect = true;

    cfg.cropConfig.cropRotatedRect = rr;
    cfg.cropConfig.normalizedCoords = normalizedCoords;
    return *this;
}

ImageManipConfig& ImageManipConfig::setWarpTransformFourPoints(std::vector<Point2f> pt, bool normalizedCoords) {
    // Enable resize stage and extended flags
    cfg.enableResize = true;
    cfg.resizeConfig.enableWarp4pt = true;
    cfg.resizeConfig.warpFourPoints = pt;
    cfg.resizeConfig.normalizedCoords = normalizedCoords;
    return *this;
}

ImageManipConfig& ImageManipConfig::setWarpTransformMatrix3x3(std::vector<float> mat) {
    // Enable resize stage and extended flags
    cfg.enableResize = true;
    cfg.resizeConfig.enableWarpMatrix = true;
    cfg.resizeConfig.warpMatrix3x3 = mat;
    return *this;
}

ImageManipConfig& ImageManipConfig::setWarpBorderReplicatePixels() {
    // Enable resize stage and extended flags
    cfg.enableResize = true;
    cfg.resizeConfig.warpBorderReplicate = true;
    return *this;
}

ImageManipConfig& ImageManipConfig::setWarpBorderFillColor(int red, int green, int blue) {
    // Enable resize stage and extended flags
    cfg.enableResize = true;
    cfg.resizeConfig.warpBorderReplicate = false;
    cfg.resizeConfig.bgRed = red;
    cfg.resizeConfig.bgGreen = green;
    cfg.resizeConfig.bgBlue = blue;
    return *this;
}

ImageManipConfig& ImageManipConfig::setCenterCrop(float ratio, float whRatio) {
    // Enable crop stage
    cfg.enableCrop = true;

    // Enable center center crop
    cfg.cropConfig.enableCenterCropRectangle = true;

    // Set crop center crop config
    cfg.cropConfig.cropRatio = ratio;
    // Limit to max 1.0f and disallow setting zero ratio
    if(ratio > 1.0f || ratio < 0.0f) {
        cfg.cropConfig.cropRatio = 1.0f;
    }

    cfg.cropConfig.widthHeightAspectRatio = whRatio;
    return *this;
}

ImageManipConfig& ImageManipConfig::setRotationDegrees(float deg) {
    cfg.enableResize = true;
    cfg.resizeConfig.rotationAngleDeg = deg;
    cfg.resizeConfig.enableRotation = true;
    return *this;
}

ImageManipConfig& ImageManipConfig::setRotationRadians(float rad) {
    static constexpr float rad2degFactor = static_cast<float>(180 / M_PI);
    setRotationDegrees(rad * rad2degFactor);
    return *this;
}

ImageManipConfig& ImageManipConfig::setResize(int w, int h) {
    // Enable resize stage
    cfg.enableResize = true;

    // Disable lock aspect ratio
    cfg.resizeConfig.lockAspectRatioFill = false;

    // Set resize config
    cfg.resizeConfig.width = w;
    cfg.resizeConfig.height = h;
    return *this;
}

ImageManipConfig& ImageManipConfig::setResize(std::tuple<int, int> size) {
    setResize(std::get<0>(size), std::get<1>(size));
    return *this;
}

ImageManipConfig& ImageManipConfig::setResizeThumbnail(int w, int h, int bgRed, int bgGreen, int bgBlue) {
    // Enable resize stage
    cfg.enableResize = true;

    // Set resize config
    cfg.resizeConfig.width = w;
    cfg.resizeConfig.height = h;

    // Set lock aspect ratio
    cfg.resizeConfig.lockAspectRatioFill = true;

    // Set background colors
    cfg.resizeConfig.bgRed = bgRed;
    cfg.resizeConfig.bgGreen = bgGreen;
    cfg.resizeConfig.bgBlue = bgBlue;
    return *this;
}

ImageManipConfig& ImageManipConfig::setResizeThumbnail(std::tuple<int, int> size, int bgRed, int bgGreen, int bgBlue) {
    setResizeThumbnail(std::get<0>(size), std::get<1>(size), bgRed, bgGreen, bgBlue);
    return *this;
}

ImageManipConfig& ImageManipConfig::setFrameType(dai::RawImgFrame::Type type) {
    // Enable format stage
    cfg.enableFormat = true;

    // Set type format
    cfg.formatConfig.type = type;
    return *this;
}

ImageManipConfig& ImageManipConfig::setHorizontalFlip(bool flip) {
    // Enable format stage
    cfg.enableFormat = true;

    // Set pixel format
    cfg.formatConfig.flipHorizontal = flip;
    return *this;
}

void ImageManipConfig::setVerticalFlip(bool flip) {
    // Enable format stage
    cfg.enableFormat = true;

    // Set pixel format
    cfg.formatConfig.flipVertical = flip;
}

ImageManipConfig& ImageManipConfig::setReusePreviousImage(bool reuse) {
    cfg.reusePreviousImage = reuse;
    return *this;
}

ImageManipConfig& ImageManipConfig::setSkipCurrentImage(bool skip) {
    cfg.skipCurrentImage = skip;
    return *this;
}

ImageManipConfig& ImageManipConfig::setKeepAspectRatio(bool keep) {
    // Set whether to keep aspect ratio or not
    cfg.resizeConfig.keepAspectRatio = keep;
    return *this;
}

// Functions to retrieve properties
float ImageManipConfig::getCropXMin() const {
    return cfg.cropConfig.cropRect.xmin;
}

float ImageManipConfig::getCropYMin() const {
    return cfg.cropConfig.cropRect.ymin;
}

float ImageManipConfig::getCropXMax() const {
    return cfg.cropConfig.cropRect.xmax;
}

float ImageManipConfig::getCropYMax() const {
    return cfg.cropConfig.cropRect.ymax;
}

int ImageManipConfig::getResizeWidth() const {
    return cfg.resizeConfig.width;
}

int ImageManipConfig::getResizeHeight() const {
    return cfg.resizeConfig.height;
}

ImageManipConfig::CropConfig ImageManipConfig::getCropConfig() const {
    return cfg.cropConfig;
}

ImageManipConfig::ResizeConfig ImageManipConfig::getResizeConfig() const {
    return cfg.resizeConfig;
}

ImageManipConfig::FormatConfig ImageManipConfig::getFormatConfig() const {
    return cfg.formatConfig;
}

bool ImageManipConfig::isResizeThumbnail() const {
    return cfg.resizeConfig.lockAspectRatioFill;
}

}  // namespace dai


text:
using UnityEngine;
using System.Collections;

public class MeshCombineUtility {

	public struct MeshInstance
	{
		public Mesh      mesh;
		public int       subMeshIndex;
		public Matrix4x4 transform;
	}

	public static Mesh Combine (MeshInstance[] combines, bool generateStrips)
	{
		int vertexCount = 0;
		int triangleCount = 0;
		int stripCount = 0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
			{
				vertexCount += combine.mesh.vertexCount;

				if (generateStrips)
				{

				//	int curStripCount = combine.mesh.GetTriangleStrip(combine.subMeshIndex).Length;
                    int curStripCount = combine.mesh.GetTriangles(combine.subMeshIndex).Length;
					if (curStripCount != 0)
					{
						if( stripCount != 0 )
						{
							if ((stripCount & 1) == 1 )
								stripCount += 3;
							else
								stripCount += 2;
						}
						stripCount += curStripCount;
					}
					else
					{
						generateStrips = false;
					}
				}
			}
		}

		// Precomputed how many triangles we need instead
		if (!generateStrips)
		{
			foreach( MeshInstance combine in combines )
			{
				if (combine.mesh)
				{
					triangleCount += combine.mesh.GetTriangles(combine.subMeshIndex).Length;
				}
			}
		}

		Vector3[] vertices = new Vector3[vertexCount] ;
		Vector3[] normals = new Vector3[vertexCount] ;
		Vector4[] tangents = new Vector4[vertexCount] ;
		Vector2[] uv = new Vector2[vertexCount];
		Vector2[] uv1 = new Vector2[vertexCount];
		Color[] colors = new Color[vertexCount];

		int[] triangles = new int[triangleCount];
		int[] strip = new int[stripCount];

		int offset;

		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
				Copy(combine.mesh.vertexCount, combine.mesh.vertices, vertices, ref offset, combine.transform);
		}

		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
			{
				Matrix4x4 invTranspose = combine.transform;
				invTranspose = invTranspose.inverse.transpose;
				CopyNormal(combine.mesh.vertexCount, combine.mesh.normals, normals, ref offset, invTranspose);
			}

		}
		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
			{
				Matrix4x4 invTranspose = combine.transform;
				invTranspose = invTranspose.inverse.transpose;
				CopyTangents(combine.mesh.vertexCount, combine.mesh.tangents, tangents, ref offset, invTranspose);
			}

		}
		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
				Copy(combine.mesh.vertexCount, combine.mesh.uv, uv, ref offset);
		}

		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
				Copy(combine.mesh.vertexCount, combine.mesh.uv2, uv1, ref offset);
		}

		offset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
				CopyColors(combine.mesh.vertexCount, combine.mesh.colors, colors, ref offset);
		}

		int triangleOffset=0;
		int stripOffset=0;
		int vertexOffset=0;
		foreach( MeshInstance combine in combines )
		{
			if (combine.mesh)
			{
				if (generateStrips)
				{
					//int[] inputstrip = combine.mesh.GetTriangleStrip(combine.subMeshIndex);
                    int[] inputstrip = combine.mesh.GetTriangles(combine.subMeshIndex);
					if (stripOffset != 0)
					{
						if ((stripOffset & 1) == 1)
						{
							strip[stripOffset+0] = strip[stripOffset-1];
							strip[stripOffset+1] = inputstrip[0] + vertexOffset;
							strip[stripOffset+2] = inputstrip[0] + vertexOffset;
							stripOffset+=3;
						}
						else
						{
							strip[stripOffset+0] = strip[stripOffset-1];
							strip[stripOffset+1] = inputstrip[0] + vertexOffset;
							stripOffset+=2;
						}
					}

					for (int i=0;i<inputstrip.Length;i++)
					{
						strip[i+stripOffset] = inputstrip[i] + vertexOffset;
					}
					stripOffset += inputstrip.Length;
				}
				else
				{
					int[]  inputtriangles = combine.mesh.GetTriangles(combine.subMeshIndex);
					for (int i=0;i<inputtriangles.Length;i++)
					{
						triangles[i+triangleOffset] = inputtriangles[i] + vertexOffset;
					}
					triangleOffset += inputtriangles.Length;
				}

				vertexOffset += combine.mesh.vertexCount;
			}
		}

		Mesh mesh = new Mesh();
		mesh.name = "Combined Mesh";
		mesh.vertices = vertices;
		mesh.normals = normals;
		mesh.colors = colors;
		mesh.uv = uv;
		mesh.uv2 = uv1;
		mesh.tangents = tangents;
		if (generateStrips)
			//mesh.SetTriangleStrip(strip, 0);
            mesh.SetTriangles(strip,0);
		else
			mesh.triangles = triangles;

		return mesh;
	}

	static void Copy (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform)
	{
		for (int i=0;i<src.Length;i++)
			dst[i+offset] = transform.MultiplyPoint(src[i]);
		offset += vertexcount;
	}

	static void CopyNormal (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform)
	{
		for (int i=0;i<src.Length;i++)
			dst[i+offset] = transform.MultiplyVector(src[i]).normalized;
		offset += vertexcount;
	}

	static void Copy (int vertexcount, Vector2[] src, Vector2[] dst, ref int offset)
	{
		for (int i=0;i<src.Length;i++)
			dst[i+offset] = src[i];
		offset += vertexcount;
	}

	static void CopyColors (int vertexcount, Color[] src, Color[] dst, ref int offset)
	{
		for (int i=0;i<src.Length;i++)
			dst[i+offset] = src[i];
		offset += vertexcount;
	}

	static void CopyTangents (int vertexcount, Vector4[] src, Vector4[] dst, ref int offset, Matrix4x4 transform)
	{
		for (int i=0;i<src.Length;i++)
		{
			Vector4 p4 = src[i];
			Vector3 p = new Vector3(p4.x, p4.y, p4.z);
			p = transform.MultiplyVector(p).normalized;
			dst[i+offset] = new Vector4(p.x, p.y, p.z, p4.w);
		}

		offset += vertexcount;
	}
}


text:
from __future__ import absolute_import
from __future__ import print_function

from argparse import ArgumentParser, RawTextHelpFormatter
from typing import Any, Dict, Text

from zerver.lib.actions import set_default_streams
from zerver.lib.management import ZulipBaseCommand

import sys

class Command(ZulipBaseCommand):
    help = """Set default streams for a realm

Users created under this realm will start out with these streams. This
command is not additive: if you re-run it on a realm with a different
set of default streams, those will be the new complete set of default
streams.

For example:

./manage.py set_default_streams --realm=foo --streams=foo,bar,baz
./manage.py set_default_streams --realm=foo --streams="foo,bar,baz with space"
./manage.py set_default_streams --realm=foo --streams=
"""

    # Fix support for multi-line usage
    def create_parser(self, *args, **kwargs):
        # type: (*Any, **Any) -> ArgumentParser
        parser = super(Command, self).create_parser(*args, **kwargs)
        parser.formatter_class = RawTextHelpFormatter
        return parser

    def add_arguments(self, parser):
        # type: (ArgumentParser) -> None
        parser.add_argument('-s', '--streams',
                            dest='streams',
                            type=str,
                            help='A comma-separated list of stream names.')
        self.add_realm_args(parser, True)

    def handle(self, **options):
        # type: (**str) -> None
        realm = self.get_realm(options)
        if options["streams"] is None:
            print("Please provide a default set of streams (which can be empty,\
with `--streams=`).", file=sys.stderr)
            exit(1)
        realm = self.get_realm(options)

        stream_dict = {
            stream.strip(): {"description": stream.strip(), "invite_only": False}
            for stream in options["streams"].split(",")
        }  # type: Dict[Text, Dict[Text, Any]]

        set_default_streams(realm, stream_dict)


text:
//
//  CZNetworkManager.m
//  网易新闻
//
//  Created by apple on 16/6/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "CZNetworkManager.h"

@implementation CZNetworkManager

+ (instancetype)sharedManager {
    static CZNetworkManager *instance;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        // 末尾要有反斜线
        NSURL *baseURL = [NSURL URLWithString:@"http://c.m.163.com/nc/article/"];

        instance = [[self alloc] initWithBaseURL:baseURL];

        // 设置相应的解析格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });

    return instance;
}

#pragma mark - 封装 AFN 网络请求
/**
 * 发起 GET 请求 - 之所以封装 GET 方法,为了保证替换网络框架使用!
 *
 * @param URLString  URLString
 * @param parameters 参数字典
 * @param completion 完成回调[json(字典/数组),错误]
 */
- (void)GETRequest:(NSString *)URLString parameters:(NSDictionary *)parameters completion:(void (^)(id json, NSError *error))completion {

    [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        completion(responseObject, nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"网络请求失败 %@", error);

        completion(nil, error);
    }];
}

#pragma mark - 网易新闻接口
- (void)newsListWithChannel:(NSString *)channel start:(NSInteger)start completion:(void (^)(NSArray *, NSError *))completion {

    NSString *urlString = [NSString stringWithFormat:@"list/%@/%zd-20.html", channel, start];

    [self GETRequest:urlString parameters:nil completion:^(id json, NSError *error) {

        // 使用频道作为 key 获取数组
        NSArray *array = json[channel];

        completion(array, error);
    }];
}

@end


text:
/* plainreader.js
part of PlainReader by Luke Hagan
created: 2012-04-13
released under the MIT license (see LICENSE.md for details) */

var PR = {};


text:
package be.turbots.webtail;

public class ServerLog {

    private String name;
    private String url;
    private String filename;

    public String getName() {
        return name;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }
}


text:
require 'rubocop'
require 'fast_spec_helper'
require 'app/models/style_checker'
require 'app/models/file_violation'
require 'app/models/line_violation'

describe StyleChecker, '#violations' do
  context 'with violations' do
    it 'returns file violations' do
      modified_line = double(:modified_line, line_number: 1)
      modified_file = double(
        :modified_file,
        filename: 'foo.rb',
        contents: '1 + 1',
        relevant_line?: true,
        modified_lines: [modified_line],
        modified_line_at: modified_line
      )
      style_checker = StyleChecker.new([modified_file])

      expect(style_checker).to have(1).violations
      file_violation = style_checker.violations.first
      expect(file_violation.line_violations.first.line).to eq modified_line
    end

    it 'finds all violations' do
      file = file_stub(content_with_violations)
      style_checker = StyleChecker.new([file])

      violations = style_checker.violations

      violation_messages = violation_messages(violations)
      expect(violation_messages).to have(2).items
      expect(violation_messages[0]).to match(/parentheses/)
      expect(violation_messages[1]).to match(/single-quoted strings/)
    end

    context 'when custom configuration overrides quote rule' do
      it 'finds only one violation' do
        file = file_stub(content_with_violations)
        custom_config = <<-FILE
          StringLiterals:
            EnforcedStyle: double_quotes
            Enabled: true
        FILE
        style_checker = StyleChecker.new([file], custom_config)

        violations = style_checker.violations

        violation_messages = violation_messages(violations)
        expect(violation_messages).to have(1).items
        expect(violation_messages[0]).to match(/parentheses/)
        expect(violation_messages[0]).not_to match(/single-quoted strings/)
      end
    end

    def content_with_violations
      <<-EOL
        def test_method()
          "hello world"
        end
      EOL
    end
  end

  context 'when some files have violations' do
    it 'returns only the files with violations' do
      file1 = file_stub("def hi \n\tactive = true ")
      file2 = file_stub("def hello\nend\n")
      file3 = file_stub("class User  \nend\n")

      style_checker = StyleChecker.new([file1, file2, file3])
      violations = style_checker.violations

      expect(violations).to have(2).items
      expect(violations[0]).to have(2).line_violations
      expect(violations[0].line_violations[0]).to have(3).messages
      expect(violations[1]).to have(1).line_violations
    end

    it 'returns only one of each violation type' do
      file1 = file_stub("{ :first => 1, :second => 2 }\n")

      style_checker = StyleChecker.new([file1])
      violations = style_checker.violations

      expect(violations).to have(1).item
      expect(violations[0]).to have(1).line_violations
      expect(violations[0].line_violations[0]).to have(1).messages
    end
  end

  def file_stub(contents)
    double(
      filename: 'test_pr_file',
      contents: contents,
      relevant_line?: true
    ).as_null_object
  end

  def violation_messages(violations)
    violations.map(&:line_violations).flatten.map(&:messages).flatten
  end
end


text:
const path = require('path');
const tap = require('tap');
const {test} = tap;
const fs = require('fs');
const readFileToBuffer = require('../fixtures/readProjectFile').readFileToBuffer;
const dispatch = require('../../src/dispatch/central-dispatch');
const VirtualMachine = require('../../src/index');

/**
 * Call _stopLoop() on the Video Sensing extension.
 * @param {VirtualMachine} vm - a VM instance which has loaded the 'videoSensing' extension.
 */
const stopVideoLoop = vm => {
    // TODO: provide a general way to tell extensions to shut down
    // Ideally we'd just dispose of the extension's Worker...
    const serviceName = vm.extensionManager._loadedExtensions.get('videoSensing');
    dispatch.call(serviceName, '_stopLoop');
};

test('Load external extensions', async t => {
    const vm = new VirtualMachine();
    const testFiles = fs.readdirSync('./test/fixtures/load-extensions/confirm-load/');

    // Test each example extension file
    for (const file of testFiles) {
        const ext = file.split('-')[0];
        const uri = path.resolve(__dirname, `../fixtures/load-extensions/confirm-load/${file}`);
        const project = readFileToBuffer(uri);

        await t.test('Confirm expected extension is installed in example sb2 and sb3 projects', extTest => {
            vm.loadProject(project)
                .then(() => {
                    extTest.ok(vm.extensionManager.isExtensionLoaded(ext));
                    extTest.end();
                });
        });
    }

    stopVideoLoop(vm);
    vm.quit();
    t.end();
});

test('Load video sensing extension and video properties', async t => {
    const vm = new VirtualMachine();
    // An array of test projects and their expected video state values
    const testProjects = [
        {
            file: 'videoState-off.sb2',
            videoState: 'off',
            videoTransparency: 50,
            mirror: undefined
        },
        {
            file: 'videoState-on-transparency-0.sb2',
            videoState: 'on',
            videoTransparency: 0,
            mirror: true
        }];

    for (const project of testProjects) {
        const uri = path.resolve(__dirname, `../fixtures/load-extensions/video-state/${project.file}`);
        const projectData = readFileToBuffer(uri);

        await vm.loadProject(projectData);

        const stage = vm.runtime.getTargetForStage();

        t.ok(vm.extensionManager.isExtensionLoaded('videoSensing'));

        // Check that the stage target has the video state values we expect
        // based on the test project files, then check that the video io device
        // has the expected state as well
        t.equal(stage.videoState, project.videoState);
        t.equal(vm.runtime.ioDevices.video.mirror, project.mirror);
        t.equal(stage.videoTransparency, project.videoTransparency);
        t.equal(vm.runtime.ioDevices.video._ghost, project.videoTransparency);
    }

    stopVideoLoop(vm);
    vm.quit();
    t.end();
});


text:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Triangulation_vertex_base_2<K> Vb;
typedef CGAL::Delaunay_mesh_face_base_2<K> Fb;
typedef CGAL::Triangulation_data_structure_2<Vb, Fb> Tds;
typedef CGAL::Constrained_Delaunay_triangulation_2<K, Tds> CDT;
typedef CGAL::Delaunay_mesh_size_criteria_2<CDT> Criteria;

typedef CDT::Vertex_handle Vertex_handle;
typedef CDT::Point Point;

int main()
{
  CDT cdt;

  Vertex_handle va = cdt.insert(Point(-4,0));
  Vertex_handle vb = cdt.insert(Point(0,-1));
  Vertex_handle vc = cdt.insert(Point(4,0));
  Vertex_handle vd = cdt.insert(Point(0,1));
  cdt.insert(Point(2, 0.6));

  cdt.insert_constraint(va, vb);
  cdt.insert_constraint(vb, vc);
  cdt.insert_constraint(vc, vd);
  cdt.insert_constraint(vd, va);

  std::cout << "Number of vertices: " << cdt.number_of_vertices() << std::endl;

  std::cout << "Meshing the triangulation..." << std::endl;
  CGAL::refine_Delaunay_mesh_2(cdt, Criteria(0.125, 0.5));

  std::cout << "Number of vertices: " << cdt.number_of_vertices() << std::endl;
}


text:
package de.free_creations.editors.contest;

import de.free_creations.actions.contest.AllocateLocationForEvent;
import de.free_creations.dbEntities.Contest;
import de.free_creations.dbEntities.Event;
import de.free_creations.dbEntities.TimeSlot;
import de.free_creations.nbPhon4Netbeans.LocationNode;
import de.free_creations.nbPhonAPI.DataBaseNotReadyException;
import de.free_creations.nbPhonAPI.Manager;
import de.free_creations.nbPhonAPI.TimeSlotCollection;
import java.awt.Color;
import java.awt.Component;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import javax.swing.AbstractCellEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.TransferHandler;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

/**
 * The time table in the Contest Edit Window (ContestTopComponent).
 *
 * @author Harald Postner <Harald at free-creations.de>
 */
public class TimeTable extends JTable {

  private final TransferHandler transferHandler = new TransferHandler() {
    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {

        return (support.isDataFlavorSupported(LocationNode.LOCATION_NODE_FLAVOR));

    }

    @Override
    public boolean importData(TransferHandler.TransferSupport support) {
      try {
        Integer key = (Integer) support.getTransferable().getTransferData(LocationNode.LOCATION_NODE_FLAVOR);
        int col = getSelectedColumn();
        int row = getSelectedRow();
        if (col > 0) {
          Integer eventId = (Integer) getValueAt(row, col);
          if (eventId != null) {
            AllocateLocationForEvent action = new AllocateLocationForEvent(eventId, key);
            action.apply(0);
            return true;
          }
        }
        return false;

      } catch (DataBaseNotReadyException | ClassCastException | UnsupportedFlavorException | IOException ex) {
        return false;
      }
    }
  };

  /**
   * The CellAdaptor forwards "PROP_VALUE_CHANGED" messages from an individual
   * cell to the table model.
   */
  private class CellAdaptor implements PropertyChangeListener {

    private final int row;
    private final int col;

    public CellAdaptor(int row, int col) {
      this.row = row;
      this.col = col;

    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
      if (TimeTableCellPanel.PROP_VALUE_CHANGED.equals(evt.getPropertyName())) {
        ((AbstractTableModel) getModel()).fireTableCellUpdated(row, col);
      }
    }
  }

  private final MouseListener timeTableMouseListener = new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent evt) {
      if (evt.getClickCount() == 2) {
        int col = columnAtPoint(evt.getPoint());
        int row = rowAtPoint(evt.getPoint());

      }
    }
  };
  private final MouseListener headerMouseListener = new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent evt) {
      if (evt.getClickCount() == 2) {
        int col = columnAtPoint(evt.getPoint());

      }
    }
  };

  private final TableCellRenderer tableCellRenderer = new TableCellRenderer() {

    private final JLabel emptyLabel = new JLabel();

    @Override
    public Component getTableCellRendererComponent(
            JTable table,
            Object value,
            boolean isSelected,
            boolean hasFocus,
            int row, int column) {
      if (java.beans.Beans.isDesignTime()) {
        return new JLabel("designTime");
      }

      JComponent c = getBaseComponent(table, value, isSelected, row, column);
      if (hasFocus) {
        c.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
      } else {
        c.setBorder(null);
      }
      return c;
    }

    private JComponent getBaseComponent(
            JTable table,
            Object value,
            boolean isSelected,
            int row, int column) {
      if (!isCellVisible(row, column)) {
        // there is no time-slot for this cell
        return emptyLabel;
      }
      if (column == 0) {
        return getRowHeaderComponent(value);
      } else {
        TimeTableCellPanel panel = getTimeTableCellPanel(table, row, column);
        panel.setValue(value);
        panel.setSelected(isSelected);
        return panel;
      }
    }

    private final HashMap<String, JLabel> colHeaderCache = new HashMap<>();

    private JComponent getRowHeaderComponent(Object value) {
      if (value instanceof String) {
        String text = (String) value;
        if (!colHeaderCache.containsKey(text)) {
          JLabel newLabel = new JLabel(text);
          colHeaderCache.put(text, newLabel);
        }
        return colHeaderCache.get(text);
      } else {
        return emptyLabel;
      }
    }
  };

  private class TimeTableCellEditor extends AbstractCellEditor implements TableCellEditor {

    private final TimeTableCellEditorPanel panel;

    private TimeTableCellEditor() {
      this.panel = new TimeTableCellEditorPanel();
    }

    @Override
    public Object getCellEditorValue() {
      return panel.getEventId();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
            Object value,
            boolean isSelected,
            int row,
            int column) {
      panel.setValue(value);
      panel.setSelected(isSelected);
      return panel;
    }
  }

  private final TimeTableCellEditor tableCellEditor;

  public TimeTable() {
    super();
    TimeTableCellEditor _tableCellEditor = null;
    if (java.beans.Beans.isDesignTime()) {
      setModel(makeDesignTimeModel());
    } else {
      tableHeader.addMouseListener(headerMouseListener);
      addMouseListener(timeTableMouseListener);
      setCellSelectionEnabled(true);

      TimeTableModel timeTableModel = new TimeTableModel(null);
      setModel(timeTableModel);
      setDefaultRenderer(Integer.class, tableCellRenderer);
      _tableCellEditor = new TimeTableCellEditor();
      setTransferHandler(transferHandler);

    }
    tableCellEditor = _tableCellEditor;
    rowHeight = 42 + 2;
    gridColor = Color.lightGray;
    showHorizontalLines = true;
    showVerticalLines = true;
  }

  public void setContestId(Integer contestId) {
    TableModel oldModel = getModel();
    if (oldModel instanceof TimeTableModel) {
      TimeTableModel oldTimeModel = (TimeTableModel) oldModel;
      if (Objects.equals(contestId, oldTimeModel.getContestId())) {
        return;
      }
      oldTimeModel.stopListening();
    }

    TimeTableModel timeTableModel = new TimeTableModel(contestId);
    setModel(timeTableModel);
    timeTableModel.startListening();
  }

  /**
   * Avoid selection on the left-most column (the row-header column).
   *
   * @param row
   * @param column
   * @return true for all cells except those in column 0.
   */
//  @Override
//  public boolean isCellSelected(int row, int column) {
//    return (column > 0) ? super.isCellSelected(row, column) : false;
//  }

  /**
   * Cells that correspond to a time-slot that cannot be found in the "ZEIT"
   * table are overlaid with a blank label.
   *
   * @param renderer
   * @param row
   * @param column
   * @return
   */
//  @Override
//  public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
//    if (java.beans.Beans.isDesignTime()) {
//      return super.prepareRenderer(renderer, row, column);
//    }
//    if (isCellVisible(row, column)) {
//      if (column > 0) {
//        return new TimeTableCellPanel();
//      }
//      return super.prepareRenderer(renderer, row, column);
//    } else {
//      return new JLabel();
//    }
//  }
  /**
   * Provides the panels to be displayed in a cell (in browse mode).
   *
   * Each panel for a given row-col is cached.
   *
   * @param table
   * @param row
   * @param column
   * @return the cached panel (or construct a new new one if none can be found
   * in cache)
   */
  @Override
  public TableCellRenderer getCellRenderer(int row, int column) {
    if (column > 0) {
      return tableCellRenderer;
    }
    // else...
    return super.getCellRenderer(row, column);
  }

  private TimeTableCellPanel getTimeTableCellPanel(JTable table, int row, int column) {

    int hash = column * maxRows + row;
    if (!cellCache.containsKey(hash)) {
      TimeTableCellPanel timeTableCellPanel = new TimeTableCellPanel(
              new Color(170, 170, 170),
              table.getSelectionBackground(),
              table.getSelectionForeground());
      CellAdaptor cellAdaptor = new CellAdaptor(row, column);
      timeTableCellPanel.addPropertyChangeListener(cellAdaptor);
      cellCache.put(hash, timeTableCellPanel);
    }
    return cellCache.get(hash);
  }
  private final HashMap<Integer, TimeTableCellPanel> cellCache = new HashMap<>();
  private static final int maxRows = 10007;

  @Override
  public TableCellEditor getCellEditor(int row, int column) {
    if (column > 0) {
      if (tableCellEditor != null) {
        return tableCellEditor;
      }
    }
    return super.getCellEditor(row, column);

  }

  @Override
  public JPopupMenu getComponentPopupMenu() {
    int col = columnAtPoint(getMousePosition());
    int row = rowAtPoint(getMousePosition());
    if (col > 0) {
      TimeTableCellPanel timeTableCellPanel = getTimeTableCellPanel(this, row, col);
      return timeTableCellPanel.getComponentPopupMenu();
    } else {
      return null;
    }
  }

  /**
   * Cells that correspond to a time-slot that cannot be found in the "ZEIT"
   * table are overlaid with a blank label.
   *
   * @param editor
   * @param row
   * @param column
   * @return
   */
  @Override
  public Component prepareEditor(TableCellEditor editor, int row, int column) {
    if (java.beans.Beans.isDesignTime()) {
      return super.prepareEditor(editor, row, column);
    }
    if (isCellVisible(row, column)) {
      return super.prepareEditor(editor, row, column);
    } else {
      return new JLabel();
    }
  }

  /**
   * Decide which cells should be blanked out (be invisible).
   *
   * Cells that correspond to a time-slot that cannot be found in the "ZEIT"
   * table are overlaid with a blank label.
   *
   * @param row
   * @param column
   * @return true if the cell should be as normal.
   */
  private boolean isCellVisible(int row, int column) {
    if (column == 0) {
      return true;
    }
    try {
      TimeSlot t = Manager.getTimeSlotCollection().findEntity(column - 1, row);
      if (t == null) {
        return false;
      } else {
        return true;
      }
    } catch (DataBaseNotReadyException ex) {
      return false;
    }
  }

  /**
   * Returns the data model which shall be displayed at design time.
   *
   * @return a data model shows data similar to the runtime version.
   */
  private TableModel makeDesignTimeModel() {
    return (new javax.swing.table.DefaultTableModel(
            new Object[][]{
              {"Vormittag", true, null, null, null, true, null, null},
              {"Nachmittag", null, true, null, true, null, null, null},
              {"Abend", null, null, true, false, null, null, null}},
            new String[]{
              ".Design.", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"
            }) {
              @Override
              public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex > 0) {
                  return Boolean.class;
                } else {
                  return String.class;
                }
              }
            });
  }

  /**
   * The table model used in the TimeTable.
   */
  public class TimeTableModel extends AbstractTableModel implements PropertyChangeListener {

    private final Integer contestId;
    private final String[] timeOfDayNames;
    private final String[] dayNames;
    private final int columnCount; // the number of data columns (first column not included)
    private final int rowCount; // the number of data rows (header row not included)

    public TimeTableModel(Integer contestId) {
      this.contestId = contestId;

      TimeSlotCollection tt = Manager.getTimeSlotCollection();

      dayNames = tt.dayNames();
      columnCount = dayNames.length;

      timeOfDayNames = tt.timeOfDayNames();
      rowCount = timeOfDayNames.length;
    }

    @Override
    public int getRowCount() {
      return rowCount;
    }

    @Override
    public int getColumnCount() {
      return columnCount + 1;
    }

    /**
     * Get the value that shall be displayed in the given position (including
     * the row headers).
     *
     * @param rowIndex
     * @param columnIndex the column relative to the table.
     * @return
     */
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
      if (columnIndex == 0) {
        return timeOfDayNames[rowIndex];
      } else {
        return getEventIdFor(rowIndex, columnIndex);
      }
    }

    private Integer getEventIdFor(int rowIndex, int columnIndex) {
      if (contestId == null) {
        return null;
      }
      TimeSlot t = getTimeSlotFor(rowIndex, columnIndex);
      if (t == null) {
        return null;
      }
      //--- retrieve the events which happen at the given time-slot.
      List<Event> eventList = t.getEventList();
      //--- within those events, search for the (first) event that happens
      //    for the given contest (note: here we could check that never two or
      //    more events happen for the same contest at the same time(slot).
      for (Event e : eventList) {
        Contest contest = e.getContest();
        if (contest != null) {
          if (Objects.equals(contest.getContestId(), contestId)) {
            return e.getEventId();
          }
        }
      }
      return null;
    }

    @Override
    public String getColumnName(int column) {
      if (column == 0) {
        return "";
      } else {
        return dayNames[column - 1];
      }
    }

    /**
     *
     * @param columnIndex
     * @return String for column 0, Integer for all other.
     */
    @Override
    public Class<?> getColumnClass(int columnIndex) {
      if (columnIndex > 0) {
        return String.class;
      } else {
        return Integer.class;
      }
    }

    @Override
    public boolean isCellEditable(int row, int column) {
      return ((column > 0) && (contestId != null));
    }

    /**
     * un-subscribe to listen on changes on the contest.
     */
    private void stopListening() {
      if (contestId != null) {
        Contest.removePropertyChangeListener(this, contestId);
      }
    }

    /**
     * Subscribe to listen on changes on the contest.
     */
    public void startListening() {
      if (contestId != null) {
        Contest.addPropertyChangeListener(this, contestId);
      }
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
    }

    private Integer getContestId() {
      return contestId;
    }

    private TimeSlot getTimeSlotFor(int rowIndex, int columnIndex) {
      if (columnIndex < 1) {
        return null;
      }
      int day = columnIndex - 1;
      int timeOfDay = rowIndex;
      try {
        return Manager.getTimeSlotCollection().findEntity(day, timeOfDay);
      } catch (DataBaseNotReadyException ex) {
        return null;
      }
    }
  }
}


text:
<?php

namespace Oro\Component\Layout\Tests\Unit\Extension\DependencyInjection;

use Oro\Component\Layout\Extension\DependencyInjection\DependencyInjectionExtension;
use Oro\Component\Layout\LayoutItemInterface;

class DependencyInjectionExtensionTest extends \PHPUnit\Framework\TestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject */
    protected $container;

    /** @var DependencyInjectionExtension */
    protected $extension;

    protected function setUp()
    {
        $this->container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $this->extension = new DependencyInjectionExtension(
            $this->container,
            ['test' => 'block_type_service'],
            ['test' => ['block_type_extension_service']],
            ['test' => ['layout_update_service']],
            ['context_configurator_service'],
            ['test' => 'data_provider_service']
        );
    }

    public function testHasType()
    {
        $this->assertTrue($this->extension->hasType('test'));
        $this->assertFalse($this->extension->hasType('unknown'));
    }

    public function testGetType()
    {
        $type = $this->createMock('Oro\Component\Layout\BlockTypeInterface');
        $type->expects($this->once())
            ->method('getName')
            ->will($this->returnValue('test'));

        $this->container->expects($this->once())
            ->method('get')
            ->with('block_type_service')
            ->will($this->returnValue($type));

        $this->assertSame($type, $this->extension->getType('test'));
    }

    // @codingStandardsIgnoreStart
    /**
     * @expectedException \Oro\Component\Layout\Exception\InvalidArgumentException
     * @expectedExceptionMessage The type name specified for the service "block_type_service" does not match the actual name. Expected "test", given "test1".
     */
    // @codingStandardsIgnoreEnd
    public function testGetTypeWithInvalidAlias()
    {
        $type = $this->createMock('Oro\Component\Layout\BlockTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('test1'));

        $this->container->expects($this->once())
            ->method('get')
            ->with('block_type_service')
            ->will($this->returnValue($type));

        $this->extension->getType('test');
    }

    /**
     * @expectedException \Oro\Component\Layout\Exception\InvalidArgumentException
     * @expectedExceptionMessage The block type "unknown" is not registered with the service container.
     */
    public function testGetUnknownType()
    {
        $this->extension->getType('unknown');
    }

    public function testHasTypeExtensions()
    {
        $this->assertTrue($this->extension->hasTypeExtensions('test'));
        $this->assertFalse($this->extension->hasTypeExtensions('unknown'));
    }

    public function testGetTypeExtensions()
    {
        $typeExtension = $this->createMock('Oro\Component\Layout\BlockTypeExtensionInterface');

        $this->container->expects($this->once())
            ->method('get')
            ->with('block_type_extension_service')
            ->will($this->returnValue($typeExtension));

        $typeExtensions = $this->extension->getTypeExtensions('test');
        $this->assertCount(1, $typeExtensions);
        $this->assertSame($typeExtension, $typeExtensions[0]);
    }

    public function testGetUnknownBlockTypeExtensions()
    {
        $this->assertSame([], $this->extension->getTypeExtensions('unknown'));
    }

    public function testHasLayoutUpdates()
    {
        $this->assertTrue($this->extension->hasLayoutUpdates($this->getLayoutItem('test')));
        $this->assertFalse($this->extension->hasLayoutUpdates($this->getLayoutItem('unknown')));

        // test by alias
        $layoutItem = $this->getLayoutItem('unknown');
        $layoutItem->expects($this->once())->method('getAlias')->willReturn('test');
        $this->assertTrue($this->extension->hasLayoutUpdates($layoutItem));
    }

    public function testGetLayoutUpdates()
    {
        $layoutUpdate = $this->createMock('Oro\Component\Layout\LayoutUpdateInterface');

        $this->container->expects($this->exactly(2))
            ->method('get')
            ->with('layout_update_service')
            ->will($this->returnValue($layoutUpdate));

        $layoutUpdates = $this->extension->getLayoutUpdates($this->getLayoutItem('test'));
        $this->assertCount(1, $layoutUpdates);
        $this->assertSame($layoutUpdate, $layoutUpdates[0]);

        // test by alias
        $layoutItem = $this->getLayoutItem('unknown');
        $layoutItem->expects($this->once())->method('getAlias')->willReturn('test');
        $this->assertCount(1, $this->extension->getLayoutUpdates($layoutItem));
        $this->assertSame($layoutUpdate, $layoutUpdates[0]);
    }

    public function testGetUnknownBlockLayoutUpdates()
    {
        $this->assertSame([], $this->extension->getLayoutUpdates($this->getLayoutItem('unknown')));
    }

    public function testHasContextConfigurators()
    {
        $this->assertTrue($this->extension->hasContextConfigurators());
    }

    public function testGetContextConfigurators()
    {
        $configurator = $this->createMock('Oro\Component\Layout\ContextConfiguratorInterface');

        $this->container->expects($this->once())
            ->method('get')
            ->with('context_configurator_service')
            ->will($this->returnValue($configurator));

        $result = $this->extension->getContextConfigurators();
        $this->assertCount(1, $result);
        $this->assertSame($configurator, $result[0]);
    }

    public function testHasContextConfiguratorsWhenNoAnyRegistered()
    {
        $extension = new DependencyInjectionExtension($this->container, [], [], [], [], []);

        $this->assertFalse($extension->hasContextConfigurators());
    }

    public function testGetContextConfiguratorsWhenNoAnyRegistered()
    {
        $extension = new DependencyInjectionExtension($this->container, [], [], [], [], []);

        $this->assertSame([], $extension->getContextConfigurators());
    }

    public function testHasDataProvider()
    {
        $this->assertTrue($this->extension->hasDataProvider('test'));
        $this->assertFalse($this->extension->hasDataProvider('unknown'));
    }

    public function testGetDataProvider()
    {
        $dataProvider = $this->createMock(\stdClass::class);

        $this->container->expects($this->once())
            ->method('get')
            ->with('data_provider_service')
            ->will($this->returnValue($dataProvider));

        $this->assertSame($dataProvider, $this->extension->getDataProvider('test'));
    }

    /**
     * @expectedException \Oro\Component\Layout\Exception\InvalidArgumentException
     * @expectedExceptionMessage The data provider "unknown" is not registered with the service container.
     */
    public function testGetUnknownDataProvider()
    {
        $this->extension->getDataProvider('unknown');
    }

    /**
     * @param string $id
     *
     * @return \PHPUnit\Framework\MockObject\MockObject|LayoutItemInterface
     */
    protected function getLayoutItem($id)
    {
        $layoutItem = $this->createMock('Oro\Component\Layout\LayoutItemInterface');
        $layoutItem->expects($this->any())->method('getId')->willReturn($id);

        return $layoutItem;
    }
}


text:
/* monster template
	{name: '',		maxHealth: ,	dmg: , dex: },
*/

var monsterData = [
    {name: 'Sleazy Hacker',			maxHealth: 20,	dmg: 5, dex: 2},
    {name: 'Sloppy Racketeer',		maxHealth: 25,	dmg: 3, dex: 8},
    {name: 'Counterfeiter',			maxHealth: 20,	dmg: 8, dex: 5},
    {name: 'Hi-tech Robber',		maxHealth: 50,	dmg: 2, dex: 1},
    {name: 'Android Husk',			maxHealth: 600,	dmg: 100, dex: 80},
    {name: 'Mech',					maxHealth: 400,	dmg: 300, dex: 20},
    {name: 'Cyborg',				maxHealth: 1200,	dmg: 200, dex: 160},
    {name: 'Combat Engineer',		maxHealth: 6000,	dmg: 800, dex: 600},
    {name: 'Mob',					maxHealth: 6000,	dmg: 800, dex: 600},
    {name: 'Nanoborg',				maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Rick Deckard',			maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Al Mechapone',				maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Future Cop',				maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Spec Ops Soldier',				maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Spec Ops Shifter',				maxHealth: 100000,	dmg: 9001, dex: 3000},
    {name: 'Tron',					maxHealth: 100000,	dmg: 9001, dex: 3000}

];

/* BUILDERS */
function buildMonster(state){
	state.monsters = state.game.add.group();
	var monster;
	monsterData.forEach(function(data) {
	    // create a sprite for them off screen
	    monster = state.monsters.create(1000, state.game.world.centerY, data.image);
	    // center anchor
	    monster.anchor.setTo(0.5);
	    // reference to the database
	    monster.details = data;

	    monster.health = monster.maxHealth = data.maxHealth;

		monster.inputEnabled = true; //enable input so we can click it!
	    monster.events.onInputDown.add(state.onClickMonster, state);
	    monster.events.onKilled.add(state.onKilledMonster, state);
	    monster.events.onRevived.add(state.onRevivedMonster, state);
	});

}

function buildMonsterUI(state) {
	state.monsterInfoUI = state.game.add.group();
	state.monsterInfoUI.position.setTo(state.currentMonster.x - 220, state.currentMonster.y + 120);
	state.monsterNameText = state.monsterInfoUI.addChild(state.game.add.text(0,0, state.currentMonster.details.name, {
		font:'48px Arial Black',
		fill:'#fff',
		strokeThickness:4
	}));

	state.monsterHealthText = state.monsterInfoUI.addChild(state.game.add.text(0, 80, state.currentMonster.health + ' HP', {
		font: '32px Arial Black',
		fill: '#ff0000',
		strokeThickness: 4
	}));
}

/* methods */

function spawnRandomMonster(state) {
	state.currentMonster = state.monsters.getRandom();
	state.currentMonster.position.set(state.game.world.centerX + 100, state.game.world.centerY);
}


text:
import json
import logging

import django
django.setup()
from django.core.management.base import BaseCommand
from django.db import transaction

from osf.models import PreprintProvider, PreprintService, Subject
from scripts import utils as script_utils
from website.project.taxonomies import validate_subject_hierarchy

logger = logging.getLogger(__name__)

BEPRESS_PROVIDER = PreprintProvider.objects.filter(_id='osf').first()

def validate_input(custom_provider, data):
    logger.info('Validating data')
    assert data.get('include'), 'Must specify Subjects to recursively include with `include`.'
    includes = data.get('include')
    excludes = data.get('exclude', [])
    customs = data.get('custom', {})
    for text in includes:
        assert Subject.objects.filter(provider=BEPRESS_PROVIDER, text=text).exists(), 'Unable to find included subject with text {}'.format(text)
    included_subjects = Subject.objects.filter(provider=BEPRESS_PROVIDER, text__in=includes).include_children()
    logger.info('Successfully validated `include`')
    for text in excludes:
        excluded = Subject.objects.get(provider=BEPRESS_PROVIDER, text=text)  # May raise not found error
        assert excluded.object_hierarchy[0].text in includes, 'Excluded subject with text {} was not included'.format(text)
    included_subjects.exclude(text__in=excludes)
    logger.info('Successfully validated `exclude`')
    for cust_name, map_dict in customs.iteritems():
        assert not included_subjects.filter(text=cust_name).exists(), 'Custom text {} already exists in mapped set'.format(cust_name)
        assert Subject.objects.filter(provider=BEPRESS_PROVIDER, text=map_dict.get('bepress')).exists(), 'Unable to find specified BePress subject with text {}'.format(map_dict.get('bepress'))
        if map_dict.get('parent'):  # Null parent possible
            assert map_dict['parent'] in set(customs.keys()) | set(included_subjects.values_list('text', flat=True)), 'Unable to find specified parent with text {} in mapped set'.format(map_dict['parent'])
            # TODO: hierarchy length validation? Probably more trouble than worth here, done on .save
    logger.info('Successfully validated `custom`')
    included_subjects = included_subjects | Subject.objects.filter(text__in=[map_dict['bepress'] for map_dict in customs.values()])
    missing_subjects = Subject.objects.filter(id__in=set([hier[-1].id for ps in PreprintService.objects.filter(provider=custom_provider) for hier in ps.subject_hierarchy])).exclude(id__in=included_subjects.values_list('id', flat=True))
    assert not missing_subjects.exists(), 'Incomplete mapping -- following subjects in use but not included:\n{}'.format(missing_subjects.all())
    logger.info('Successfully validated mapping completeness')

def create_subjects_recursive(custom_provider, root_text, exclude_texts, parent=None):
    logger.info('Duplicating BePress subject {} on {}'.format(root_text, custom_provider._id))
    bepress_subj = Subject.objects.get(provider=BEPRESS_PROVIDER, text=root_text)
    custom_subj = Subject(text=root_text, parent=parent, bepress_subject=bepress_subj, provider=custom_provider)
    custom_subj.save()
    # This is not a problem now, as all excluded subjects are leafs, but it could be problematic if non-leafs had their children excluded.
    # It could also be problematic if they didn't, if any of those children are used by existing preprints.
    # TODO: Determine correct resolution
    for child_text in bepress_subj.children.exclude(text__in=exclude_texts).values_list('text', flat=True):
        create_subjects_recursive(custom_provider, child_text, exclude_texts, parent=custom_subj)

def do_create_subjects(custom_provider, includes, excludes):
    for root_text in includes:
        create_subjects_recursive(custom_provider, root_text, excludes)

def map_custom_subject(custom_provider, name, parent, mapping):
    logger.info('Attempting to create subject {} on {} from {} with {}'.format(name, custom_provider._id, mapping, 'parent {}'.format(parent) if parent else 'no parent'))
    if parent:
        parent_subject = Subject.objects.filter(provider=custom_provider, text=parent).first()
    else:
        parent_subject = None
    bepress_subject = Subject.objects.get(provider=BEPRESS_PROVIDER, text=mapping)
    if parent and not parent_subject:
        return False
    custom_subject = Subject(provider=custom_provider, text=name, parent=parent_subject, bepress_subject=bepress_subject)
    custom_subject.save()
    return True

def do_custom_mapping(custom_provider, customs):
    tries = 0
    unmapped_customs = customs
    previous_len = len(unmapped_customs)
    while len(unmapped_customs):
        tries += 1
        if tries == 10:
            raise RuntimeError('Unable to map custom subjects with 10 iterations -- invalid input')
        successes = []
        for cust_name, map_dict in unmapped_customs.iteritems():
            if map_custom_subject(custom_provider, cust_name, map_dict.get('parent'), map_dict.get('bepress')):
                successes.append(cust_name)
            else:
                logger.warn('Failed. Retrying next iteration')
        [unmapped_customs.pop(key) for key in successes]
        new_len = len(unmapped_customs)
        if new_len == previous_len:
            raise RuntimeError('Unable to map any custom subjects on iteration -- invalid input')

def map_preprints_to_custom_subjects(custom_provider):
    for preprint in PreprintService.objects.filter(provider=custom_provider):
        logger.info('Preparing to migrate preprint {}'.format(preprint.id))
        old_hier = preprint.subject_hierarchy
        subject_ids_to_map = [hier[-1].id for hier in old_hier]
        aliased_subject_ids = set(Subject.objects.filter(bepress_subject__id__in=subject_ids_to_map, provider=custom_provider).values_list('id', flat=True))
        aliased_hiers = [s.object_hierarchy for s in Subject.objects.filter(id__in=aliased_subject_ids)]
        preprint.subjects.clear()
        for hier in aliased_hiers:
            validate_subject_hierarchy([s._id for s in hier])
            for s in hier:
                preprint.subjects.add(s)
        preprint.save()
        preprint.reload()
        new_hier = [s.object_hierarchy for s in preprint.subjects.exclude(children__in=preprint.subjects.all())]
        logger.info('Successfully migrated preprint {}.\n\tOld hierarchy:{}\n\tNew hierarchy:{}'.format(preprint.id, old_hier, new_hier))

def migrate(provider=None, data=None):
    custom_provider = PreprintProvider.objects.filter(_id=provider).first()
    assert custom_provider, 'Unable to find specified provider: {}'.format(provider)
    assert custom_provider.id != BEPRESS_PROVIDER.id, 'Cannot add custom mapping to BePress provider'
    validate_input(custom_provider, data)
    do_create_subjects(custom_provider, data['include'], data.get('exclude', []))
    do_custom_mapping(custom_provider, data.get('custom', {}))
    map_preprints_to_custom_subjects(custom_provider)

class Command(BaseCommand):
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Run migration and roll back changes to db',
        )
        parser.add_argument(
            '--data',
            action='store',
            dest='data',
            required=True,
            help='List of targets, of form {\n"include": [<list of subject texts to include at top level, children implicit>],'
            '\n"exclude": [<list of children to exclude from included trees>],'
            '\n"custom": [{"<Custom Name": {"parent": <Parent text>", "bepress": "<Bepress Name>"}}, ...]}',
        )
        parser.add_argument(
            '--provider',
            action='store',
            dest='provider',
            required=True,
            help='_id of the PreprintProvider object, e.g. "osf"'
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run')
        provider = options['provider']
        data = options['data']
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
        with transaction.atomic():
            migrate(provider=provider, data=json.loads(data))
            if dry_run:
                raise RuntimeError('Dry run, transaction rolled back.')


text:
package com.google.gerrit.acceptance.api.change;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.extensions.api.changes.FixInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.client.ChangeStatus;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.ProblemInfo;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.project.ChangeControl;
import com.google.inject.Inject;

import org.junit.Test;

import java.util.Collections;
import java.util.List;

@NoHttpd
public class CheckIT extends AbstractDaemonTest {
  @Inject
  private ChangeControl.GenericFactory changeControlFactory;

  @Inject
  private IdentifiedUser.GenericFactory userFactory;

  @Inject
  private ChangeUpdate.Factory changeUpdateFactory;

  // Most types of tests belong in ConsistencyCheckerTest; these mostly just
  // test paths outside of ConsistencyChecker, like API wiring.
  @Test
  public void currentPatchSetMissing() throws Exception {
    PushOneCommit.Result r = createChange();
    Change c = getChange(r);
    db.patchSets().deleteKeys(Collections.singleton(c.currentPatchSetId()));
    indexer.index(db, c);

    List<ProblemInfo> problems = gApi.changes()
        .id(r.getChangeId())
        .check()
        .problems;
    assertThat(problems).hasSize(1);
    assertThat(problems.get(0).message)
        .isEqualTo("Current patch set 1 not found");
  }

  @Test
  public void fixReturnsUpdatedValue() throws Exception {
    PushOneCommit.Result r = createChange();
    gApi.changes()
        .id(r.getChangeId())
        .revision(r.getCommit().name())
        .review(ReviewInput.approve());
    gApi.changes()
        .id(r.getChangeId())
        .revision(r.getCommit().name())
        .submit();

    Change c = getChange(r);
    c.setStatus(Change.Status.NEW);
    db.changes().update(Collections.singleton(c));
    ChangeUpdate changeUpdate =
        changeUpdateFactory.create(
            changeControlFactory.controlFor(
                c, userFactory.create(admin.id)));
    changeUpdate.setStatus(Change.Status.NEW);
    changeUpdate.commit();
    indexer.index(db, c);

    ChangeInfo info = gApi.changes()
        .id(r.getChangeId())
        .check();
    assertThat(info.problems).hasSize(1);
    assertThat(info.problems.get(0).status).isNull();
    assertThat(info.status).isEqualTo(ChangeStatus.NEW);

    info = gApi.changes()
        .id(r.getChangeId())
        .check(new FixInput());
    assertThat(info.problems).hasSize(1);
    assertThat(info.problems.get(0).status).isEqualTo(ProblemInfo.Status.FIXED);
    assertThat(info.status).isEqualTo(ChangeStatus.MERGED);

    info = gApi.changes()
        .id(r.getChangeId())
        .get();
    assertThat(info.status).isEqualTo(ChangeStatus.MERGED);
  }

  private Change getChange(PushOneCommit.Result r) throws Exception {
    return db.changes().get(new Change.Id(
        gApi.changes().id(r.getChangeId()).get()._number));
  }
}


text:
import { GraphQLList as ListType } from 'graphql';
import PlantType from '../types/PlantType';
import { Plant, Attribute } from '../models';

async function getPlantsShop() {
  const plants = await Plant.findAll({
    attributes: [
      'name',
      'description',
      'pictureUrl',
      'price',
      'maxMana',
      'manaPerSec',
    ],
    where: {},
    include: [
      {
        model: Attribute,
        as: 'attributes',
        through: { attributes: ['value'] },
      },
    ],
  });
  /* .then(plant => {
    console.log(plant[0].dataValues.attributes[0]);
  }); */
  return plants;
}

const plantsShop = {
  type: new ListType(PlantType),
  resolve() {
    const plants = getPlantsShop();
    console.log(plants);
    return plants;
  },
};

export default plantsShop;


text:
package com.loomcom.symon;

import com.loomcom.symon.exceptions.*;

/**
 * MemoryRange is a simple container class representing a literal
 * range of memory, with a staraddress, and an end address.  It has
 * guards against creating impossible memory ranges, and implements
 * some useful methods for checking address inclusion and range
 * overlaps.
 */
public class MemoryRange implements Comparable<MemoryRange> {

    /**
     * The starting address of the memory range.
     */
    public int startAddress;
    /**
     * The ending address of the memory range.
     */
    public int endAddress;

    public MemoryRange(int startAddress, int endAddress)
            throws MemoryRangeException {
        if (startAddress < 0 || endAddress < 0) {
            throw new MemoryRangeException("Addresses cannot be less than 0.");
        }
        if (startAddress >= endAddress) {
            throw new MemoryRangeException("End address must be greater " +
                    "than start address.");
        }
        this.startAddress = startAddress;
        this.endAddress = endAddress;
    }

    /**
     * @return the starting address.
     */
    public int startAddress() {
        return startAddress;
    }

    /**
     * @return the ending address.
     */
    public int endAddress() {
        return endAddress;
    }

    /**
     * Checks for address inclusion in the range.
     *
     * @return true if the address is included within this range,
     * false otherwise.
     */
    public boolean includes(int address) {
        return (address <= endAddress &&
                address >= startAddress);
    }

    /**
     * Checks for overlapping memory ranges.
     *
     * @return true if this range overlaps in any way with the other.
     */
    public boolean overlaps(MemoryRange other) {
        return (this.includes(other.startAddress()) ||
                other.includes(this.startAddress()));
    }

    // Implementation of Comparable interface
    public int compareTo(MemoryRange other) {
        if (other == null) {
            throw new NullPointerException("Cannot compare to null.");
        }
        if (this == other) {
            return 0;
        }
        Integer thisStartAddr = this.startAddress();
        Integer thatStartAddr = other.startAddress();
        return thisStartAddr.compareTo(thatStartAddr);
    }

    public String toString() {
        return "@" + String.format("0x%04x", startAddress) + "-" +
                String.format("0x%04x", endAddress);
    }
}


text:
<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>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <netty.version>4.0.30.Final</netty.version>
        <source.version>1.7</source.version>
        <target.version>1.7</target.version>
        <bintray.repo>andsel/maven</bintray.repo>
        <bintray.parent.package>org.dna.mqtt.moquette-parent</bintray.parent.package>
        <moquette.version>0.8-SNAPSHOT</moquette.version>
    </properties>

    <groupId>org.eclipse.moquette</groupId>
    <artifactId>moquette-parent</artifactId>

    <packaging>pom</packaging>
    <version>${moquette.version}</version>
    <name>Moquette MQTT parent</name>
    <url>https://github.com/andsel/moquette/</url>

    <developers>
        <developer>
            <id>andsel</id>
            <name>Andrea Selva</name>
            <roles>
                <role>architect</role>
                <role>developer</role>
                <role>founder</role>
            </roles>
            <timezone>+1</timezone>
        </developer>
    </developers>

    <contributors>
        <contributor>
            <name>Steven Warwick</name>
            <url>http://stevenwarwick.com</url>
        </contributor>
        <contributor>
            <name>Igor Yova</name>
            <url>https://github.com/Fameing</url>
        </contributor>
        <contributor>
            <name>Luca Capra</name>
            <url>https://github.com/muka</url>
        </contributor>
        <contributor>
            <name>Wagner Macedo</name>
            <url>https://github.com/wagnerluis1982</url>
        </contributor>
    </contributors>

    <modules>
        <module>parser_commons</module>
        <module>netty_parser</module>
        <module>broker</module>
        <module>distribution</module>
        <module>embedding_moquette</module>
    </modules>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.6</version>
            </plugin>
        </plugins>
    </reporting>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${source.version}</source>
                    <target>${target.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>Paho Releases</id>
            <url>https://repo.eclipse.org/content/repositories/paho-releases/</url>
        </repository>

        <repository>
            <id>sonatype-snapshots</id>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </repository>
    </repositories>

    <distributionManagement>
        <repository>
            <id>bintray</id>
            <url>https://api.bintray.com/maven/${bintray.repo}/${bintray.parent.package}</url>
        </repository>
    </distributionManagement>
</project>


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

<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net http://dozer.sourceforge.net/schema/beanmapping.xsd">

  <mapping>
    <class-a>org.dozer.vo.inheritance.hints.Source</class-a>
    <class-b>org.dozer.vo.inheritance.hints.Target</class-b>
    <field>
      set
      set

        org.dozer.vo.inheritance.hints.BaseA,
        org.dozer.vo.inheritance.hints.BaseB

        org.dozer.vo.inheritance.hints.BaseA2,
        org.dozer.vo.inheritance.hints.BaseB2

    </field>
  </mapping>

  <mapping>
    <class-a>org.dozer.vo.inheritance.hints.BaseA</class-a>
    <class-b>org.dozer.vo.inheritance.hints.BaseA2</class-b>
  </mapping>

  <mapping>
    <class-a>org.dozer.vo.inheritance.hints.BaseB</class-a>
    <class-b>org.dozer.vo.inheritance.hints.BaseB2</class-b>
  </mapping>

</mappings>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Práctica1deEstructuradedatos.byTeo.: Colores y flechas del Gráfico</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Práctica1deEstructuradedatos.byTeo.

Página principal

Clases

Archivos

          <input type="text" id="MSearchField" value="Buscar" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Colores y flechas del Gráfico

Esta página explica como interpretar los gráficos que son generados por doxygen.

Considere el siguiente ejemplo:

    1 /*! Clase invisible por truncamiento */

    2 class Invisible { };

    3

    4 /*! Clase truncada, relación de herencia escondida */

    5 class Truncated : public Invisible { };

    6

    7 /* Clase no documentada con comentarios de doxygen */

    8 class Undocumented { };

    9

   10 /*! Clase que es heredera usando herencia publica */

   11 class PublicBase : public Truncated { };

   12

   13 /*! Clase plantilla */

   14 template<class T> class Templ { };

   15

   16 /*! Clase que es heredera usando herencia protegida  */

   17 class ProtectedBase { };

   18

   19 /*! Clase que es heredera usando herencia privada  */

   20 class PrivateBase { };

   21

   22 /*! Clase que es usada por la clase heredada */

   23 class Used { };

   24

   25 /*! Super-Clase que hereda de varias otras clases */

   26 class Inherited : public PublicBase,

   27                   protected ProtectedBase,

   28                   private PrivateBase,

   29                   public Undocumented,

   30                   public Templ<int>

   31 {

   32   private:

   33     Used *m_usedClass;

   34 };

 Dará como resultado el siguiente gráfico:

Las cajas en el gráfico arriba tienen el siguiente significado:

Una caja llena gris representa la estructura o clase para la cuálse generó el gráfico.

Una caja con borde negro señala una estructura o clase documentada.

Una caja con borde griz señala una estructura o clase no documentada.

una caja con borde rojo señala una estructura o clase documentada de la cuál no toda las relaciones de jerarquía/contenido son mostradas. El gráfico sera truncado si este no calza dentro de los límites especificados.

Las flechas tienen el siguiente significado:

Una flecha azul oscuro es usada para visualizar una relación herencia publica entre dos clases.

Una flecha verde oscuro es usada para herencia protegida.

Una flecha rojo oscuro es usada para herencia privada.

Una flecha segmentada púrpura se usa si la clase es contenida o usada por otra clase. La flecha está etiquetada por la variable con que se accede a la clase o estructura apuntada.

Una flecha segmentada amarilla indica la relación entre una instancia template y la clase template de la que se ha instanciado. La flecha se etiqueta con los parámetros con que se llama al template.

<address class="footer">
Generado por

 1.8.9.1
</address>


text:
from __future__ import unicode_literals

import datetime
from functools import update_wrapper

from django.contrib import admin, messages
from django.contrib.admin.helpers import AdminErrorList, AdminForm
from django.contrib.auth import get_permission_codename
from django.contrib.auth.admin import csrf_protect_m
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.shortcuts import redirect
from django.template.defaultfilters import slugify, yesno
from django.template.response import TemplateResponse
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _
from tablib import Dataset

from .conf import settings
from .forms import SubmissionExportForm
from .models import Form, FormSubmission

try:
    from django.contrib.admin.options import IS_POPUP_VAR
except ImportError:
    IS_POPUP_VAR = '_popup'

try:
    from django.contrib.admin.utils import unquote
except ImportError:
    from django.contrib.admin.util import unquote

try:
    from django.http import JsonResponse
except ImportError:
    from .compat import JsonResponse

class FormFilter(admin.SimpleListFilter):
    title = _('Forms')
    parameter_name = 'form'

    def lookups(self, request, model_admin):
        forms = Form.active_objects.all()
        for obj in forms:
            yield (
                str(obj.id), u'%s (%s)' % (obj.name, obj.submission_count)
            )

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(plugin_id=self.value())

class FormSubmissionAdmin(admin.ModelAdmin):
    change_form_template = 'admin/djangocms_forms/formsubmission/change_form.html'
    change_list_template = 'admin/djangocms_forms/formsubmission/change_list.html'
    export_form_template = 'admin/djangocms_forms/formsubmission/export_form.html'
    list_display = ('plugin', 'creation_date_display', 'created_by', 'ip', 'referrer', )
    list_filter = (FormFilter, )
    readonly_fields = ('creation_date_display', 'created_by', 'plugin', 'ip', 'referrer', )
    date_hierarchy = 'creation_date'
    fieldsets = (
        (None, {
            'fields': ('creation_date_display', 'created_by', 'ip', 'referrer', )
        }),
    )

    class Media:
        js = (
            'js/djangocms_forms/admin/jquery-form-export.js',
        )

    def has_add_permission(self, request):
        return False

    def has_export_permission(self, request):
        opts = self.opts
        codename = get_permission_codename('export', opts)
        return request.user.has_perm('%s.%s' % (opts.app_label, codename))

    def creation_date_display(self, obj):
        return obj.creation_date.strftime(settings.DJANGOCMS_FORMS_DATETIME_FORMAT)
    creation_date_display.short_description = _('Sent On')

    def get_queryset(self, request):
        qs = super(FormSubmissionAdmin, self).get_queryset(request)
        return qs.select_related('created_by', 'plugin', )

    def get_urls(self):
        """
        Add the export view to urls.
        """
        urls = super(FormSubmissionAdmin, self).get_urls()
        from django.conf.urls import url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        extra_urls = [
            url(r'^export/$', wrap(self.export_view), name='%s_%s_export' % info),
        ]
        return extra_urls + urls

    @csrf_protect_m
    def changelist_view(self, request, extra_context=None):
        context = extra_context or {}
        context.update({
            'title': self.opts.verbose_name_plural.title(),
            'has_export_permission': self.has_export_permission(request),
        })
        return super(FormSubmissionAdmin, self).changelist_view(
            request, extra_context=context)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        context = extra_context or {}
        obj = self.get_object(request, unquote(object_id))

        if obj:
            context.update({
                'title': force_text(obj.plugin),
            })

        return super(FormSubmissionAdmin, self).change_view(
            request, object_id, form_url=form_url,
            extra_context=context)

    def export_view(self, request, form_url=''):
        """The 'export' admin view for this model."""

        info = self.opts.app_label, self.opts.model_name

        if not self.has_export_permission(request):
            raise PermissionDenied

        form = SubmissionExportForm(data=request.POST if request.method == 'POST' else None)

        if form.is_valid():
            data = form.cleaned_data
            queryset = self.get_queryset(request) \
                .filter(plugin_id=data.get('form')) \
                .select_related('created_by', 'plugin', )

            from_date, to_date = data.get('from_date'), data.get('to_date')
            headers = data.get('headers', [])

            if from_date:
                queryset = queryset.filter(creation_date__gte=from_date)
            if to_date:
                queryset = queryset.filter(creation_date__lt=to_date + datetime.timedelta(days=1))

            if not queryset.exists():
                message = _('No matching %s found for the given criteria. '
                            'Please try again.') % self.opts.verbose_name_plural
                self.message_user(request, message, level=messages.WARNING)
                if request.is_ajax():
                    data = {
                        'reloadBrowser': True,
                        'submissionCount': 0,
                    }
                    return JsonResponse(data)
                return redirect('admin:%s_%s_export' % info)

            latest_submission = queryset[:1].get()
            dataset = Dataset(title=Truncator(latest_submission.plugin.name).chars(31))

            if not headers:
                headers = [field['label'].strip() for field in latest_submission.form_data]
                for submission in queryset:
                    for field in submission.form_data:
                        label = field['label'].strip()
                        if label not in headers:
                            headers.append(label)

                if request.is_ajax():
                    data = {
                        'reloadBrowser': False,
                        'submissionCount': queryset.count(),
                        'availableHeaders': headers,
                    }
                    return JsonResponse(data)

            headers.extend(['Submitted By', 'Submitted on', 'Sender IP', 'Referrer URL'])
            dataset.headers = headers

            def humanize(field):
                value = field['value']
                field_type = field['type']

                if value in (None, '', [], (), {}):
                    return None

                if field_type == 'checkbox':
                    value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
                if field_type == 'checkbox_multiple':
                    value = ', '.join(list(value))
                return value

            for submission in queryset:
                row = [None] * len(headers)
                for field in submission.form_data:
                    label = field['label'].strip()
                    if label in headers:
                        row[headers.index(label)] = humanize(field)

                    row[-4] = force_text(submission.created_by or _('Unknown'))
                    row[-3] = submission.creation_date.strftime(
                        settings.DJANGOCMS_FORMS_DATETIME_FORMAT)
                    row[-2] = submission.ip
                    row[-1] = submission.referrer
                dataset.append(row)

            mimetype = {
                'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'csv': 'text/csv',
                'html': 'text/html',
                'yaml': 'text/yaml',
                'json': 'application/json',
            }

            file_type = data.get('file_type', 'xlsx')
            filename = settings.DJANGOCMS_FORMS_EXPORT_FILENAME.format(
                form_name=slugify(latest_submission.plugin.name))
            filename = timezone.now().strftime(filename)
            filename = '%s.%s' % (filename, file_type)

            response = HttpResponse(
                getattr(dataset, file_type), {
                    'content_type': mimetype.get(file_type, 'application/octet-stream')
                })

            response['Content-Disposition'] = 'attachment; filename=%s' % filename
            return response

        # Wrap in all admin layout
        fieldsets = ((None, {'fields': form.fields.keys()}),)
        adminform = AdminForm(form, fieldsets, {}, model_admin=self)
        media = self.media + adminform.media

        context = {
            'title': _('Export %s') % force_text(self.opts.verbose_name_plural),
            'adminform': adminform,
            'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),
            'media': mark_safe(media),
            'errors': AdminErrorList(form, ()),
            'app_label': self.opts.app_label,
        }
        return self.render_export_form(request, context, form_url)

    def render_export_form(self, request, context, form_url=''):
        """
        Render the from submission export form.
        """
        context.update({
            'has_change_permission': self.has_change_permission(request),
            'form_url': mark_safe(form_url),
            'opts': self.opts,
            'add': True,
            'save_on_top': self.save_on_top,
        })

        return TemplateResponse(request, self.export_form_template, context)

admin.site.register(FormSubmission, FormSubmissionAdmin)


text:
<!doctype html>

    <title>Cierge - passwordless authentication done right.</title>
    <link rel="shortcut icon" type="image/png" href="favicon.png"/>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <link rel="stylesheet" href="master.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700|Assistant" rel="stylesheet">

                Try it out
                Get it on GitHub

                Star

            Cierge is an open source authentication server (OIDC) that handles
            user signup, login, profiles, management, and more. Instead
            of storing passwords, Cierge uses magic links/codes and external logins
            to authenticate your users.

No passwords

                                    Instead of passwords, users login using a magic link/code or
                                    using external social logins - no more passwords to remember
                                    or store and all emails are verified by default

User management

                                    Users can edit their profiles and add or remove emails or external logins
                                    while an admin manages it all from the admin panel

External logins

                                    Instead of logging in using email, users can use
                                    social logins such as Google, Facebook, Github, etc.
                                    Users can also associate multiple logins for one account

No leakage

                                    Cierge does not reveal anything (literally) about users until they've
                                    been authenticated - eg. it's impossible for an attacker to even know
                                    if an email is in use (unlike traditional password systems)

Event logs

                                    To aid in breach detection, detailed event logs
                                    are kept easily accessible to users and admins
                                    for each account

OpenID Connect

                                Cierge exposes an OIDC (based on OAuth 2.0, implicit flow) endpoint
                                so you can easily integrate it with your existing APIs

Spin it up in a Docker container and ta-da, you're done with auth.

Get Cierge, it's free

                    Try it out
                    Get it on GitHub

                    Star

           Created by Biarity in Brisbane.
           Contact: admin@biarity.me

           Icons by Freepik


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true">

    <SlidingDrawer
        android:layout_width="fill_parent"
        android:layout_height="85dp"
        android:content="@+id/content"
        android:handle="@+id/buttonHandle"
        android:id="@+id/slidingDrawer"
        >

        <RelativeLayout
            android:id="@+id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:background="@android:color/black">

            <Button
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/stop"
                android:id="@+id/buttonHandleLeft"
                android:maxWidth="90dp"
                android:maxHeight="60dp"
                android:textSize="10sp"
                android:minHeight="60dp"
                android:minWidth="90dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentStart="true"
                android:textColor="@android:color/black" />

            <Button
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/pause"
                android:id="@+id/buttonHandleCenter"
                android:maxWidth="90dp"
                android:maxHeight="60dp"
                android:textSize="10sp"
                android:minHeight="60dp"
                android:minWidth="90dp"
                android:textColor="@android:color/black"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"/>

        </RelativeLayout>

        <Button
            android:id="@+id/buttonHandle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minHeight="5dp"
            android:minWidth="240dp"
            android:background="@android:color/holo_blue_bright"
            android:maxHeight="5dp" />
    </SlidingDrawer>

</FrameLayout>


text:
using System.Collections.Generic;

namespace NewsSite.Core.Database.Tables
{
    public class PostPosition : BaseEntity
    {
        public PostPosition()
        {
            Posts = new HashSet<Post>();
        }

        public string Name { get; set; }

        public virtual ICollection<Post> Posts { get; set; }
    }
}


text:
using Publisher.CommandSpecific.Chocolatey;
using Publisher.Core;
using SysCommand.ConsoleApp;
using System.Collections.Generic;

namespace Publisher.CommandSpecific
{
    public class PublishCommand : Command
    {
        public void Publish()
        {
            var build = App.Commands.Get<BuildCommand>();
            var pack = App.Commands.Get<PackCommand>();
            var version = App.Commands.Get<VersionCommand>();
            var github = App.Commands.Get<GitHubCommand>();
            var pathCommand = App.Commands.Get<PathCommand>();
            var chocolateyCommand = App.Commands.Get<ChocolateyCommand>();
            var fileReplaceCommand = App.Commands.Get<FileReplaceCommand>();
            var gitCommand = App.Commands.Get<GitCommand>();

            Title("SET NEXT VERSION");
            version.Next();

            Title("UPDATE VERSION IN TEXT FILES");
            fileReplaceCommand.Version();

            Title("CHECK GIT STATUS");
            gitCommand.CheckUncommitedFiles();

            Title("BUILD");
            build.Clear();
            build.Build();

            Title("PACK");
            pack.Pack();

            if (Utils.Continue(this, "Do you create a new release in github?"))
            {
                Title("GITHUB - CREATE NEW RELEASE");

                // Check error in connection
                github.TestConnection();

                github.CreateRelease();

                if (Utils.Continue(this, "Do you want to upload the package to github?"))
                {
                    Title("GITHUB - UPLOADING PACKS");
                    github.UploadPackFolder();
                }
            }

            if (Utils.Continue(this, "Do you create a new release in Chocolatey?"))
            {
                Title("CHOCOLATEY - CREATE NEW RELEASE");

                chocolateyCommand.Build();
                chocolateyCommand.Pack();

                if (Utils.Continue(this, "Do you want to upload the package to Chocolatey.org?"))
                {
                    Title("CHOCOLATEY - PUSHING PACK");
                    chocolateyCommand.Push();
                }
            }
        }

        private void Title(string text)
        {
            var count = 80;
            App.Console.Write(new string('-', count));
            App.Console.Write(text);
            App.Console.Write(new string('-', count));
        }
    }
}