text:
from django.contrib import admin
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.views.main import ChangeList, SEARCH_VAR
from django.core.paginator import Paginator
from django.template import Context, Template
from django.test import TestCase
from django.test.client import RequestFactory
from django.contrib.auth.models import User

from models import (Child, Parent, Genre, Band, Musician, Group, Quartet,
    Membership, ChordsMusician, ChordsBand, Invitation)

class ChangeListTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_select_related_preserved(self):
        """
        Regression test for #10348: ChangeList.get_query_set() shouldn't
        overwrite a custom select_related provided by ModelAdmin.queryset().
        """
        m = ChildAdmin(Child, admin.site)
        request = self.factory.get('/child/')
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        self.assertEqual(cl.query_set.query.select_related, {'parent': {'name': {}}})

    def test_result_list_empty_changelist_value(self):
        """
        Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
        for relationship fields
        """
        new_child = Child.objects.create(name='name', parent=None)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        row_html = '

<input type="checkbox" class="action-select" value="%d" name="_selected_action" />	name	(None)

' % (new_child.id, new_child.id)
        self.assertFalse(table_output.find(row_html) == -1,
            'Failed to find expected row element: %s' % table_output)

    def test_result_list_html(self):
        """
        Verifies that inclusion tag result_list generates a table when with
        default ModelAdmin settings.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        row_html = '

<input type="checkbox" class="action-select" value="%d" name="_selected_action" />	name	Parent object

' % (new_child.id, new_child.id)
        self.assertFalse(table_output.find(row_html) == -1,
            'Failed to find expected row element: %s' % table_output)

    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, admin.site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = '
<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" />
' % new_child.id
        self.assertFalse(table_output.find(hiddenfields_div) == -1,
            'Failed to find hidden fields in: %s' % table_output)
        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />'
        self.assertFalse('%s	' % editable_name_field == -1,
            'Failed to find "name" list_editable field in: %s' % table_output)

    def test_result_list_editable(self):
        """
        Regression test for #14312: list_editable with pagination
        """

        new_parent = Parent.objects.create(name='parent')
        for i in range(200):
            new_child = Child.objects.create(name='name %s' % i, parent=new_parent)
        request = self.factory.get('/child/', data={'p': -1})  # Anything outside range
        m = ChildAdmin(Child, admin.site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        self.assertRaises(IncorrectLookupParameters, lambda: \
            ChangeList(request, Child, m.list_display, m.list_display_links,
                    m.list_filter, m.date_hierarchy, m.search_fields,
                    m.list_select_related, m.list_per_page, m.list_editable, m))

    def test_custom_paginator(self):
        new_parent = Parent.objects.create(name='parent')
        for i in range(200):
            new_child = Child.objects.create(name='name %s' % i, parent=new_parent)

        request = self.factory.get('/child/')
        m = ChildAdmin(Child, admin.site)
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        m.paginator = CustomPaginator

        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)

        cl.get_results(request)
        self.assertIsInstance(cl.paginator, CustomPaginator)

    def test_distinct_for_m2m_in_list_filter(self):
        """
        Regression test for #13902: When using a ManyToMany in list_filter,
        results shouldn't apper more than once. Basic ManyToMany.
        """
        blues = Genre.objects.create(name='Blues')
        band = Band.objects.create(name='B.B. King Review', nr_of_members=11)

        band.genres.add(blues)
        band.genres.add(blues)

        m = BandAdmin(Band, admin.site)
        request = self.factory.get('/band/', data={'genres': blues.pk})

        cl = ChangeList(request, Band, m.list_display,
                m.list_display_links, m.list_filter, m.date_hierarchy,
                m.search_fields, m.list_select_related, m.list_per_page,
                m.list_editable, m)

        cl.get_results(request)

        # There's only one Group instance
        self.assertEqual(cl.result_count, 1)

    def test_distinct_for_through_m2m_in_list_filter(self):
        """
        Regression test for #13902: When using a ManyToMany in list_filter,
        results shouldn't apper more than once. With an intermediate model.
        """
        lead = Musician.objects.create(name='Vox')
        band = Group.objects.create(name='The Hype')
        Membership.objects.create(group=band, music=lead, role='lead voice')
        Membership.objects.create(group=band, music=lead, role='bass player')

        m = GroupAdmin(Group, admin.site)
        request = self.factory.get('/group/', data={'members': lead.pk})

        cl = ChangeList(request, Group, m.list_display,
                m.list_display_links, m.list_filter, m.date_hierarchy,
                m.search_fields, m.list_select_related, m.list_per_page,
                m.list_editable, m)

        cl.get_results(request)

        # There's only one Group instance
        self.assertEqual(cl.result_count, 1)

    def test_distinct_for_inherited_m2m_in_list_filter(self):
        """
        Regression test for #13902: When using a ManyToMany in list_filter,
        results shouldn't apper more than once. Model managed in the
        admin inherits from the one that defins the relationship.
        """
        lead = Musician.objects.create(name='John')
        four = Quartet.objects.create(name='The Beatles')
        Membership.objects.create(group=four, music=lead, role='lead voice')
        Membership.objects.create(group=four, music=lead, role='guitar player')

        m = QuartetAdmin(Quartet, admin.site)
        request = self.factory.get('/quartet/', data={'members': lead.pk})

        cl = ChangeList(request, Quartet, m.list_display,
                m.list_display_links, m.list_filter, m.date_hierarchy,
                m.search_fields, m.list_select_related, m.list_per_page,
                m.list_editable, m)

        cl.get_results(request)

        # There's only one Quartet instance
        self.assertEqual(cl.result_count, 1)

    def test_distinct_for_m2m_to_inherited_in_list_filter(self):
        """
        Regression test for #13902: When using a ManyToMany in list_filter,
        results shouldn't apper more than once. Target of the relationship
        inherits from another.
        """
        lead = ChordsMusician.objects.create(name='Player A')
        three = ChordsBand.objects.create(name='The Chords Trio')
        Invitation.objects.create(band=three, player=lead, instrument='guitar')
        Invitation.objects.create(band=three, player=lead, instrument='bass')

        m = ChordsBandAdmin(ChordsBand, admin.site)
        request = self.factory.get('/chordsband/', data={'members': lead.pk})

        cl = ChangeList(request, ChordsBand, m.list_display,
                m.list_display_links, m.list_filter, m.date_hierarchy,
                m.search_fields, m.list_select_related, m.list_per_page,
                m.list_editable, m)

        cl.get_results(request)

        # There's only one ChordsBand instance
        self.assertEqual(cl.result_count, 1)

    def test_distinct_for_non_unique_related_object_in_list_filter(self):
        """
        Regressions tests for #15819: If a field listed in list_filters
        is a non-unique related object, distinct() must be called.
        """
        parent = Parent.objects.create(name='Mary')
        # Two children with the same name
        Child.objects.create(parent=parent, name='Daniel')
        Child.objects.create(parent=parent, name='Daniel')

        m = ParentAdmin(Parent, admin.site)
        request = self.factory.get('/parent/', data={'child__name': 'Daniel'})

        cl = ChangeList(request, Parent, m.list_display, m.list_display_links,
                        m.list_filter, m.date_hierarchy, m.search_fields,
                        m.list_select_related, m.list_per_page,
                        m.list_editable, m)

        # Make sure distinct() was called
        self.assertEqual(cl.query_set.count(), 1)

    def test_distinct_for_non_unique_related_object_in_search_fields(self):
        """
        Regressions tests for #15819: If a field listed in search_fields
        is a non-unique related object, distinct() must be called.
        """
        parent = Parent.objects.create(name='Mary')
        Child.objects.create(parent=parent, name='Danielle')
        Child.objects.create(parent=parent, name='Daniel')

        m = ParentAdmin(Parent, admin.site)
        request = self.factory.get('/parent/', data={SEARCH_VAR: 'daniel'})

        cl = ChangeList(request, Parent, m.list_display, m.list_display_links,
                        m.list_filter, m.date_hierarchy, m.search_fields,
                        m.list_select_related, m.list_per_page,
                        m.list_editable, m)

        # Make sure distinct() was called
        self.assertEqual(cl.query_set.count(), 1)

    def test_pagination(self):
        """
        Regression tests for #12893: Pagination in admins changelist doesn't
        use queryset set by modeladmin.
        """
        parent = Parent.objects.create(name='anything')
        for i in range(30):
            Child.objects.create(name='name %s' % i, parent=parent)
            Child.objects.create(name='filtered %s' % i, parent=parent)

        request = self.factory.get('/child/')

        # Test default queryset
        m = ChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        self.assertEqual(cl.query_set.count(), 60)
        self.assertEqual(cl.paginator.count, 60)
        self.assertEqual(cl.paginator.page_range, [1, 2, 3, 4, 5, 6])

        # Test custom queryset
        m = FilteredChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        self.assertEqual(cl.query_set.count(), 30)
        self.assertEqual(cl.paginator.count, 30)
        self.assertEqual(cl.paginator.page_range, [1, 2, 3])

    def test_dynamic_list_display(self):
        """
        Regression tests for #14206: dynamic list_display support.
        """
        parent = Parent.objects.create(name='parent')
        for i in range(10):
            Child.objects.create(name='child %s' % i, parent=parent)

        user_noparents = User.objects.create(
            username='noparents',
            is_superuser=True)
        user_parents = User.objects.create(
            username='parents',
            is_superuser=True)

        def _mocked_authenticated_request(user):
            request = self.factory.get('/child/')
            request.user = user
            return request

        # Test with user 'noparents'
        m = DynamicListDisplayChildAdmin(Child, admin.site)
        request = _mocked_authenticated_request(user_noparents)
        response = m.changelist_view(request)
        # XXX - Calling render here to avoid ContentNotRenderedError to be
        # raised. Ticket #15826 should fix this but it's not yet integrated.
        response.render()
        self.assertNotContains(response, 'Parent object')

        # Test with user 'parents'
        m = DynamicListDisplayChildAdmin(Child, admin.site)
        request = _mocked_authenticated_request(user_parents)
        response = m.changelist_view(request)
        # XXX - #15826
        response.render()
        self.assertContains(response, 'Parent object')

        # Test default implementation
        m = ChildAdmin(Child, admin.site)
        request = _mocked_authenticated_request(user_noparents)
        response = m.changelist_view(request)
        # XXX - #15826
        response.render()
        self.assertContains(response, 'Parent object')

class ParentAdmin(admin.ModelAdmin):
    list_filter = ['child__name']
    search_fields = ['child__name']

class ChildAdmin(admin.ModelAdmin):
    list_display = ['name', 'parent']
    list_per_page = 10

    def queryset(self, request):
        return super(ChildAdmin, self).queryset(request).select_related("parent__name")

class FilteredChildAdmin(admin.ModelAdmin):
    list_display = ['name', 'parent']
    list_per_page = 10

    def queryset(self, request):
        return super(FilteredChildAdmin, self).queryset(request).filter(
            name__contains='filtered')

class CustomPaginator(Paginator):
    def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True):
        super(CustomPaginator, self).__init__(queryset, 5, orphans=2,
            allow_empty_first_page=allow_empty_first_page)

class BandAdmin(admin.ModelAdmin):
    list_filter = ['genres']

class GroupAdmin(admin.ModelAdmin):
    list_filter = ['members']

class QuartetAdmin(admin.ModelAdmin):
    list_filter = ['members']

class ChordsBandAdmin(admin.ModelAdmin):
    list_filter = ['members']

class DynamicListDisplayChildAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent')

    def get_list_display(self, request):
        my_list_display = list(self.list_display)
        if request.user.username == 'noparents':
            my_list_display.remove('parent')

        return my_list_display


text:
layout: page-fullwidth
permalink: /about/
title: About Us
---

    Some of the content in the website comes from a capstone course on computer science methodologies taught by
    Michael Heroux since 1998. This material draws upon and develops the best way to capture students' assignments.

    Contact

    Any concern or contribution, please contact us at dhdo@csbsju.edu

    Authors and Contributors

    This site is developed and maintained by Michael Heroux @maherou
    with assistance from Duong Do @duongdo27

    Its content is used as part of a Computer Science capstone course in research methodologies at the
    College of St. Benedict and St. John's University in rural Collegeville, Minnesota.

redpajama_set_name: RedPajamaGithub


text:
using System.Reflection;

[assembly: AssemblyTitle("Projac.Redis.Tests")]
[assembly: AssemblyDescription("")]


text:
package org.camunda.bpm.engine.impl.cmd;

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

import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.impl.cfg.CommandChecker;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.migration.MigrationInstructionGenerator;
import org.camunda.bpm.engine.impl.migration.MigrationLogger;
import org.camunda.bpm.engine.impl.migration.MigrationPlanBuilderImpl;
import org.camunda.bpm.engine.impl.migration.MigrationPlanImpl;
import org.camunda.bpm.engine.impl.migration.validation.instruction.MigrationInstructionValidationReportImpl;
import org.camunda.bpm.engine.impl.migration.validation.instruction.MigrationInstructionValidator;
import org.camunda.bpm.engine.impl.migration.validation.instruction.MigrationPlanValidationReportImpl;
import org.camunda.bpm.engine.impl.migration.validation.instruction.ValidatingMigrationInstruction;
import org.camunda.bpm.engine.impl.migration.validation.instruction.ValidatingMigrationInstructionImpl;
import org.camunda.bpm.engine.impl.migration.validation.instruction.ValidatingMigrationInstructions;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.camunda.bpm.engine.impl.util.EngineUtilLogger;
import org.camunda.bpm.engine.impl.util.EnsureUtil;
import org.camunda.bpm.engine.migration.MigrationInstruction;
import org.camunda.bpm.engine.migration.MigrationPlan;

/**
 * @author Thorben Lindhauer
 *
 */
public class CreateMigrationPlanCmd implements Command<MigrationPlan> {

  public static final MigrationLogger LOG = EngineUtilLogger.MIGRATION_LOGGER;

  protected MigrationPlanBuilderImpl migrationBuilder;

  public CreateMigrationPlanCmd(MigrationPlanBuilderImpl migrationPlanBuilderImpl) {
    this.migrationBuilder = migrationPlanBuilderImpl;
  }

  @Override
  public MigrationPlan execute(CommandContext commandContext) {
    ProcessDefinitionEntity sourceProcessDefinition = getProcessDefinition(commandContext, migrationBuilder.getSourceProcessDefinitionId(), "Source");
    ProcessDefinitionEntity targetProcessDefinition = getProcessDefinition(commandContext, migrationBuilder.getTargetProcessDefinitionId(), "Target");

    checkAuthorization(commandContext, sourceProcessDefinition, targetProcessDefinition);

    MigrationPlanImpl migrationPlan = new MigrationPlanImpl(sourceProcessDefinition.getId(), targetProcessDefinition.getId());
    List<MigrationInstruction> instructions = new ArrayList<MigrationInstruction>();

    if (migrationBuilder.isMapEqualActivities()) {
      instructions.addAll(generateInstructions(commandContext, sourceProcessDefinition, targetProcessDefinition, migrationBuilder.isUpdateEventTriggersForGeneratedInstructions()));
    }

    instructions.addAll(migrationBuilder.getExplicitMigrationInstructions());
    migrationPlan.setInstructions(instructions);

    validateMigrationPlan(commandContext, migrationPlan, sourceProcessDefinition, targetProcessDefinition);

    return migrationPlan;
  }

  protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String id, String type) {
    EnsureUtil.ensureNotNull(BadUserRequestException.class, type + " process definition id", id);

    try {
      return commandContext.getProcessEngineConfiguration()
        .getDeploymentCache().findDeployedProcessDefinitionById(id);
    }
    catch (NullValueException e) {
      throw LOG.processDefinitionDoesNotExist(id, type);
    }
  }

  protected void checkAuthorization(CommandContext commandContext, ProcessDefinitionEntity sourceProcessDefinition, ProcessDefinitionEntity targetProcessDefinition) {

    for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
      checker.checkCreateMigrationPlan(sourceProcessDefinition, targetProcessDefinition);
    }
  }

  protected List<MigrationInstruction> generateInstructions(CommandContext commandContext,
      ProcessDefinitionImpl sourceProcessDefinition,
      ProcessDefinitionImpl targetProcessDefinition,
      boolean updateEventTriggers) {
    ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration();

    // generate instructions
    MigrationInstructionGenerator migrationInstructionGenerator = processEngineConfiguration.getMigrationInstructionGenerator();
    ValidatingMigrationInstructions generatedInstructions = migrationInstructionGenerator.generate(sourceProcessDefinition, targetProcessDefinition, updateEventTriggers);

    // filter only valid instructions
    generatedInstructions.filterWith(processEngineConfiguration.getMigrationInstructionValidators());

    return generatedInstructions.asMigrationInstructions();
  }

  protected void validateMigrationPlan(CommandContext commandContext, MigrationPlanImpl migrationPlan, ProcessDefinitionImpl sourceProcessDefinition, ProcessDefinitionImpl targetProcessDefinition) {
    List<MigrationInstructionValidator> migrationInstructionValidators = commandContext.getProcessEngineConfiguration().getMigrationInstructionValidators();

    MigrationPlanValidationReportImpl planReport = new MigrationPlanValidationReportImpl(migrationPlan);
    ValidatingMigrationInstructions validatingMigrationInstructions = wrapMigrationInstructions(migrationPlan, sourceProcessDefinition, targetProcessDefinition, planReport);

    for (ValidatingMigrationInstruction validatingMigrationInstruction : validatingMigrationInstructions.getInstructions()) {
      MigrationInstructionValidationReportImpl instructionReport = validateInstruction(validatingMigrationInstruction, validatingMigrationInstructions, migrationInstructionValidators);
      if (instructionReport.hasFailures()) {
        planReport.addInstructionReport(instructionReport);
      }
    }

    if (planReport.hasInstructionReports()) {
      throw LOG.failingMigrationPlanValidation(planReport);
    }

  }

  protected MigrationInstructionValidationReportImpl validateInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, List<MigrationInstructionValidator> migrationInstructionValidators) {
    MigrationInstructionValidationReportImpl validationReport = new MigrationInstructionValidationReportImpl(instruction.toMigrationInstruction());
    for (MigrationInstructionValidator migrationInstructionValidator : migrationInstructionValidators) {
      migrationInstructionValidator.validate(instruction, instructions, validationReport);
    }
    return validationReport;
  }

  protected ValidatingMigrationInstructions wrapMigrationInstructions(MigrationPlan migrationPlan, ProcessDefinitionImpl sourceProcessDefinition, ProcessDefinitionImpl targetProcessDefinition, MigrationPlanValidationReportImpl planReport) {
    ValidatingMigrationInstructions validatingMigrationInstructions = new ValidatingMigrationInstructions();
    for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) {
      MigrationInstructionValidationReportImpl instructionReport = new MigrationInstructionValidationReportImpl(migrationInstruction);

      String sourceActivityId = migrationInstruction.getSourceActivityId();
      String targetActivityId = migrationInstruction.getTargetActivityId();
      if (sourceActivityId != null && targetActivityId != null) {
        ActivityImpl sourceActivity = sourceProcessDefinition.findActivity(sourceActivityId);
        ActivityImpl targetActivity = targetProcessDefinition.findActivity(migrationInstruction.getTargetActivityId());

        if (sourceActivity != null && targetActivity != null) {
          validatingMigrationInstructions.addInstruction(new ValidatingMigrationInstructionImpl(sourceActivity, targetActivity, migrationInstruction.isUpdateEventTrigger()));
        }
        else {
          if (sourceActivity == null) {
            instructionReport.addFailure("Source activity '" + sourceActivityId + "' does not exist");
          }
          if (targetActivity == null) {
            instructionReport.addFailure("Target activity '" + targetActivityId + "' does not exist");
          }
        }
      }
      else {
        if (sourceActivityId == null) {
          instructionReport.addFailure("Source activity id is null");
        }
        if (targetActivityId == null) {
          instructionReport.addFailure("Target activity id is null");
        }
      }

      if (instructionReport.hasFailures()) {
        planReport.addInstructionReport(instructionReport);
      }
    }
    return validatingMigrationInstructions;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

      <!-- classpath*带上*,不然报找不到文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--由于没有默认applicationContext.xml文件,需要指定相应文件 -->
        <param-value>classpath*:spring/spring.xml</param-value>
    </context-param>

    <!-- Spring的log4j监听器 -->
    <listener>
      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- 防止spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!--设置编码-->
	<filter>
		<display-name>CharacterEncodingFilter</display-name>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <!--配置  cxf 的核心的过滤器
	<servlet>
     	<servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
         <servlet-name>CXFServlet</servlet-name>
         <url-pattern>/webservice/*</url-pattern>
    </servlet-mapping>
    -->

	<!--配置  springmvc 的核心的过滤器-->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:spring/spring-mvc.xml</param-value>
		</init-param>
		<!-- <load-on-startup>1</load-on-startup> -->
	</servlet>

	<!--servlet的映射,如果有多个需要注意加载顺序 -->
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<!-- url-pattern配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问,
		需在spring-mvc.xml中配置。如配为*.do,则不影响静态文件的访问,但正文乱码不好解决  -->
		<url-pattern>/</url-pattern>
		<!-- <url-pattern>*.do</url-pattern> -->
	</servlet-mapping>

<!-- 配置session超时时间,单位分钟 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

	<error-page>
		<error-code>404</error-code>
		<location>/error/404.jsp</location>
		<error-code>500</error-code>
		<location>/error/404.jsp</location>
	</error-page>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


text:
package lombok.extern.jackson;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import lombok.Builder;
import lombok.experimental.SuperBuilder;

/**
 * The {@code @Jacksonized} annotation is an add-on annotation for
 * {@code @}{@link Builder} and {@code @}{@link SuperBuilder}. It automatically
 * configures the generated builder class to be used by Jackson's
 * deserialization. It only has an effect if present at a context where there is
 * also a {@code @Builder} or a {@code @SuperBuilder}; a warning is emitted
 * otherwise.
 *

 * In particular, the annotation does the following:
 *

 *
Configure Jackson to use the builder for deserialization using
 * {@code @JsonDeserialize(builder=Foobar.FoobarBuilder[Impl].class)}
 * on the class (where Foobar is the name of the annotated class).

 *
Copy Jackson-related configuration annotations (like
 * {@code @JsonIgnoreProperties}) from the class to the builder class. This is
 * necessary so that Jackson recognizes them when using the builder.

 *
Insert {@code @JsonPOJOBuilder(withPrefix="")} on the generated builder
 * class to override Jackson's default prefix "with". If you configured a
 * different prefix in lombok using {@code setterPrefix}, this value is used. If
 * you changed the name of the {@code build()} method using using
 * {@code buildMethodName}, this is also made known to Jackson.

 *
For {@code @SuperBuilder}, make the builder implementation class
 * package-private.

 *

 * This annotation does not change the behavior of the generated builder.
 * A {@code @Jacksonized} {@code @SuperBuilder} remains fully compatible to
 * regular {@code @SuperBuilder}s.
 */
@Target({TYPE, METHOD, CONSTRUCTOR})
@Retention(SOURCE)
public @interface Jacksonized {
}


text:
	<link rel="stylesheet" href="css/questions.css" />

Questions?


text:
<meta_metadata_repository name="sequencedClippableDocument" package="ecologylab.bigsemantics.metadata.builtins"
  default_user_agent_name="firefox_3_5">

  <meta_metadata name="sequenced_clippable_document" extends="clippable_document" built_in="true">
    <scalar name="duration" scalar_type="int" comment="duration of media in milliseconds." />
    <scalar name="file_format" scalar_type="String" hide="true" />
  </meta_metadata>
</meta_metadata_repository>


text:
#ifndef ATEMA_CORE_THREADPOOL_HPP
#define ATEMA_CORE_THREADPOOL_HPP

#include <Atema/Core/Config.hpp>
#include <Atema/Core/NonCopyable.hpp>
#include <Atema/Core/Pointer.hpp>

#include <vector>
#include <thread>
#include <queue>
#include <functional>
#include <mutex>

namespace at
{
	class ATEMA_CORE_API Task
	{
	public:
		Task() = delete;
		Task(const std::function<void(size_t)>& function);
		virtual ~Task();

		void start(size_t threadIndex);

		void wait() noexcept;

	private:
		std::function<void(size_t)> m_function;
		bool m_finished;
		std::mutex m_mutex;
		std::condition_variable m_condition;
	};

	class ATEMA_CORE_API TaskManager : public NonCopyable
	{
	public:
		virtual ~TaskManager();

		static TaskManager& instance();

		size_t getSize() const noexcept;

		Ptr<Task> createTask(const std::function<void()>& function);
		Ptr<Task> createTask(const std::function<void(size_t)>& function);

	private:
		TaskManager();
		void initialize(size_t size);

		std::atomic_bool m_exit;
		std::vector<Ptr<std::thread>> m_threads;
		std::mutex m_taskMutex;
		std::queue<Ptr<Task>> m_tasks;
		std::condition_variable m_condition;
	};
}

#endif


text:
//// [commentsVarDecl.ts]
/** Variable comments*/
var myVariable = 10; // This trailing Comment1

/** This is another variable comment*/
var anotherVariable = 30;

// shouldn't appear
var aVar = "";

/** this is multiline comment
  * All these variables are of number type */
var anotherAnotherVariable = 70; /* these are multiple trailing comments */ /* multiple trailing comments */

/** Triple slash multiline comment*/
/** another line in the comment*/
/** comment line 2*/
var x = 70; /* multiline trailing comment
this is multiline trailing comment */
/** Triple slash comment on the assignement shouldnt be in .d.ts file*/
x = myVariable;

/** triple slash comment1*/
/** jsdocstyle comment - only this comment should be in .d.ts file*/
var n = 30;

/** var deckaration with comment on type as well*/
var y = /** value comment */ 20;

/// var deckaration with comment on type as well
var yy =
    /// value comment
    20;

/** comment2 */
var z = /** lambda comment */ (x: number, y: number) => x + y;

var z2: /** type comment*/ (x: number) => string;

var x2 = z2;

var n4: (x: number) => string;
n4 = z2;

//// [commentsVarDecl.js]
/** Variable comments*/
var myVariable = 10; // This trailing Comment1
/** This is another variable comment*/
var anotherVariable = 30;
// shouldn't appear
var aVar = "";
/** this is multiline comment
  * All these variables are of number type */
var anotherAnotherVariable = 70; /* these are multiple trailing comments */ /* multiple trailing comments */
/** Triple slash multiline comment*/
/** another line in the comment*/
/** comment line 2*/
var x = 70; /* multiline trailing comment
this is multiline trailing comment */
/** Triple slash comment on the assignement shouldnt be in .d.ts file*/
x = myVariable;
/** triple slash comment1*/
/** jsdocstyle comment - only this comment should be in .d.ts file*/
var n = 30;
/** var deckaration with comment on type as well*/
var y = /** value comment */ 20;
/// var deckaration with comment on type as well
var yy =
/// value comment
20;
/** comment2 */
var z = /** lambda comment */ function (x, y) { return x + y; };
var z2;
var x2 = z2;
var n4;
n4 = z2;

//// [commentsVarDecl.d.ts]
/** Variable comments*/
declare var myVariable: number;
/** This is another variable comment*/
declare var anotherVariable: number;
declare var aVar: string;
/** this is multiline comment
  * All these variables are of number type */
declare var anotherAnotherVariable: number;
/** Triple slash multiline comment*/
/** another line in the comment*/
/** comment line 2*/
declare var x: number;
/** triple slash comment1*/
/** jsdocstyle comment - only this comment should be in .d.ts file*/
declare var n: number;
/** var deckaration with comment on type as well*/
declare var y: number;
declare var yy: number;
/** comment2 */
declare var z: (x: number, y: number) => number;
declare var z2: (x: number) => string;
declare var x2: (x: number) => string;
declare var n4: (x: number) => string;


text:
// Copyright 2016 Chris Conway (Koderz). All Rights Reserved.

#pragma once

#include "Engine.h"
#include "Components/MeshComponent.h"
#include "RuntimeMeshProfiling.h"
#include "RuntimeMeshVersion.h"
#include "Runtime/Launch/Resources/Version.h"
#include "RuntimeMeshCore.generated.h"

class FRuntimeMeshVertexFactory;

/* Helper for determining if a struct has a member of type "FVector" with the name "Position" */
template<typename T> struct FVertexHasPositionComponent {
	struct Fallback { FVector Position; };
	struct Derived : T, Fallback { };

	template<typename C, C> struct ChT;

	template<typename C> static char(&f(ChT<FVector Fallback::*, &C::Position>*))[1];
	template<typename C> static char(&f(...))[2];

	static bool const Value = sizeof(f<Derived>(0)) == 2;
};

#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 12
/** Structure definition of a vertex */
using RuntimeMeshVertexStructure = FLocalVertexFactory::FDataType;
#else
/** Structure definition of a vertex */
using RuntimeMeshVertexStructure = FLocalVertexFactory::DataType;
#endif

#define RUNTIMEMESH_VERTEXCOMPONENT(VertexBuffer, VertexType, Member, MemberType) \
	STRUCTMEMBER_VERTEXSTREAMCOMPONENT(&VertexBuffer, VertexType, Member, MemberType)

/* Update frequency for a section. Used to optimize for update or render speed*/
UENUM(BlueprintType)
enum class EUpdateFrequency
{
	/* Tries to skip recreating the scene proxy if possible. */
	Average UMETA(DisplayName = "Average"),
	/* Tries to skip recreating the scene proxy if possible and optimizes the buffers for frequent updates. */
	Frequent UMETA(DisplayName = "Frequent"),
	/* If the component is static it will try to use the static rendering path (this will force a recreate of the scene proxy) */
	Infrequent UMETA(DisplayName = "Infrequent")
};

/* Update frequency for a section. Used to optimize for update or render speed*/
enum class ESectionUpdateFlags
{
	None = 0x0,

	/**
		This will use move-assignment when copying the supplied vertices/triangles into the section.
		This is faster as it doesn't require copying the data.

		CAUTION: This means that your copy of the arrays will be cleared!
	*/
	MoveArrays = 0x1,

	//CalculateNormalTangent = 0x2,

};
ENUM_CLASS_FLAGS(ESectionUpdateFlags)

/**
*	Struct used to specify a tangent vector for a vertex
*	The Y tangent is computed from the cross product of the vertex normal (Tangent Z) and the TangentX member.
*/
USTRUCT(BlueprintType)
struct FRuntimeMeshTangent
{
	GENERATED_USTRUCT_BODY()

	/** Direction of X tangent for this vertex */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Tangent)
	FVector TangentX;

	/** Bool that indicates whether we should flip the Y tangent when we compute it using cross product */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Tangent)
	bool bFlipTangentY;

	FRuntimeMeshTangent()
		: TangentX(1.f, 0.f, 0.f)
		, bFlipTangentY(false)
	{}

	FRuntimeMeshTangent(float X, float Y, float Z)
		: TangentX(X, Y, Z)
		, bFlipTangentY(false)
	{}

	FRuntimeMeshTangent(FVector InTangentX, bool bInFlipTangentY)
		: TangentX(InTangentX)
		, bFlipTangentY(bInFlipTangentY)
	{}

	void AdjustNormal(FPackedNormal& Normal) const
	{
		Normal.Vector.W = bFlipTangentY ? 0 : 255;
	}
};

/* The different buffers within the Runtime Mesh Component */
enum class ERuntimeMeshBuffer
{
	None = 0x0,
	Vertices = 0x1,
	Triangles = 0x2,
	Positions = 0x4
};
ENUM_CLASS_FLAGS(ERuntimeMeshBuffer)

USTRUCT()
struct FRuntimeMeshCollisionSection
{
	GENERATED_BODY()

	UPROPERTY()
	TArray<FVector> VertexBuffer;

	UPROPERTY()
	TArray<int32> IndexBuffer;

	void Reset()
	{
		VertexBuffer.Empty();
		IndexBuffer.Empty();
	}

	friend FArchive& operator <<(FArchive& Ar, FRuntimeMeshCollisionSection& Section)
	{
		Ar << Section.VertexBuffer;
		Ar << Section.IndexBuffer;
		return Ar;
	}
};

USTRUCT()
struct FRuntimeConvexCollisionSection
{
	GENERATED_BODY()

	UPROPERTY()
	TArray<FVector> VertexBuffer;

	UPROPERTY()
	FBox BoundingBox;

	void Reset()
	{
		VertexBuffer.Empty();
		BoundingBox.Init();
	}

	friend FArchive& operator <<(FArchive& Ar, FRuntimeConvexCollisionSection& Section)
	{
		Ar << Section.VertexBuffer;
		Ar << Section.BoundingBox;
		return Ar;
	}
};

struct RUNTIMEMESHCOMPONENT_API FRuntimeMeshVertexTypeInfo
{
	FString TypeName;
	FGuid TypeGuid;

	FRuntimeMeshVertexTypeInfo(FString Name, FGuid Guid) : TypeName(Name), TypeGuid(Guid) { }

	bool Equals(const FRuntimeMeshVertexTypeInfo* Other) const
	{
		if (TypeGuid != Other->TypeGuid)
		{
			return false;
		}

		return EqualsAdvanced(Other);
	}

	template<typename Type>
	void EnsureEquals() const
	{
		if (!Equals(&Type::TypeInfo))
		{
			ThrowMismatchException(Type::TypeInfo.TypeName);
		}
	}

protected:

	void ThrowMismatchException(const FString& OtherName) const
	{
		UE_LOG(RuntimeMeshLog, Fatal, TEXT("Vertex Type Mismatch: %s  and  %s"), *TypeName, *OtherName);
	}

	/*
	*	This is called only if the Guids match. This is meant to due further
	*	checking like in the case of the generic vertex, how it's configured.
	*/
	virtual bool EqualsAdvanced(const FRuntimeMeshVertexTypeInfo* Other) const { return true; }
};

#define DECLARE_RUNTIMEMESH_VERTEXTYPEINFO_SIMPLE(TypeName, Guid) \
	struct FRuntimeMeshVertexTypeInfo_##TypeName : public FRuntimeMeshVertexTypeInfo \
	{ \
		FRuntimeMeshVertexTypeInfo_##TypeName() : FRuntimeMeshVertexTypeInfo(TEXT(#TypeName), Guid) { } \
	}; \
	static const FRuntimeMeshVertexTypeInfo_##TypeName TypeInfo;

#define DEFINE_RUNTIMEMESH_VERTEXTYPEINFO(TypeName) \
	const  TypeName::FRuntimeMeshVertexTypeInfo_##TypeName TypeName::TypeInfo = TypeName::FRuntimeMeshVertexTypeInfo_##TypeName();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SurfaceMachineSystems.QcController.MotorCommands.MessageEntry
{
    public class POL : SurfaceMachineSystems.QcController.QcMessageEntry
    {
        public POL(QcMessage? Datagram = null)
            : base(Datagram)
        {
            TxMessage = new QcMessage()
            {
                Command = QcCommand.POL,
                Type = PacketType.Command,
                MotorAddress = MotorAddress,
                Psw = new List<QcPsw>()
            };
        }

        public override QcMessage EmitTxMessage()
        {
            return base.EmitTxMessage();
        }

        public override void UpdateStatus(QcMessage Datagram)
        {
            base.UpdateStatus(Datagram);
        }
    }
}


text:
/* global Sideshow */
import '@wlk/tutorial/build';
import '@wlk/tutorial/distr/stylesheets/sideshow.min.css';
import '@wlk/tutorial/distr/fonts/sideshow-fontface.min.css';
export default Sideshow;
//# sourceMappingURL=tutorial.js.map


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SolidEdgeSpy.InteropServices;

namespace SolidEdgeSpy.Forms
{
    public partial class TypeBrowser : UserControl
    {
        private bool _scanComplete = false;
        readonly NavigationController<object> _navigationController;

        public TypeBrowser()
        {
            InitializeComponent();

            _navigationController = new NavigationController<object>(buttonBack, buttonForward, 20);

            ComTypeManager.Instance.ComTypeLibrarySelected += Instance_ComTypeLibrarySelected;
            ComTypeManager.Instance.ComTypeInfoSelected += Instance_ComTypeInfoSelected;

            comTypeTreeView.GotFocus += comTypeTreeView_GotFocus;
        }

        private void TypeBrowser_Load(object sender, EventArgs e)
        {
            _navigationController.GotoItem += _navigationController_GotoItem;

            if (comTypeTreeView.Nodes.Count == 0)
            {
                comTypeTreeView.RefreshNodes();
            }
        }

        void _navigationController_GotoItem(object sender, NavigationControllerEventArgs<object> e)
        {
            try
            {
                TreeNode treeNode = e.Item as TreeNode;
                ListViewItem listViewItem = e.Item as ListViewItem;

                if (treeNode != null)
                {
                    treeNode.TreeView.SelectedNode = treeNode;
                    treeNode.EnsureVisible();
                    treeNode.TreeView.Focus();
                }
                else if (listViewItem != null)
                {
                    listViewItem.Selected = true;
                    listViewItem.EnsureVisible();
                    listViewItem.ListView.Focus();
                }
            }
            catch
            {
            }
        }

        void Instance_ComTypeInfoSelected(object sender, ComTypeInfo comTypeInfo)
        {
            _scanComplete = false;

            try
            {
                if (comTypeTreeView.IsFiltered)
                {
                    comTypeTreeView.Filter = String.Empty;
                }

                if (comTypeTreeView.Nodes.Count == 0)
                {
                    comTypeTreeView.RefreshNodes();
                }

                ScanForNodeAndSelect(comTypeInfo, comTypeTreeView.Nodes);
            }
            catch
            {
                GlobalExceptionHandler.HandleException();
            }
        }

        void Instance_ComTypeLibrarySelected(object sender, ComTypeLibrary comTypeLibrary)
        {
            _scanComplete = false;

            try
            {
                if (comTypeTreeView.IsFiltered)
                {
                    comTypeTreeView.Filter = String.Empty;
                }

                if (comTypeTreeView.Nodes.Count == 0)
                {
                    comTypeTreeView.RefreshNodes();
                }

                ScanForNodeAndSelect(comTypeLibrary, comTypeTreeView.Nodes);
            }
            catch
            {
                GlobalExceptionHandler.HandleException();
            }
        }

        public void ScanForNodeAndSelect(ComTypeLibrary comTypeLibrary, TreeNodeCollection nodes)
        {
            if (comTypeLibrary == null) return;
            if (nodes == null) return;
            if (_scanComplete == true) return;

            foreach (TreeNode node in nodes)
            {
                ComTypeLibraryTreeNode comTypeLibraryTreeNode = node as ComTypeLibraryTreeNode;

                if (comTypeLibraryTreeNode != null)
                {
                    if (comTypeLibraryTreeNode.ComTypeLibrary.Name.Equals(comTypeLibrary.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        _scanComplete = true;
                        node.TreeView.SelectedNode = node;
                        node.EnsureVisible();
                        return;
                    }
                }
            }
        }

        public void ScanForNodeAndSelect(ComTypeInfo comTypeInfo, TreeNodeCollection nodes)
        {
            if (comTypeInfo == null) return;
            if (nodes == null) return;
            if (_scanComplete == true) return;

            foreach (TreeNode node in nodes)
            {
                ComTypeLibraryTreeNode comTypeLibraryTreeNode = node as ComTypeLibraryTreeNode;
                ComTypeInfoTreeNode comTypeInfoTreeNode = node as ComTypeInfoTreeNode;

                if (comTypeLibraryTreeNode != null)
                {
                    if (comTypeLibraryTreeNode.ComTypeLibrary.Name.Equals(comTypeInfo.ComTypeLibrary.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        ScanForNodeAndSelect(comTypeInfo, node.Nodes);
                        return;
                    }
                }
                else if (comTypeInfoTreeNode != null)
                {
                    if (comTypeInfoTreeNode.ComTypeInfo.Name.Equals(comTypeInfo.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        _scanComplete = true;
                        node.TreeView.SelectedNode = node;
                        node.EnsureVisible();
                        return;
                    }
                }
            }
        }

        void comTypeTreeView_GotFocus(object sender, EventArgs e)
        {
            comTypeTreeView_AfterSelect(comTypeTreeView, new TreeViewEventArgs(comTypeTreeView.SelectedNode));
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            comTypeTreeView.RefreshNodes();
        }

        private void comTypeTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            _navigationController.Remove(comTypeListView.Items.OfType<ListViewItem>().ToArray());
            _navigationController.CurrentItem = e.Node;

            ComTypeLibraryTreeNode comTypeLibraryTreeNode = e.Node as ComTypeLibraryTreeNode;
            ComTypeInfoTreeNode comTypeInfoTreeNode = e.Node as ComTypeInfoTreeNode;
            ComFunctionInfoTreeNode comFunctionInfoTreeNode = e.Node as ComFunctionInfoTreeNode;
            ComPropertyInfoTreeNode comPropertyInfoTreeNode = e.Node as ComPropertyInfoTreeNode;
            ComVariableInfoTreeNode comVariableInfoTreeNode = e.Node as ComVariableInfoTreeNode;

            comTypeListView.SelectedComTypeInfo = null;

            if (comTypeLibraryTreeNode != null)
            {
                typeInfoRichTextBox.DescribeComTypeLibrary(comTypeLibraryTreeNode.ComTypeLibrary);
            }
            else if (comTypeInfoTreeNode != null)
            {
                ComTypeInfo comTypeInfo = comTypeInfoTreeNode.ComTypeInfo;
                comTypeListView.SelectedComTypeInfo = comTypeInfo;
                typeInfoRichTextBox.DescribeComTypeInfo(comTypeInfo);
            }
            else if (comFunctionInfoTreeNode != null)
            {
                typeInfoRichTextBox.DescribeComFunctionInfo(comFunctionInfoTreeNode.ComFunctionInfo);
            }
            else if (comPropertyInfoTreeNode != null)
            {
                typeInfoRichTextBox.DescribeComPropertyInfo(comPropertyInfoTreeNode.ComPropertyInfo);
            }
            else if (comVariableInfoTreeNode != null)
            {
                typeInfoRichTextBox.DescribeComVariableInfo(comVariableInfoTreeNode.ComVariableInfo);
            }
        }

        private void comTypeListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comTypeListView.SelectedItems.Count > 0)
            {
                ListViewItem item = comTypeListView.SelectedItems[0];

                if (item.Tag is ComFunctionInfo)
                {
                    typeInfoRichTextBox.DescribeComFunctionInfo((ComFunctionInfo)item.Tag);
                }
                else if (item.Tag is ComPropertyInfo)
                {
                    typeInfoRichTextBox.DescribeComPropertyInfo((ComPropertyInfo)item.Tag);
                }
                else if (item.Tag is ComVariableInfo)
                {
                    typeInfoRichTextBox.DescribeComVariableInfo((ComVariableInfo)item.Tag);
                }

                _navigationController.CurrentItem = item;
            }
        }

        private void typeInfoRichTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            try
            {
                string[] linkInfo = e.LinkText.Split(new char[] { '#' });

                switch (linkInfo.Length)
                {
                    case 1:
                        ComTypeManager.Instance.LookupAndSelect(linkInfo[0]);
                        break;
                    case 2:
                        ComTypeManager.Instance.LookupAndSelect(linkInfo[1]);
                        break;
                }
            }
            catch
            {
                GlobalExceptionHandler.HandleException();
            }
        }

        private void textBoxSearch_TextAccepted(object sender, EventArgs e)
        {
            buttonSearch_Click(sender, e);
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            comTypeTreeView.Filter = textBoxSearch.Text;
        }

        private void buttonClearSearch_Click(object sender, EventArgs e)
        {
            comTypeTreeView.Filter = String.Empty;
        }

        private void comTypeTreeView_FilterChanged(object sender, EventArgs e)
        {
            if (comTypeTreeView.IsFiltered == false)
            {
                textBoxSearch.Text = String.Empty;
            }

            _navigationController.Clear();
            comTypeListView.SelectedComTypeInfo = null;
            typeInfoRichTextBox.Clear();
        }
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p169;

import org.gradle.test.performance.mediummonolithicjavaproject.p168.Production3376;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test3385 {
    Production3385 objectUnderTest = new Production3385();

    @Test
    public void testProperty0() {
        Production3376 value = new Production3376();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production3380 value = new Production3380();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production3384 value = new Production3384();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Bull. Acad. sin. , Taipei 44(3): 253 (2003)

#### Original name
Tubeufia dactylariae H.S. Chang

### Remarks
null


text:
'use strict';
var passport = require('passport');
// Draw routes.  Locomotive's router provides expressive syntax for drawing
// routes, including support for resourceful routes, namespaces, and nesting.
// MVC routes can be mapped to controllers using convenient
// `controller#action` shorthand.  Standard middleware in the form of
// `function(req, res, next)` is also fully supported.  Consult the Locomotive
// Guide on [routing](http://locomotivejs.org/guide/routing.html) for additional
// information.
module.exports = function routes() {

  // Protect post and put
  this.post('*', passport.authenticate('basic', { session : false }) );
  this.put('*', passport.authenticate('basic', { session : false }) );
  this.delete('*', passport.authenticate('basic', { session : false }) );

  this.root('index#main');
  this.resources('locations', function () {
    this.resources('connections');
    this.resources('commodities',
    function() {
      this.get('traderoutes','traderoutes#show');
    });
    this.get('traderoutes','traderoutes#show');

  });
  //this.post('locations/search', passport.authenticate('basic', { session : false }) );
  this.post('locations/search','search#show');

  this.resources('commoditygroups', function() {
    this.resources('commoditytypes');
  });
  this.resources('commoditytypes');

  this.get('traderoutes','traderoutes#show');

  //this.get('/locations', passport.authenticate('basic', { session : false }) );
  //this.post('*', passport.authenticate('basic', { session : false }) );
  //this.put('*', passport.authenticate('basic', { session : false }) );

};


text:
class MakeQuestItemRevisable < ActiveRecord::Migration

  def self.up
    add_column :quest_items, :revisable_original_id, :integer
    add_column :quest_items, :revisable_branched_from_id, :integer
    add_column :quest_items, :revisable_number, :integer
    add_column :quest_items, :revisable_name, :string
    add_column :quest_items, :revisable_type, :string
    add_column :quest_items, :revisable_current_at, :datetime
    add_column :quest_items, :revisable_revised_at, :datetime
    add_column :quest_items, :revisable_deleted_at, :datetime
    add_column :quest_items, :revisable_is_current, :boolean
    #
    add_index :quest_items, :revisable_original_id
  end

  def self.down
    remove_column :quest_items, :revisable_original_id
    remove_column :quest_items, :revisable_branched_from_id
    remove_column :quest_items, :revisable_number
    remove_column :quest_items, :revisable_name
    remove_column :quest_items, :revisable_type
    remove_column :quest_items, :revisable_current_at
    remove_column :quest_items, :revisable_revised_at
    remove_column :quest_items, :revisable_deleted_at
    remove_column :quest_items, :revisable_is_current
  end

end


text:
package com.trivago.triava.tcache.action;

import javax.cache.event.EventType;

import com.trivago.triava.tcache.statistics.StatisticsCalculator;
import com.trivago.triava.tcache.util.ChangeStatus;

/**
 * An Action that has both Get and Put characteristics, like getAndPut(), retAndReplace() and the 3-arg replace().
 * Should be renamed to GetPutAction.
 *
 * @author cesken
 *
 * @param <K> The key class
 * @param <V> The value class
 * @param <W> The return type of the writeThroughImpl (unused)
 */
public class ReplaceAction<K, V, W> extends PutAction<K, V, W>
{

	public ReplaceAction(K key, V value, EventType eventType)
	{
		super(key, value, eventType, true);
	}

	@Override
	W writeThroughImpl(ActionRunner<K,V> actionRunner, Object arg)
	{
		ChangeStatus changeStatus = (ChangeStatus) arg;
		if (changeStatus == ChangeStatus.CHANGED)
			return super.writeThroughImpl(actionRunner, arg);

		return null;
	}

	@Override
	void statisticsImpl(ActionRunner<K, V> actionRunner, Object arg)
	{
		StatisticsCalculator stats = actionRunner.stats;
		ChangeStatus changeStatus = (ChangeStatus) arg;
		switch (changeStatus)
		{
			case CHANGED:
				stats.incrementHitCount();
				stats.incrementPutCount();
				break;
			case UNCHANGED:
				stats.incrementMissCount();
				break;
			case CREATED:
//				System.out.println("actionRunnter " + actionRunner + ", cs=" +changeStatus + ", stats B:" + stats);
				stats.incrementMissCount();
//				stats.incrementPutCount(); // cache.putToMap() still does it. Thus do not increment here
//				System.out.println("actionRunnter " + actionRunner + ", cs=" +changeStatus + ", stats A:" + stats);
				break;
			case CAS_FAILED_EQUALS:
				stats.incrementHitCount();
				break;
		}
	}
}


text:
package com.podio.calendar;

import java.util.List;

import org.joda.time.LocalDate;

import com.podio.BaseAPI;
import com.podio.ResourceFactory;
import com.podio.common.CSVUtil;
import com.podio.common.ReferenceType;
import com.podio.serialize.DateTimeUtil;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;

/**
 * The calendar is used to get the calendar for a user. The calendar includes
 * items with a date field in the interval and tasks with a due date in the
 * interval.
 *
 * Calendar entries are always sorted by date.
 */
public class CalendarAPI extends BaseAPI {

	public CalendarAPI(ResourceFactory resourceFactory) {
		super(resourceFactory);
	}

	private List<Event> getCalendar(String path, LocalDate dateFrom,
			LocalDate dateTo, List<Integer> spaceIds, ReferenceType... types) {
		WebResource resource = getResourceFactory().getApiResource(
				"/calendar/" + path + "/");
		resource = resource.queryParam("date_from",
				DateTimeUtil.formatDate(dateFrom));
		resource = resource.queryParam("date_to",
				DateTimeUtil.formatDate(dateTo));
		if (spaceIds != null && spaceIds.size() > 0) {
			resource = resource
					.queryParam("space_ids", CSVUtil.toCSV(spaceIds));
		}
		if (types.length > 0) {
			resource = resource.queryParam("types",
					CSVUtil.toCSV((Object[]) types));
		}

		return resource.get(new GenericType<List<Event>>() {
		});
	}

	/**
	 * Returns the items and tasks that are related to the given app.
	 *
	 * @param appId
	 *            The id of the app
	 * @param dateFrom
	 *            The from date
	 * @param dateTo
	 *            The to date
	 * @param types
	 *            The types of events that should be returned. Leave out to get
	 *            all types of events.
	 * @return The events in the calendar
	 */
	public List<Event> getApp(int appId, LocalDate dateFrom, LocalDate dateTo,
			ReferenceType... types) {
		return getCalendar("app/" + appId, dateFrom, dateTo, null, types);
	}

	/**
	 * Returns all items and tasks that the user have access to in the given
	 * space. Tasks with reference to other spaces are not returned or tasks
	 * with no reference.
	 *
	 * @param spaceId
	 *            The id of the space
	 * @param dateFrom
	 *            The from date
	 * @param dateTo
	 *            The to date
	 * @param types
	 *            The types of events that should be returned. Leave out to get
	 *            all types of events.
	 * @return The events in the calendar
	 */
	public List<Event> getSpace(int spaceId, LocalDate dateFrom,
			LocalDate dateTo, ReferenceType... types) {
		return getCalendar("space/" + spaceId, dateFrom, dateTo, null, types);
	}

	/**
	 * Returns all items that the user have access to and all tasks that are
	 * assigned to the user. The items and tasks can be filtered by a list of
	 * space ids, but tasks without a reference will always be returned.
	 *
	 * @param dateFrom
	 *            The from date
	 * @param dateTo
	 *            The to date
	 * @param types
	 *            The types of events that should be returned. Leave out to get
	 *            all types of events.
	 * @return The events in the calendar
	 */
	public List<Event> getGlobal(LocalDate dateFrom, LocalDate dateTo,
			List<Integer> spaceIds, ReferenceType... types) {
		return getCalendar("", dateFrom, dateTo, spaceIds, types);
	}
}


text:
import {onSelect} from "../services/dom";
import {Component} from "./component";

/**
 * Tabs
 * Works by matching 'tabToggle<Key>' with 'tabContent<Key>' sections.
 */
export class Tabs extends Component {

    setup() {
        this.tabContentsByName = {};
        this.tabButtonsByName = {};
        this.allContents = [];
        this.allButtons = [];

        for (const [key, elems] of Object.entries(this.$manyRefs || {})) {
            if (key.startsWith('toggle')) {
                const cleanKey = key.replace('toggle', '').toLowerCase();
                onSelect(elems, e => this.show(cleanKey));
                this.allButtons.push(...elems);
                this.tabButtonsByName[cleanKey] = elems;
            }
            if (key.startsWith('content')) {
                const cleanKey = key.replace('content', '').toLowerCase();
                this.tabContentsByName[cleanKey] = elems;
                this.allContents.push(...elems);
            }
        }
    }

    show(key) {
        this.allContents.forEach(c => {
            c.classList.add('hidden');
            c.classList.remove('selected');
        });
        this.allButtons.forEach(b => b.classList.remove('selected'));

        const contents = this.tabContentsByName[key] || [];
        const buttons = this.tabButtonsByName[key] || [];
        if (contents.length > 0) {
            contents.forEach(c => {
                c.classList.remove('hidden')
                c.classList.add('selected')
            });
            buttons.forEach(b => b.classList.add('selected'));
        }
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fantastock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Josh
 */
public class JsonHandler {

        private static String readAll(Reader rd) throws IOException {
            StringBuilder sb = new StringBuilder();
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            return sb.toString();
        }

        public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
            InputStream is = new URL(url).openStream();
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                String jsonText = readAll(rd);
                JSONObject json = new JSONObject(jsonText);
                return json;
            } finally {
                is.close();
            }
        }
}


text:
#region Assembly System.Web.Helpers.dll, v3.0.0.0
// D:\GenApps\MaheshTestAppSecurity2\packages\Microsoft.AspNet.WebPages.3.2.2\lib\net45\System.Web.Helpers.dll
#endregion

using System;

namespace System.Web.Helpers
{
    // Summary:
    //     Specifies visual themes for a System.Web.Helpers.Chart object.
    public static class ChartTheme1
    {

        public const string Pie = @"<Chart BackColor=""#f5f5f5"" BorderColor=""14, 10, 11, 0"" BorderWidth=""2"" BorderlineDashStyle=""Solid"" Palette=""BrightPastel"">
  <ChartAreas>
    <ChartArea Name=""Default"" _Template_=""All"" BackColor=""#ffffff"" BackSecondaryColor=""White"" BorderColor=""14, 10, 11, 0"" BorderDashStyle=""Solid"" ShadowColor=""Transparent"">
      <AxisY>
        <LabelStyle Font=""Trebuchet MS, 8.25pt, style=Bold"" />
      </AxisY>
      <AxisX LineColor=""14, 10, 11, 0"">
        <LabelStyle Font=""Trebuchet MS, 8.25pt, style=Bold"" />
      </AxisX>
    </ChartArea>
  </ChartAreas>
  <Legends>
    <Legend _Template_=""All"" BackColor=""Transparent"" Docking=""Bottom"" Font=""Trebuchet MS, 8.25pt, style=Bold"" LegendStyle=""Row"">
    </Legend>
  </Legends>
  <BorderSkin SkinStyle=""None"" />
</Chart>";

        public const String ColumnBar = @"<Chart BackColor=""#f5f5f5"" BorderColor=""#e3e3e3"" BorderWidth=""2"" BorderlineDashStyle=""Solid"" Palette=""BrightPastel"">
  <ChartAreas>
    <ChartArea Name=""Default"" _Template_=""All"" BackColor=""#ffffff"" BackSecondaryColor=""White"" BorderColor=""14, 10, 11, 0"" BorderDashStyle=""Solid"" ShadowColor=""Transparent"">
      <AxisY>
        <LabelStyle Font=""Trebuchet MS, 8.25pt, style=Bold"" />
      </AxisY>
      <AxisX LineColor=""14, 10, 11, 0"">
        <LabelStyle Font=""Trebuchet MS, 8.25pt, style=Bold"" />
      </AxisX>
    </ChartArea>
  </ChartAreas>
  <Legends>
    <Legend _Template_=""All"" BackColor=""Transparent"" Docking=""Bottom"" Font=""Trebuchet MS, 8.25pt, style=Bold"" LegendStyle=""Row"">
    </Legend>
  </Legends>
  <BorderSkin SkinStyle=""None"" />
</Chart>";

    }
}


text:
namespace cobalt {
namespace bindings {
namespace testing {

class AnonymousNamedIndexedGetterInterface : public script::Wrappable {
 public:
  MOCK_METHOD0(length, uint32_t());
  MOCK_METHOD1(AnonymousIndexedGetter, uint32_t(uint32_t));
  MOCK_METHOD2(AnonymousIndexedSetter, void(uint32_t, uint32_t));
  MOCK_METHOD1(AnonymousNamedGetter, std::string(const std::string&));
  MOCK_METHOD2(AnonymousNamedSetter,
               void(const std::string&, const std::string&));

  MOCK_METHOD1(CanQueryNamedProperty, bool(const std::string&));
  MOCK_METHOD1(EnumerateNamedProperties, void(script::PropertyEnumerator*));

  DEFINE_WRAPPABLE_TYPE(AnonymousNamedIndexedGetterInterface);
};

}  // namespace testing
}  // namespace bindings
}  // namespace cobalt

#endif  // COBALT_BINDINGS_TESTING_ANONYMOUS_NAMED_INDEXED_GETTER_INTERFACE_H_


text:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class SelectOnInput : MonoBehaviour
{

    public EventSystem eventSystem;
    public GameObject selectedObject;

    private bool buttonSelected;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetAxisRaw("Vertical") != 0 && buttonSelected == false)
        {
            eventSystem.SetSelectedGameObject(selectedObject);
            buttonSelected = true;
        }
    }

    private void OnDisable()
    {
        buttonSelected = false;
    }
}


text:
<?php  defined('C5_EXECUTE') or die(_("Access Denied."));  ?>

<?php  $this->inc('elements/header.php'); ?>

Menu

Content

Footer

				<?php
					 $a = new Area('Header');
					 $a->display($c);
				?>

						<?php
							$a = new Area('Main');
							$a->display($c);
						?>

						<?php
							$a = new Area('Sidebar');
							$a->display($c);
						?>

			<?php  $this->inc('elements/footer.php'); ?>

		<?php  $this->inc('elements/footer-c5.php'); ?>


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Enforcement Rules of the Refrigeration and Air Conditioning Industries Governance Act</英文法規名稱>
<中文法規名稱>冷凍空調業管理條例施行細則</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=J0030083</法規網址>
<最新英文異動日期>20050222</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.Date:February 22,2005 (Announced)]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[These Enforcement Rules are enacted in accordance with Article 26 of the Refrigeration and Air Conditioning Industries Governance Act (the "Act").]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The simple design, construction supervision, installation or maintenance under Paragraph 3, Article 3 of the Act shall refer to the design, construction supervision, installation or maintenance of a single main machine of less than 10 refrigeration tons or 5 horsepower.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[An enterprise may apply for refrigeration and air conditioning company or business incorporation or alteration registration only after obtaining a permit from the central competent authority; upon such incorporation or alteration registration, the enterprise shall apply to the central competent authority for issuance of a refrigeration and air conditioning enterprise registration certificate.
If, after an enterprise has obtained a permit to operate a refrigeration and air conditioning business, there is any alteration in the permitted matters of the enterprise before the application for issuance of a registration certificate is filed, it shall reapply for a permit.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[To apply for a permit to operate a refrigeration and air conditioning enterprise, the applicant shall file a duly completed application form together with the following documents with the central competent authority:
1. Photocopies of its responsible person's ID and certificates and supporting documents of his/her education and work experience.
2. Documents certifying its registered capital.
3. Documents certifying its experience or capability in manufacturing or installing refrigeration and air conditioning engineering work.
4. Roster and photocopied certificates of the full-time engineers or technicians to be employed by it.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[To apply for a refrigeration and air conditioning enterprise registration certificate, the applicant shall file a duly completed application form together with the following documents with the central competent authority:
1. The permit.
2. Documents proving its company or business registration.
3. Roster of its directors, supervisors, executive salespersons, shareholders representing the enterprise or its responsible person.
4. Roster and certificates of the full-time engineers or technicians employed by it.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The refrigeration and air conditioning enterprise directory set forth in Article 8 of the Act shall be prepared by the central competent authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[A "full-time" engineer or technician as referred to in Paragraphs 1 and 2, Article 9 of the Act shall mean an engineer or technician who performs services in the offices of a refrigeration and air conditioning enterprise that employs him/her or outside the offices of the enterprise as arranged by the enterprise during all business hours of the enterprise and is paid for all such business hours, and during his/her employment by the enterprise, does not undertake any part-time business or duties other than those assigned by the enterprise during all its business hours, except for any part-time disaster-relief work, disaster surveys or other business or duties recognized by the central competent authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The application documents set forth in Paragraph 3, Article 10 of the Act shall mean the application forms as well as the documents set forth in Items 2 to 4 of Article 5 of these Enforcement Rules.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[A refrigeration and air conditioning enterprise intending to alter any of the following matters but not its class shall file a duly completed application form together with the relevant materials to request alteration registration:
1. Its registered capital.
2. A full-time engineer or technician employed by it.
A refrigeration and air conditioning enterprise intending to alter any of the following matters shall file a duly completed application form together with the relevant materials to request alteration registration, as well as submit the original registration certificate to request the replacement of its original registration certificate with a new one:
1. Its name.
2. Its place of business.
3. Its unified company or business code.
4. Name of its responsible person.
A refrigeration and air conditioning enterprise intending to alter any of the following matters shall apply for a new permit and a new registration certificate, and its original registration certificate shall be revoked:
1. Alteration of its organization.
2. The class it is classified under.
An application filed under any of the preceding three paragraphs shall be filed with the central competent authority within 30 days after the alteration is made.
A refrigeration and air conditioning enterprise whose registration certificate is lost, destroyed or damaged may apply to the central competent authority for the reissuance thereof.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[A new registration certificate reissued or replaced under the preceding Article shall bear the number of the original certificate, as well as the date of reissuance (replacement) and the words This is a Reissued/Replaced Certificate.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 11</條號>
    <條文內容><![CDATA[A foreign refrigeration and air conditioning enterprise applying to the central competent authority for a permit under Article 22 of the Act shall complete the procedures set forth in Article 4 of these Enforcement Rules, as well as submit documents to prove that it has been incorporated and registered as a refrigeration and air conditioning enterprise in accordance with the laws of its home country.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 12</條號>
    <條文內容><![CDATA[Where a certificate or document required under the preceding Article is produced in a foreign language, such certificate or document shall be subject to the notarization or certification by a local notarizing or certifying institution and attached with a Chinese translation certified or authenticated by the R.O.C. embassy/consulate/representative office/office in the foreign country or another institution authorized by the Ministry of Foreign Affairs of the R.O.C.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13</條號>
    <條文內容><![CDATA[An enterprise applying for replacement of its original refrigeration and air conditioning engineering enterprise registration license with a refrigeration and air conditioning enterprise registration certificate under Paragraph 1, Article 23 of the Act shall submit the following documents to the central competent authority:
1. Its original refrigeration and air conditioning engineering enterprise registration license.
2. Documents set forth in Items 2 to 4 of Article 5 of these Enforcement Rules.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 14</條號>
    <條文內容><![CDATA[These Enforcement Rules shall come into force from the date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
package DDG::Spice::RxInfo;
# ABSTRACT: Given an NDC or physical characteristics, returns an image or images of corresponding pill(s) along with some drug information

use DDG::Spice;

name "RxInfo";
source "C3PI RxImageAccess RESTful API";
description "Search for prespection and over the counter solid dosage pharmaceutical by NDC and characteristics (shape, color, imprint).";
primary_example_queries "pill red round", "rxinfo 68180-0481-01", "pill LL blue";
category "special";
topics "everyday", "special_interest";
code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/RxInfo.pm";
attribution web => ['http://www.medicosconsultants.com', 'Medicos Consultants, LLC'];

triggers startend => 'pill', 'rxinfo', 'capsule', 'tablet', 'softgel', 'caplets';

spice to => 'http://rximage.nlm.nih.gov/api/rximage/1/rxbase?resolution=300&includeIngredients=true&parse=$1';
spice wrap_jsonp_callback => 1;

handle remainder => sub {
    return $_ if $_;
    return;
};
1;


text:
mod group;
mod map;
mod message;
mod oneof;
mod scalar;

use std::fmt;
use std::slice;

use anyhow::{bail, Error};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, Ident, Lit, LitBool, Meta, MetaList, MetaNameValue, NestedMeta};

#[derive(Clone)]
pub enum Field {
    /// A scalar field.
    Scalar(scalar::Field),
    /// A message field.
    Message(message::Field),
    /// A map field.
    Map(map::Field),
    /// A oneof field.
    Oneof(oneof::Field),
    /// A group field.
    Group(group::Field),
}

impl Field {
    /// Creates a new `Field` from an iterator of field attributes.
    ///
    /// If the meta items are invalid, an error will be returned.
    /// If the field should be ignored, `None` is returned.
    pub fn new(attrs: Vec<Attribute>, inferred_tag: Option<u32>) -> Result<Option<Field>, Error> {
        let attrs = prost_attrs(attrs);

        // TODO: check for ignore attribute.

        let field = if let Some(field) = scalar::Field::new(&attrs, inferred_tag)? {
            Field::Scalar(field)
        } else if let Some(field) = message::Field::new(&attrs, inferred_tag)? {
            Field::Message(field)
        } else if let Some(field) = map::Field::new(&attrs, inferred_tag)? {
            Field::Map(field)
        } else if let Some(field) = oneof::Field::new(&attrs)? {
            Field::Oneof(field)
        } else if let Some(field) = group::Field::new(&attrs, inferred_tag)? {
            Field::Group(field)
        } else {
            bail!("no type attribute");
        };

        Ok(Some(field))
    }

    /// Creates a new oneof `Field` from an iterator of field attributes.
    ///
    /// If the meta items are invalid, an error will be returned.
    /// If the field should be ignored, `None` is returned.
    pub fn new_oneof(attrs: Vec<Attribute>) -> Result<Option<Field>, Error> {
        let attrs = prost_attrs(attrs);

        // TODO: check for ignore attribute.

        let field = if let Some(field) = scalar::Field::new_oneof(&attrs)? {
            Field::Scalar(field)
        } else if let Some(field) = message::Field::new_oneof(&attrs)? {
            Field::Message(field)
        } else if let Some(field) = map::Field::new_oneof(&attrs)? {
            Field::Map(field)
        } else if let Some(field) = group::Field::new_oneof(&attrs)? {
            Field::Group(field)
        } else {
            bail!("no type attribute for oneof field");
        };

        Ok(Some(field))
    }

    pub fn tags(&self) -> Vec<u32> {
        match *self {
            Field::Scalar(ref scalar) => vec![scalar.tag],
            Field::Message(ref message) => vec![message.tag],
            Field::Map(ref map) => vec![map.tag],
            Field::Oneof(ref oneof) => oneof.tags.clone(),
            Field::Group(ref group) => vec![group.tag],
        }
    }

    /// Returns a statement which encodes the field.
    pub fn encode(&self, ident: TokenStream) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => scalar.encode(ident),
            Field::Message(ref message) => message.encode(ident),
            Field::Map(ref map) => map.encode(ident),
            Field::Oneof(ref oneof) => oneof.encode(ident),
            Field::Group(ref group) => group.encode(ident),
        }
    }

    /// Returns an expression which evaluates to the result of merging a decoded
    /// value into the field.
    pub fn merge(&self, ident: TokenStream) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => scalar.merge(ident),
            Field::Message(ref message) => message.merge(ident),
            Field::Map(ref map) => map.merge(ident),
            Field::Oneof(ref oneof) => oneof.merge(ident),
            Field::Group(ref group) => group.merge(ident),
        }
    }

    /// Returns an expression which evaluates to the encoded length of the field.
    pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => scalar.encoded_len(ident),
            Field::Map(ref map) => map.encoded_len(ident),
            Field::Message(ref msg) => msg.encoded_len(ident),
            Field::Oneof(ref oneof) => oneof.encoded_len(ident),
            Field::Group(ref group) => group.encoded_len(ident),
        }
    }

    /// Returns a statement which clears the field.
    pub fn clear(&self, ident: TokenStream) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => scalar.clear(ident),
            Field::Message(ref message) => message.clear(ident),
            Field::Map(ref map) => map.clear(ident),
            Field::Oneof(ref oneof) => oneof.clear(ident),
            Field::Group(ref group) => group.clear(ident),
        }
    }

    pub fn default(&self) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => scalar.default(),
            _ => quote!(::core::default::Default::default()),
        }
    }

    /// Produces the fragment implementing debug for the given field.
    pub fn debug(&self, ident: TokenStream) -> TokenStream {
        match *self {
            Field::Scalar(ref scalar) => {
                let wrapper = scalar.debug(quote!(ScalarWrapper));
                quote! {
                    {
                        #wrapper
                        ScalarWrapper(&#ident)
                    }
                }
            }
            Field::Map(ref map) => {
                let wrapper = map.debug(quote!(MapWrapper));
                quote! {
                    {
                        #wrapper
                        MapWrapper(&#ident)
                    }
                }
            }
            _ => quote!(&#ident),
        }
    }

    pub fn methods(&self, ident: &Ident) -> Option<TokenStream> {
        match *self {
            Field::Scalar(ref scalar) => scalar.methods(ident),
            Field::Map(ref map) => map.methods(ident),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Label {
    /// An optional field.
    Optional,
    /// A required field.
    Required,
    /// A repeated field.
    Repeated,
}

impl Label {
    fn as_str(self) -> &'static str {
        match self {
            Label::Optional => "optional",
            Label::Required => "required",
            Label::Repeated => "repeated",
        }
    }

    fn variants() -> slice::Iter<'static, Label> {
        const VARIANTS: &[Label] = &[Label::Optional, Label::Required, Label::Repeated];
        VARIANTS.iter()
    }

    /// Parses a string into a field label.
    /// If the string doesn't match a field label, `None` is returned.
    fn from_attr(attr: &Meta) -> Option<Label> {
        if let Meta::Path(ref path) = *attr {
            for &label in Label::variants() {
                if path.is_ident(label.as_str()) {
                    return Some(label);
                }
            }
        }
        None
    }
}

impl fmt::Debug for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Get the items belonging to the 'prost' list attribute, e.g. `#[prost(foo, bar="baz")]`.
fn prost_attrs(attrs: Vec<Attribute>) -> Vec<Meta> {
    attrs
        .iter()
        .flat_map(Attribute::parse_meta)
        .flat_map(|meta| match meta {
            Meta::List(MetaList { path, nested, .. }) => {
                if path.is_ident("prost") {
                    nested.into_iter().collect()
                } else {
                    Vec::new()
                }
            }
            _ => Vec::new(),
        })
        .flat_map(|attr| -> Result<_, _> {
            match attr {
                NestedMeta::Meta(attr) => Ok(attr),
                NestedMeta::Lit(lit) => bail!("invalid prost attribute: {:?}", lit),
            }
        })
        .collect()
}

pub fn set_option<T>(option: &mut Option<T>, value: T, message: &str) -> Result<(), Error>
where
    T: fmt::Debug,
{
    if let Some(ref existing) = *option {
        bail!("{}: {:?} and {:?}", message, existing, value);
    }
    *option = Some(value);
    Ok(())
}

pub fn set_bool(b: &mut bool, message: &str) -> Result<(), Error> {
    if *b {
        bail!("{}", message);
    } else {
        *b = true;
        Ok(())
    }
}

/// Unpacks an attribute into a (key, boolean) pair, returning the boolean value.
/// If the key doesn't match the attribute, `None` is returned.
fn bool_attr(key: &str, attr: &Meta) -> Result<Option<bool>, Error> {
    if !attr.path().is_ident(key) {
        return Ok(None);
    }
    match *attr {
        Meta::Path(..) => Ok(Some(true)),
        Meta::List(ref meta_list) => {
            // TODO(rustlang/rust#23121): slice pattern matching would make this much nicer.
            if meta_list.nested.len() == 1 {
                if let NestedMeta::Lit(Lit::Bool(LitBool { value, .. })) = meta_list.nested[0] {
                    return Ok(Some(value));
                }
            }
            bail!("invalid {} attribute", key);
        }
        Meta::NameValue(MetaNameValue {
            lit: Lit::Str(ref lit),
            ..
        }) => lit
            .value()
            .parse::<bool>()
            .map_err(Error::from)
            .map(Option::Some),
        Meta::NameValue(MetaNameValue {
            lit: Lit::Bool(LitBool { value, .. }),
            ..
        }) => Ok(Some(value)),
        _ => bail!("invalid {} attribute", key),
    }
}

/// Checks if an attribute matches a word.
fn word_attr(key: &str, attr: &Meta) -> bool {
    if let Meta::Path(ref path) = *attr {
        path.is_ident(key)
    } else {
        false
    }
}

pub(super) fn tag_attr(attr: &Meta) -> Result<Option<u32>, Error> {
    if !attr.path().is_ident("tag") {
        return Ok(None);
    }
    match *attr {
        Meta::List(ref meta_list) => {
            // TODO(rustlang/rust#23121): slice pattern matching would make this much nicer.
            if meta_list.nested.len() == 1 {
                if let NestedMeta::Lit(Lit::Int(ref lit)) = meta_list.nested[0] {
                    return Ok(Some(lit.base10_parse()?));
                }
            }
            bail!("invalid tag attribute: {:?}", attr);
        }
        Meta::NameValue(ref meta_name_value) => match meta_name_value.lit {
            Lit::Str(ref lit) => lit
                .value()
                .parse::<u32>()
                .map_err(Error::from)
                .map(Option::Some),
            Lit::Int(ref lit) => Ok(Some(lit.base10_parse()?)),
            _ => bail!("invalid tag attribute: {:?}", attr),
        },
        _ => bail!("invalid tag attribute: {:?}", attr),
    }
}

fn tags_attr(attr: &Meta) -> Result<Option<Vec<u32>>, Error> {
    if !attr.path().is_ident("tags") {
        return Ok(None);
    }
    match *attr {
        Meta::List(ref meta_list) => {
            let mut tags = Vec::with_capacity(meta_list.nested.len());
            for item in &meta_list.nested {
                if let NestedMeta::Lit(Lit::Int(ref lit)) = *item {
                    tags.push(lit.base10_parse()?);
                } else {
                    bail!("invalid tag attribute: {:?}", attr);
                }
            }
            Ok(Some(tags))
        }
        Meta::NameValue(MetaNameValue {
            lit: Lit::Str(ref lit),
            ..
        }) => lit
            .value()
            .split(',')
            .map(|s| s.trim().parse::<u32>().map_err(Error::from))
            .collect::<Result<Vec<u32>, _>>()
            .map(Some),
        _ => bail!("invalid tag attribute: {:?}", attr),
    }
}


text:
package lib

import (
	"fmt"
	"github.com/belogik/goes"
	"net/http"
	"net/url"
	"strconv"
)

type JsonPresenter struct {
}

func (p *JsonPresenter) Present(data *goes.Response, ctx *Context) *Results {
	var items []*Item

	dataItems := data.Hits.Hits
	var itemImage map[string]interface{}

	for _, it := range dataItems {
		source := it.Source
		title := source["title"].(string)
		slug := source["slug"].(string)
		currency := source["currency_code"].(string)
		price := uint64(source["price"].(float64))
		shop := source["shop"].(map[string]interface{})
		shopId := shop["id"].(float64)
		url := shop["url"].(string)

		formattedPrice := formatAmount(price, currency)

		itemLinks := map[string]*Link{
			"web": &Link{Href: fmt.Sprintf("http://%s/products/%s", url, slug)},
		}

		if img, ok := source["image"]; ok {
			itemImage = img.(map[string]interface{})
		}

		itemLinks["thumbnail"] = &Link{Href: itemThumbnail(shopId, ctx.CdnHost, itemImage)}

		item := &Item{
			Links:          itemLinks,
			Title:          title,
			Price:          price,
			FormattedPrice: formattedPrice,
		}

		items = append(items, item)
	}

	var embeddedItems interface{}

	if len(items) == 0 {
		embeddedItems = []string{}
	} else {
		embeddedItems = items
	}

	page := ctx.Page
	perPage := ctx.PerPage
	q := ctx.Q

	embedded := map[string]interface{}{
		"items": embeddedItems,
	}

	var nextPage uint64

	tot := (page-1)*perPage + uint64(len(items))
	if tot < data.Hits.Total {
		nextPage = page + 1
	}

	links := map[string]interface{}{}

	links["self"] = paginationLink(ctx.Req, q, page, perPage)

	if nextPage > 0 {
		links["next"] = paginationLink(ctx.Req, q, nextPage, perPage)
	}

	if page > 1 {
		links["prev"] = paginationLink(ctx.Req, q, page-1, perPage)
	}

	results := &Results{
		Links:      links,
		TotalItems: data.Hits.Total,
		Page:       page,
		PerPage:    perPage,
		Embedded:   embedded,
	}

	return results
}

func paginationLink(req *http.Request, q string, page, perPage uint64) *Link {
	u := &url.URL{
		Scheme: "http",
		Host:   req.Host,
		Path:   req.URL.Path,
	}

	query := u.Query()
	query.Set("page", strconv.FormatUint(page, 10))
	query.Set("per_page", strconv.FormatUint(perPage, 10))
	query.Set("q", q)
	u.RawQuery = query.Encode()

	return &Link{Href: u.String()}
}

func itemThumbnail(shopId float64, cdnHost string, image map[string]interface{}) string {
	// https://o.btcdn.co/224/thumbnail/25368-stallion2.gif
	var fileName string
	if fn, ok := image["file_name"]; ok {
		fileName = fn.(string)
	} else {
		return ""
	}
	id := image["id"].(string)

	return fmt.Sprintf("%s/%.0f/thumbnail/%s-%s", cdnHost, shopId, id, fileName)
}


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

import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorColumnHandle;
import com.facebook.presto.spi.type.Type;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;

public class JmxColumnHandle
        implements ConnectorColumnHandle
{
    private final String connectorId;
    private final String columnName;
    private final Type columnType;
    private final int ordinalPosition;

    @JsonCreator
    public JmxColumnHandle(
            @JsonProperty("connectorId") String connectorId,
            @JsonProperty("columnName") String columnName,
            @JsonProperty("columnType") Type columnType,
            @JsonProperty("ordinalPosition") int ordinalPosition)
    {
        this.connectorId = connectorId;
        this.columnName = columnName;
        this.columnType = columnType;
        this.ordinalPosition = ordinalPosition;
    }

    @JsonProperty
    public String getConnectorId()
    {
        return connectorId;
    }

    @JsonProperty
    public String getColumnName()
    {
        return columnName;
    }

    @JsonProperty
    public Type getColumnType()
    {
        return columnType;
    }

    @JsonProperty
    public int getOrdinalPosition()
    {
        return ordinalPosition;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(connectorId, columnName, columnType);
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        JmxColumnHandle other = (JmxColumnHandle) obj;
        return Objects.equals(this.connectorId, other.connectorId) &&
                Objects.equals(this.columnName, other.columnName) &&
                Objects.equals(this.columnType, other.columnType);
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("connectorId", connectorId)
                .add("columnName", columnName)
                .add("columnType", columnType)
                .toString();
    }

    public ColumnMetadata getColumnMetadata()
    {
        return new ColumnMetadata(columnName, columnType, ordinalPosition, false);
    }
}


text:
(function() {
  var CommandGoogleCalender, Icommand, Moment, request,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  Icommand = require('../icommand.js');

  request = require('request');

  Moment = require('moment');

  CommandGoogleCalender = (function(superClass) {
    extend(CommandGoogleCalender, superClass);

    function CommandGoogleCalender() {
      this.APIPath = 'https://clients6.google.com/calendar/v3/calendars/@/events';
    }

    CommandGoogleCalender.prototype.handle = function(sender, text, args, storage, textRouter, commandManager) {
      var calenderId;
      if (args.length === 1 || (args.length === 2 && args[1] === "")) {
        return false;
      }
      calenderId = args[1];
      request.get({
        url: this.APIPath,
        qs: {
          calendarId: calenderId,
          maxResults: 20,
          singleEvents: true,
          key: 'AIzaSyBNlYH01_9Hc5S1J9vuFmu2nUqBZJNAXxs',
          maxAttendees: 1,
          timeZone: 'Asia/Taipei',
          sanitizeHtml: true,
          orderBy: 'startTime',
          timeMin: (new Date).toJSON()
        }
      }, (function(_this) {
        return function(error, response, body) {
          var err, error1, items;
          if (error) {
            console.error(error);
          }
          if (response.statusCode !== 200) {
            console.log(response.statusCode);
            console.log(body);
          }
          if (!error && response.statusCode === 200) {
            try {
              body = JSON.parse(body);
            } catch (error1) {
              err = error1;
              return console.error(err);
            }
            items = body.items;
            items = items.map(function(item) {
              var date, displayDate;
              date = item.start.dateTime || item.start.date;
              displayDate = (Moment(date)).format('LL');
              return displayDate + " " + item.summary;
            });
            return commandManager.send(sender, textRouter, items.join('\r\n'));
          }
        };
      })(this));
      return true;
    };

    CommandGoogleCalender.prototype.help = function(commandPrefix) {
      return ["make this bot to say some message", "this command will send to you according to where you exec this command, Usage", commandPrefix + " [-rj] messages..", "flags:", "r: raw string, no line break", "j: full js format string"];
    };

    CommandGoogleCalender.prototype.hasPermission = function(sender, text, args, storage, textRouter, commandManager, fromBinding) {
      return true;
    };

    return CommandGoogleCalender;

  })(Icommand);

  module.exports = CommandGoogleCalender;

}).call(this);