stateBeansList=null;\n\t\tInteger projectID = serializableBeanAllowedContext.getProjectID();\n\t\tInteger issueTypeID = serializableBeanAllowedContext.getIssueTypeID();\n", "answers": ["\t\tif (projectID==null || issueTypeID==null) {"], "length": 1101, "dataset": "lcc", "language": "java", "all_classes": null, "_id": "63fdad7f1feacdf8cca4aaf57dae737d83c351d9ab66db8b"}
{"input": "", "context": "# Copyright 2009-2013 Canonical Ltd. This software is licensed under the\n# GNU Affero General Public License version 3 (see the file LICENSE).\n\"\"\"Browser views for products.\"\"\"\n__metaclass__ = type\n__all__ = [\n 'ProductAddSeriesView',\n 'ProductAddView',\n 'ProductAddViewBase',\n 'ProductAdminView',\n 'ProductBrandingView',\n 'ProductBugsMenu',\n 'ProductConfigureBase',\n 'ProductConfigureAnswersView',\n 'ProductConfigureBlueprintsView',\n 'ProductDownloadFileMixin',\n 'ProductDownloadFilesView',\n 'ProductEditPeopleView',\n 'ProductEditView',\n 'ProductFacets',\n 'ProductInvolvementView',\n 'ProductNavigation',\n 'ProductNavigationMenu',\n 'ProductOverviewMenu',\n 'ProductPackagesView',\n 'ProductPackagesPortletView',\n 'ProductPurchaseSubscriptionView',\n 'ProductRdfView',\n 'ProductReviewLicenseView',\n 'ProductSeriesSetView',\n 'ProductSetBreadcrumb',\n 'ProductSetFacets',\n 'ProductSetNavigation',\n 'ProductSetReviewLicensesView',\n 'ProductSetView',\n 'ProductSpecificationsMenu',\n 'ProductView',\n 'SortSeriesMixin',\n 'ProjectAddStepOne',\n 'ProjectAddStepTwo',\n ]\nfrom operator import attrgetter\nfrom lazr.delegates import delegates\nfrom lazr.restful.interface import copy_field\nfrom lazr.restful.interfaces import IJSONRequestCache\nfrom z3c.ptcompat import ViewPageTemplateFile\nfrom zope.component import getUtility\nfrom zope.event import notify\nfrom zope.formlib import form\nfrom zope.formlib.interfaces import WidgetInputError\nfrom zope.formlib.widget import CustomWidgetFactory\nfrom zope.formlib.widgets import (\n CheckBoxWidget,\n TextAreaWidget,\n TextWidget,\n )\nfrom zope.interface import (\n implements,\n Interface,\n )\nfrom zope.lifecycleevent import ObjectCreatedEvent\nfrom zope.schema import (\n Bool,\n Choice,\n )\nfrom zope.schema.vocabulary import (\n SimpleTerm,\n SimpleVocabulary,\n )\nfrom lp import _\nfrom lp.answers.browser.faqtarget import FAQTargetNavigationMixin\nfrom lp.answers.browser.questiontarget import (\n QuestionTargetFacetMixin,\n QuestionTargetTraversalMixin,\n )\nfrom lp.app.browser.launchpadform import (\n action,\n custom_widget,\n LaunchpadEditFormView,\n LaunchpadFormView,\n ReturnToReferrerMixin,\n safe_action,\n )\nfrom lp.app.browser.lazrjs import (\n BooleanChoiceWidget,\n InlinePersonEditPickerWidget,\n TextLineEditorWidget,\n )\nfrom lp.app.browser.multistep import (\n MultiStepView,\n StepView,\n )\nfrom lp.app.browser.stringformatter import FormattersAPI\nfrom lp.app.browser.tales import (\n format_link,\n MenuAPI,\n )\nfrom lp.app.enums import (\n InformationType,\n PROPRIETARY_INFORMATION_TYPES,\n PUBLIC_PROPRIETARY_INFORMATION_TYPES,\n ServiceUsage,\n )\nfrom lp.app.errors import NotFoundError\nfrom lp.app.interfaces.headings import IEditableContextTitle\nfrom lp.app.interfaces.launchpad import ILaunchpadCelebrities\nfrom lp.app.utilities import json_dump_information_types\nfrom lp.app.vocabularies import InformationTypeVocabulary\nfrom lp.app.widgets.date import DateWidget\nfrom lp.app.widgets.itemswidgets import (\n CheckBoxMatrixWidget,\n LaunchpadRadioWidget,\n LaunchpadRadioWidgetWithDescription,\n )\nfrom lp.app.widgets.popup import PersonPickerWidget\nfrom lp.app.widgets.product import (\n GhostWidget,\n LicenseWidget,\n ProductNameWidget,\n )\nfrom lp.app.widgets.textwidgets import StrippedTextWidget\nfrom lp.blueprints.browser.specificationtarget import (\n HasSpecificationsMenuMixin,\n )\nfrom lp.bugs.browser.bugtask import (\n BugTargetTraversalMixin,\n get_buglisting_search_filter_url,\n )\nfrom lp.bugs.browser.structuralsubscription import (\n expose_structural_subscription_data_to_js,\n StructuralSubscriptionMenuMixin,\n StructuralSubscriptionTargetTraversalMixin,\n )\nfrom lp.bugs.interfaces.bugtask import RESOLVED_BUGTASK_STATUSES\nfrom lp.code.browser.branchref import BranchRef\nfrom lp.code.browser.sourcepackagerecipelisting import HasRecipesMenuMixin\nfrom lp.registry.browser import (\n add_subscribe_link,\n BaseRdfView,\n )\nfrom lp.registry.browser.announcement import HasAnnouncementsView\nfrom lp.registry.browser.branding import BrandingChangeView\nfrom lp.registry.browser.menu import (\n IRegistryCollectionNavigationMenu,\n RegistryCollectionActionMenuBase,\n )\nfrom lp.registry.browser.pillar import (\n PillarBugsMenu,\n PillarInvolvementView,\n PillarNavigationMixin,\n PillarViewMixin,\n )\nfrom lp.registry.browser.productseries import get_series_branch_error\nfrom lp.registry.interfaces.pillar import IPillarNameSet\nfrom lp.registry.interfaces.product import (\n IProduct,\n IProductReviewSearch,\n IProductSet,\n License,\n LicenseStatus,\n )\nfrom lp.registry.interfaces.productrelease import (\n IProductRelease,\n IProductReleaseSet,\n )\nfrom lp.registry.interfaces.productseries import IProductSeries\nfrom lp.registry.interfaces.series import SeriesStatus\nfrom lp.registry.interfaces.sourcepackagename import ISourcePackageNameSet\nfrom lp.services.config import config\nfrom lp.services.database.decoratedresultset import DecoratedResultSet\nfrom lp.services.feeds.browser import FeedsMixin\nfrom lp.services.fields import (\n PillarAliases,\n PublicPersonChoice,\n )\nfrom lp.services.librarian.interfaces import ILibraryFileAliasSet\nfrom lp.services.propertycache import cachedproperty\nfrom lp.services.webapp import (\n ApplicationMenu,\n canonical_url,\n enabled_with_permission,\n LaunchpadView,\n Link,\n Navigation,\n sorted_version_numbers,\n StandardLaunchpadFacets,\n stepthrough,\n stepto,\n structured,\n )\nfrom lp.services.webapp.authorization import check_permission\nfrom lp.services.webapp.batching import BatchNavigator\nfrom lp.services.webapp.breadcrumb import Breadcrumb\nfrom lp.services.webapp.interfaces import UnsafeFormGetSubmissionError\nfrom lp.services.webapp.menu import NavigationMenu\nfrom lp.services.worlddata.helpers import browser_languages\nfrom lp.services.worlddata.interfaces.country import ICountry\nfrom lp.translations.browser.customlanguagecode import (\n HasCustomLanguageCodesTraversalMixin,\n )\nOR = ' OR '\nSPACE = ' '\nclass ProductNavigation(\n Navigation, BugTargetTraversalMixin,\n FAQTargetNavigationMixin, HasCustomLanguageCodesTraversalMixin,\n QuestionTargetTraversalMixin, StructuralSubscriptionTargetTraversalMixin,\n PillarNavigationMixin):\n usedfor = IProduct\n @stepto('.bzr')\n def dotbzr(self):\n if self.context.development_focus.branch:\n return BranchRef(self.context.development_focus.branch)\n else:\n return None\n @stepthrough('+spec')\n def traverse_spec(self, name):\n spec = self.context.getSpecification(name)\n if not check_permission('launchpad.LimitedView', spec):\n return None\n return spec\n @stepthrough('+milestone')\n def traverse_milestone(self, name):\n return self.context.getMilestone(name)\n @stepthrough('+release')\n def traverse_release(self, name):\n return self.context.getRelease(name)\n @stepthrough('+announcement')\n def traverse_announcement(self, name):\n return self.context.getAnnouncement(name)\n @stepthrough('+commercialsubscription')\n def traverse_commercialsubscription(self, name):\n return self.context.commercial_subscription\n def traverse(self, name):\n return self.context.getSeries(name)\nclass ProductSetNavigation(Navigation):\n usedfor = IProductSet\n def traverse(self, name):\n product = self.context.getByName(name)\n if product is None:\n raise NotFoundError(name)\n return self.redirectSubTree(canonical_url(product))\nclass ProductLicenseMixin:\n \"\"\"Adds licence validation and requests reviews of licences.\n Subclasses must inherit from Launchpad[Edit]FormView as well.\n Requires the \"product\" attribute be set in the child\n classes' action handler.\n \"\"\"\n def validate(self, data):\n \"\"\"Validate 'licenses' and 'license_info'.\n 'licenses' must not be empty unless the product already\n exists and never has had a licence set.\n 'license_info' must not be empty if \"Other/Proprietary\"\n or \"Other/Open Source\" is checked.\n \"\"\"\n licenses = data.get('licenses', [])\n license_widget = self.widgets.get('licenses')\n if (len(licenses) == 0 and license_widget is not None):\n self.setFieldError(\n 'licenses',\n 'You must select at least one licence. If you select '\n 'Other/Proprietary or Other/OpenSource you must include a '\n 'description of the licence.')\n elif License.OTHER_PROPRIETARY in licenses:\n if not data.get('license_info'):\n self.setFieldError(\n 'license_info',\n 'A description of the \"Other/Proprietary\" '\n 'licence you checked is required.')\n elif License.OTHER_OPEN_SOURCE in licenses:\n if not data.get('license_info'):\n self.setFieldError(\n 'license_info',\n 'A description of the \"Other/Open Source\" '\n 'licence you checked is required.')\n else:\n # Launchpad is ok with all licenses used in this project.\n pass\nclass ProductFacets(QuestionTargetFacetMixin, StandardLaunchpadFacets):\n \"\"\"The links that will appear in the facet menu for an IProduct.\"\"\"\n usedfor = IProduct\n enable_only = ['overview', 'bugs', 'answers', 'specifications',\n 'translations', 'branches']\n links = StandardLaunchpadFacets.links\n def overview(self):\n text = 'Overview'\n summary = 'General information about %s' % self.context.displayname\n return Link('', text, summary)\n def bugs(self):\n text = 'Bugs'\n summary = 'Bugs reported about %s' % self.context.displayname\n return Link('', text, summary)\n def branches(self):\n text = 'Code'\n summary = 'Branches for %s' % self.context.displayname\n return Link('', text, summary)\n def specifications(self):\n text = 'Blueprints'\n summary = 'Feature specifications for %s' % self.context.displayname\n return Link('', text, summary)\n def translations(self):\n text = 'Translations'\n summary = 'Translations of %s in Launchpad' % self.context.displayname\n return Link('', text, summary)\nclass ProductInvolvementView(PillarInvolvementView):\n \"\"\"Encourage configuration of involvement links for projects.\"\"\"\n has_involvement = True\n @property\n def visible_disabled_link_names(self):\n \"\"\"Show all disabled links...except blueprints\"\"\"\n involved_menu = MenuAPI(self).navigation\n all_links = involved_menu.keys()\n # The register blueprints link should not be shown since its use is\n # not encouraged.\n all_links.remove('register_blueprint')\n return all_links\n @cachedproperty\n def configuration_states(self):\n \"\"\"Create a dictionary indicating the configuration statuses.\n Each app area will be represented in the return dictionary, except\n blueprints which we are not currently promoting.\n \"\"\"\n states = {}\n states['configure_bugtracker'] = (\n self.context.bug_tracking_usage != ServiceUsage.UNKNOWN)\n states['configure_answers'] = (\n self.context.answers_usage != ServiceUsage.UNKNOWN)\n states['configure_translations'] = (\n self.context.translations_usage != ServiceUsage.UNKNOWN)\n states['configure_codehosting'] = (\n self.context.codehosting_usage != ServiceUsage.UNKNOWN)\n return states\n @property\n def configuration_links(self):\n \"\"\"The enabled involvement links.\n Returns a list of dicts keyed by:\n 'link' -- the menu link, and\n 'configured' -- a boolean representing the configuration status.\n \"\"\"\n overview_menu = MenuAPI(self.context).overview\n series_menu = MenuAPI(self.context.development_focus).overview\n configuration_names = [\n 'configure_bugtracker',\n 'configure_answers',\n 'configure_translations',\n #'configure_blueprints',\n ]\n config_list = []\n config_statuses = self.configuration_states\n for key in configuration_names:\n config_list.append(dict(link=overview_menu[key],\n configured=config_statuses[key]))\n # Add the branch configuration in separately.\n set_branch = series_menu['set_branch']\n set_branch.text = 'Configure project branch'\n set_branch.summary = \"Specify the location of this project's code.\"\n config_list.append(\n dict(link=set_branch,\n configured=config_statuses['configure_codehosting']))\n return config_list\n @property\n def registration_completeness(self):\n \"\"\"The percent complete for registration.\"\"\"\n config_statuses = self.configuration_states\n configured = sum(1 for val in config_statuses.values() if val)\n scale = 100\n done = int(float(configured) / len(config_statuses) * scale)\n undone = scale - done\n return dict(done=done, undone=undone)\n @property\n def registration_done(self):\n \"\"\"A boolean indicating that the services are fully configured.\"\"\"\n return (self.registration_completeness['done'] == 100)\nclass ProductNavigationMenu(NavigationMenu):\n usedfor = IProduct\n facet = 'overview'\n links = [\n 'details',\n 'announcements',\n 'downloads',\n ]\n def details(self):\n text = 'Details'\n return Link('', text)\n def announcements(self):\n text = 'Announcements'\n return Link('+announcements', text)\n def downloads(self):\n text = 'Downloads'\n return Link('+download', text)\nclass ProductEditLinksMixin(StructuralSubscriptionMenuMixin):\n \"\"\"A mixin class for menus that need Product edit links.\"\"\"\n @enabled_with_permission('launchpad.Edit')\n def edit(self):\n text = 'Change details'\n return Link('+edit', text, icon='edit')\n @enabled_with_permission('launchpad.BugSupervisor')\n def configure_bugtracker(self):\n text = 'Configure bug tracker'\n summary = 'Specify where bugs are tracked for this project'\n return Link('+configure-bugtracker', text, summary, icon='edit')\n @enabled_with_permission('launchpad.TranslationsAdmin')\n def configure_translations(self):\n text = 'Configure translations'\n summary = 'Allow users to submit translations for this project'\n return Link('+configure-translations', text, summary, icon='edit')\n @enabled_with_permission('launchpad.Edit')\n def configure_answers(self):\n text = 'Configure support tracker'\n summary = 'Allow users to ask questions on this project'\n return Link('+configure-answers', text, summary, icon='edit')\n @enabled_with_permission('launchpad.Edit')\n def configure_blueprints(self):\n text = 'Configure blueprints'\n summary = 'Enable tracking of feature planning.'\n return Link('+configure-blueprints', text, summary, icon='edit')\n @enabled_with_permission('launchpad.Edit')\n def branding(self):\n text = 'Change branding'\n return Link('+branding', text, icon='edit')\n @enabled_with_permission('launchpad.Edit')\n def reassign(self):\n text = 'Change people'\n return Link('+edit-people', text, icon='edit')\n @enabled_with_permission('launchpad.Moderate')\n def review_license(self):\n text = 'Review project'\n return Link('+review-license', text, icon='edit')\n @enabled_with_permission('launchpad.Moderate')\n def administer(self):\n text = 'Administer'\n return Link('+admin', text, icon='edit')\n @enabled_with_permission('launchpad.Driver')\n def sharing(self):\n return Link('+sharing', 'Sharing', icon='edit')\nclass IProductEditMenu(Interface):\n \"\"\"A marker interface for the 'Change details' navigation menu.\"\"\"\nclass IProductActionMenu(Interface):\n \"\"\"A marker interface for the global action navigation menu.\"\"\"\nclass ProductActionNavigationMenu(NavigationMenu, ProductEditLinksMixin):\n \"\"\"A sub-menu for acting upon a Product.\"\"\"\n usedfor = IProductActionMenu\n facet = 'overview'\n title = 'Actions'\n @cachedproperty\n def links(self):\n links = ['edit', 'review_license', 'administer', 'sharing']\n add_subscribe_link(links)\n return links\nclass ProductOverviewMenu(ApplicationMenu, ProductEditLinksMixin,\n HasRecipesMenuMixin):\n usedfor = IProduct\n facet = 'overview'\n links = [\n 'edit',\n 'configure_answers',\n 'configure_blueprints',\n 'configure_bugtracker',\n 'configure_translations',\n 'reassign',\n 'top_contributors',\n 'distributions',\n 'packages',\n 'series',\n 'series_add',\n 'milestones',\n 'downloads',\n 'announce',\n 'announcements',\n 'administer',\n 'review_license',\n 'rdf',\n 'branding',\n 'view_recipes',\n ]\n def top_contributors(self):\n text = 'More contributors'\n return Link('+topcontributors', text, icon='info')\n def distributions(self):\n text = 'Distribution packaging information'\n return Link('+distributions', text, icon='info')\n def packages(self):\n text = 'Show distribution packages'\n return Link('+packages', text, icon='info')\n def series(self):\n text = 'View full history'\n return Link('+series', text, icon='info')\n @enabled_with_permission('launchpad.Driver')\n def series_add(self):\n text = 'Register a series'\n return Link('+addseries', text, icon='add')\n def milestones(self):\n text = 'View milestones'\n return Link('+milestones', text, icon='info')\n @enabled_with_permission('launchpad.Edit')\n def announce(self):\n text = 'Make announcement'\n summary = 'Publish an item of news for this project'\n return Link('+announce', text, summary, icon='add')\n def announcements(self):\n text = 'Read all announcements'\n enabled = bool(self.context.getAnnouncements())\n return Link('+announcements', text, icon='info', enabled=enabled)\n def rdf(self):\n text = structured(\n ''\n 'RDF metadata')\n return Link('+rdf', text, icon='download')\n def downloads(self):\n text = 'Downloads'\n return Link('+download', text, icon='info')\nclass ProductBugsMenu(PillarBugsMenu, ProductEditLinksMixin):\n usedfor = IProduct\n facet = 'bugs'\n configurable_bugtracker = True\n @cachedproperty\n def links(self):\n links = ['filebug', 'bugsupervisor', 'cve']\n add_subscribe_link(links)\n links.append('configure_bugtracker')\n return links\nclass ProductSpecificationsMenu(NavigationMenu, ProductEditLinksMixin,\n HasSpecificationsMenuMixin):\n usedfor = IProduct\n facet = 'specifications'\n links = ['configure_blueprints', 'listall', 'doc', 'assignments', 'new',\n 'register_sprint']\ndef _cmp_distros(a, b):\n \"\"\"Put Ubuntu first, otherwise in alpha order.\"\"\"\n if a == 'ubuntu':\n return -1\n elif b == 'ubuntu':\n return 1\n else:\n return cmp(a, b)\nclass ProductSetBreadcrumb(Breadcrumb):\n \"\"\"Return a breadcrumb for an `IProductSet`.\"\"\"\n text = \"Projects\"\nclass ProductSetFacets(StandardLaunchpadFacets):\n \"\"\"The links that will appear in the facet menu for the IProductSet.\"\"\"\n usedfor = IProductSet\n enable_only = ['overview', 'branches']\nclass SortSeriesMixin:\n \"\"\"Provide access to helpers for series.\"\"\"\n def _sorted_filtered_list(self, filter=None):\n \"\"\"Return a sorted, filtered list of series.\n The series list is sorted by version in reverse order. It is also\n filtered by calling `filter` on every series. If the `filter`\n function returns False, don't include the series. With None (the\n default, include everything).\n The development focus is always first in the list.\n \"\"\"\n series_list = []\n for series in self.product.series:\n if filter is None or filter(series):\n series_list.append(series)\n # In production data, there exist development focus series that are\n # obsolete. This may be caused by bad data, or it may be intended\n # functionality. In either case, ensure that the development focus\n # branch is first in the list.\n if self.product.development_focus in series_list:\n series_list.remove(self.product.development_focus)\n # Now sort the list by name with newer versions before older.\n series_list = sorted_version_numbers(series_list,\n key=attrgetter('name'))\n series_list.insert(0, self.product.development_focus)\n return series_list\n @property\n def sorted_series_list(self):\n \"\"\"Return a sorted list of series.\n The series list is sorted by version in reverse order.\n The development focus is always first in the list.\n \"\"\"\n return self._sorted_filtered_list()\n @property\n def sorted_active_series_list(self):\n \"\"\"Like `sorted_series_list()` but filters out OBSOLETE series.\"\"\"\n # Callback for the filter which only allows series that have not been\n # marked obsolete.\n def check_active(series):\n return series.status != SeriesStatus.OBSOLETE\n return self._sorted_filtered_list(check_active)\nclass ProductWithSeries:\n \"\"\"A decorated product that includes series data.\n The extra data is included in this class to avoid repeated\n database queries. Rather than hitting the database, the data is\n cached locally and simply returned.\n \"\"\"\n # `series` and `development_focus` need to be declared as class\n # attributes so that this class will not delegate the actual instance\n # variables to self.product, which would bypass the caching.\n series = None\n development_focus = None\n delegates(IProduct, 'product')\n def __init__(self, product):\n self.product = product\n self.series = []\n for series in self.product.series:\n series_with_releases = SeriesWithReleases(series, parent=self)\n self.series.append(series_with_releases)\n if self.product.development_focus == series:\n self.development_focus = series_with_releases\n # Get all of the releases for all of the series in a single\n # query. The query sorts the releases properly so we know the\n # resulting list is sorted correctly.\n series_by_id = dict((series.id, series) for series in self.series)\n self.release_by_id = {}\n milestones_and_releases = list(\n self.product.getMilestonesAndReleases())\n for milestone, release in milestones_and_releases:\n series = series_by_id[milestone.productseries.id]\n release_delegate = ReleaseWithFiles(release, parent=series)\n series.addRelease(release_delegate)\n self.release_by_id[release.id] = release_delegate\nclass DecoratedSeries:\n \"\"\"A decorated series that includes helper attributes for templates.\"\"\"\n delegates(IProductSeries, 'series')\n def __init__(self, series):\n self.series = series\n @property\n def css_class(self):\n \"\"\"The highlight, lowlight, or normal CSS class.\"\"\"\n if self.is_development_focus:\n return 'highlight'\n elif self.status == SeriesStatus.OBSOLETE:\n return 'lowlight'\n else:\n # This is normal presentation.\n return ''\n @cachedproperty\n def packagings(self):\n \"\"\"Convert packagings to list to prevent multiple evaluations.\"\"\"\n return list(self.series.packagings)\nclass SeriesWithReleases(DecoratedSeries):\n \"\"\"A decorated series that includes releases.\n The extra data is included in this class to avoid repeated\n database queries. Rather than hitting the database, the data is\n cached locally and simply returned.\n \"\"\"\n # `parent` and `releases` need to be declared as class attributes so that\n # this class will not delegate the actual instance variables to\n # self.series, which would bypass the caching for self.releases and would\n # raise an AttributeError for self.parent.\n parent = None\n releases = None\n def __init__(self, series, parent):\n super(SeriesWithReleases, self).__init__(series)\n self.parent = parent\n self.releases = []\n def addRelease(self, release):\n self.releases.append(release)\n @cachedproperty\n def has_release_files(self):\n for release in self.releases:\n if len(release.files) > 0:\n return True\n return False\nclass ReleaseWithFiles:\n \"\"\"A decorated release that includes product release files.\n The extra data is included in this class to avoid repeated\n database queries. Rather than hitting the database, the data is\n cached locally and simply returned.\n \"\"\"\n # `parent` needs to be declared as class attributes so that\n # this class will not delegate the actual instance variables to\n # self.release, which would raise an AttributeError.\n parent = None\n delegates(IProductRelease, 'release')\n def __init__(self, release, parent):\n self.release = release\n self.parent = parent\n self._files = None\n @property\n def files(self):\n \"\"\"Cache the release files for all the releases in the product.\"\"\"\n if self._files is None:\n # Get all of the files for all of the releases. The query\n # returns all releases sorted properly.\n product = self.parent.parent\n release_delegates = product.release_by_id.values()\n files = getUtility(IProductReleaseSet).getFilesForReleases(\n release_delegates)\n for release_delegate in release_delegates:\n release_delegate._files = []\n for file in files:\n id = file.productrelease.id\n release_delegate = product.release_by_id[id]\n release_delegate._files.append(file)\n # self._files was set above, since self is actually in the\n # release_delegates variable.\n return self._files\n @property\n def name_with_codename(self):\n milestone = self.release.milestone\n if milestone.code_name:\n return \"%s (%s)\" % (milestone.name, milestone.code_name)\n else:\n return milestone.name\n @cachedproperty\n def total_downloads(self):\n \"\"\"Total downloads of files associated with this release.\"\"\"\n return sum(file.libraryfile.hits for file in self.files)\nclass ProductDownloadFileMixin:\n \"\"\"Provides methods for managing download files.\"\"\"\n @cachedproperty\n def product(self):\n \"\"\"Product with all series, release and file data cached.\n Decorated classes are created, and they contain cached data\n obtained with a few queries rather than many iterated queries.\n \"\"\"\n return ProductWithSeries(self.context)\n def deleteFiles(self, releases):\n \"\"\"Delete the selected files from the set of releases.\n :param releases: A set of releases in the view.\n :return: The number of files deleted.\n \"\"\"\n del_count = 0\n for release in releases:\n for release_file in release.files:\n if release_file.libraryfile.id in self.delete_ids:\n release_file.destroySelf()\n self.delete_ids.remove(release_file.libraryfile.id)\n del_count += 1\n return del_count\n def getReleases(self):\n \"\"\"Find the releases with download files for view.\"\"\"\n raise NotImplementedError\n def processDeleteFiles(self):\n \"\"\"If the 'delete_files' button was pressed, process the deletions.\"\"\"\n del_count = None\n if 'delete_files' in self.form:\n if self.request.method == 'POST':\n self.delete_ids = [\n int(value) for key, value in self.form.items()\n if key.startswith('checkbox')]\n del(self.form['delete_files'])\n releases = self.getReleases()\n del_count = self.deleteFiles(releases)\n else:\n # If there is a form submission and it is not a POST then\n # raise an error. This is to protect against XSS exploits.\n raise UnsafeFormGetSubmissionError(self.form['delete_files'])\n if del_count is not None:\n if del_count <= 0:\n self.request.response.addNotification(\n \"No files were deleted.\")\n elif del_count == 1:\n self.request.response.addNotification(\n \"1 file has been deleted.\")\n else:\n self.request.response.addNotification(\n \"%d files have been deleted.\" %\n del_count)\n @cachedproperty\n def latest_release_with_download_files(self):\n \"\"\"Return the latest release with download files.\"\"\"\n for series in self.sorted_active_series_list:\n for release in series.releases:\n if len(list(release.files)) > 0:\n return release\n return None\n @cachedproperty\n def has_download_files(self):\n for series in self.context.series:\n if series.status == SeriesStatus.OBSOLETE:\n continue\n for release in series.getCachedReleases():\n if len(list(release.files)) > 0:\n return True\n return False\nclass ProductView(PillarViewMixin, HasAnnouncementsView, SortSeriesMixin,\n FeedsMixin, ProductDownloadFileMixin):\n implements(IProductActionMenu, IEditableContextTitle)\n @property\n def maintainer_widget(self):\n return InlinePersonEditPickerWidget(\n self.context, IProduct['owner'],\n format_link(self.context.owner),\n header='Change maintainer', edit_view='+edit-people',\n step_title='Select a new maintainer', show_create_team=True)\n @property\n def driver_widget(self):\n return InlinePersonEditPickerWidget(\n self.context, IProduct['driver'],\n format_link(self.context.driver, empty_value=\"Not yet selected\"),\n header='Change driver', edit_view='+edit-people',\n step_title='Select a new driver', show_create_team=True,\n null_display_value=\"Not yet selected\",\n help_link=\"/+help-registry/driver.html\")\n def __init__(self, context, request):\n HasAnnouncementsView.__init__(self, context, request)\n self.form = request.form_ng\n def initialize(self):\n super(ProductView, self).initialize()\n self.status_message = None\n product = self.context\n title_field = IProduct['title']\n title = \"Edit this title\"\n self.title_edit_widget = TextLineEditorWidget(\n product, title_field, title, 'h1', max_width='95%',\n truncate_lines=2)\n programming_lang = IProduct['programminglang']\n title = 'Edit programming languages'\n additional_arguments = {\n 'width': '9em',\n 'css_class': 'nowrap'}\n if self.context.programminglang is None:\n additional_arguments.update(dict(\n default_text='Not yet specified',\n initial_value_override='',\n ))\n self.languages_edit_widget = TextLineEditorWidget(\n product, programming_lang, title, 'span', **additional_arguments)\n self.show_programming_languages = bool(\n self.context.programminglang or\n check_permission('launchpad.Edit', self.context))\n expose_structural_subscription_data_to_js(\n self.context, self.request, self.user)\n @property\n def page_title(self):\n return '%s in Launchpad' % self.context.displayname\n @property\n def page_description(self):\n return '\\n'.filter(\n None,\n [self.context.summary, self.context.description])\n @property\n def show_license_status(self):\n return self.context.license_status != LicenseStatus.OPEN_SOURCE\n @property\n def freshmeat_url(self):\n if self.context.freshmeatproject:\n return (\"http://freshmeat.net/projects/%s\"\n % self.context.freshmeatproject)\n return None\n @property\n def sourceforge_url(self):\n if self.context.sourceforgeproject:\n return (\"http://sourceforge.net/projects/%s\"\n % self.context.sourceforgeproject)\n return None\n @property\n def has_external_links(self):\n return (self.context.homepageurl or\n self.context.sourceforgeproject or\n self.context.freshmeatproject or\n self.context.wikiurl or\n self.context.screenshotsurl or\n self.context.downloadurl)\n @property\n def external_links(self):\n \"\"\"The project's external links.\n The home page link is not included because its link must have the\n rel=nofollow attribute.\n \"\"\"\n from lp.services.webapp.menu import MenuLink\n urls = [\n ('Sourceforge project', self.sourceforge_url),\n ('Freshmeat record', self.freshmeat_url),\n ('Wiki', self.context.wikiurl),\n ('Screenshots', self.context.screenshotsurl),\n ('External downloads', self.context.downloadurl),\n ]\n links = []\n for (text, url) in urls:\n if url is not None:\n menu_link = MenuLink(\n Link(url, text, icon='external-link', enabled=True))\n menu_link.url = url\n links.append(menu_link)\n return links\n @property\n def should_display_homepage(self):\n return (self.context.homepageurl and\n self.context.homepageurl not in\n [self.freshmeat_url, self.sourceforge_url])\n def requestCountry(self):\n return ICountry(self.request, None)\n def browserLanguages(self):\n return browser_languages(self.request)\n def getClosedBugsURL(self, series):\n status = [status.title for status in RESOLVED_BUGTASK_STATUSES]\n url = canonical_url(series) + '/+bugs'\n return get_buglisting_search_filter_url(url, status=status)\n @property\n def can_purchase_subscription(self):\n return (check_permission('launchpad.Edit', self.context)\n and not self.context.qualifies_for_free_hosting)\n @cachedproperty\n def effective_driver(self):\n \"\"\"Return the product driver or the project driver.\"\"\"\n if self.context.driver is not None:\n driver = self.context.driver\n elif (self.context.project is not None and\n self.context.project.driver is not None):\n driver = self.context.project.driver\n else:\n driver = None\n return driver\n @cachedproperty\n def show_commercial_subscription_info(self):\n \"\"\"Should subscription information be shown?\n Subscription information is only shown to the project maintainers,\n Launchpad admins, and members of the Launchpad commercial team. The\n first two are allowed via the Launchpad.Edit permission. The latter\n is allowed via Launchpad.Commercial.\n \"\"\"\n return (check_permission('launchpad.Edit', self.context) or\n check_permission('launchpad.Commercial', self.context))\n @cachedproperty\n def show_license_info(self):\n \"\"\"Should the view show the extra licence information.\"\"\"\n return (\n License.OTHER_OPEN_SOURCE in self.context.licenses\n or License.OTHER_PROPRIETARY in self.context.licenses)\n @cachedproperty\n def is_proprietary(self):\n \"\"\"Is the project proprietary.\"\"\"\n return License.OTHER_PROPRIETARY in self.context.licenses\n @property\n def active_widget(self):\n return BooleanChoiceWidget(\n self.context, IProduct['active'],\n content_box_id='%s-edit-active' % FormattersAPI(\n self.context.name).css_id(),\n edit_view='+review-license',\n tag='span',\n false_text='Deactivated',\n true_text='Active',\n header='Is this project active and usable by the community?')\n @property\n def project_reviewed_widget(self):\n return BooleanChoiceWidget(\n self.context, IProduct['project_reviewed'],\n content_box_id='%s-edit-project-reviewed' % FormattersAPI(\n self.context.name).css_id(),\n edit_view='+review-license',\n tag='span',\n false_text='Unreviewed',\n true_text='Reviewed',\n header='Have you reviewed the project?')\n @property\n def license_approved_widget(self):\n licenses = list(self.context.licenses)\n if License.OTHER_PROPRIETARY in licenses:\n return 'Commercial subscription required'\n elif [License.DONT_KNOW] == licenses or [] == licenses:\n return 'Licence required'\n return BooleanChoiceWidget(\n self.context, IProduct['license_approved'],\n content_box_id='%s-edit-license-approved' % FormattersAPI(\n self.context.name).css_id(),\n edit_view='+review-license',\n tag='span',\n false_text='Unapproved',\n true_text='Approved',\n header='Does the licence qualifiy the project for free hosting?')\nclass ProductPurchaseSubscriptionView(ProductView):\n \"\"\"View the instructions to purchase a commercial subscription.\"\"\"\n page_title = 'Purchase subscription'\nclass ProductPackagesView(LaunchpadView):\n \"\"\"View for displaying product packaging\"\"\"\n label = 'Linked packages'\n page_title = label\n @cachedproperty\n def series_batch(self):\n \"\"\"A batch of series that are active or have packages.\"\"\"\n decorated_series = DecoratedResultSet(\n self.context.active_or_packaged_series, DecoratedSeries)\n return BatchNavigator(decorated_series, self.request)\n @property\n def distro_packaging(self):\n \"\"\"This method returns a representation of the product packagings\n for this product, in a special structure used for the\n product-distros.pt page template.\n Specifically, it is a list of \"distro\" objects, each of which has a\n title, and an attribute \"packagings\" which is a list of the relevant\n packagings for this distro and product.\n \"\"\"\n distros = {}\n for packaging in self.context.packagings:\n distribution = packaging.distroseries.distribution\n if distribution.name in distros:\n distro = distros[distribution.name]\n else:\n # Create a dictionary for the distribution.\n distro = dict(\n distribution=distribution,\n packagings=[])\n distros[distribution.name] = distro\n distro['packagings'].append(packaging)\n # Now we sort the resulting list of \"distro\" objects, and return that.\n distro_names = distros.keys()\n distro_names.sort(cmp=_cmp_distros)\n results = [distros[name] for name in distro_names]\n return results\nclass ProductPackagesPortletView(LaunchpadView):\n \"\"\"View class for product packaging portlet.\"\"\"\n schema = Interface\n @cachedproperty\n def sourcepackages(self):\n \"\"\"The project's latest source packages.\"\"\"\n current_packages = [\n sp for sp in self.context.sourcepackages\n if sp.currentrelease is not None]\n current_packages.reverse()\n return current_packages[0:5]\n @cachedproperty\n def can_show_portlet(self):\n \"\"\"Are there packages, or can packages be suggested.\"\"\"\n if len(self.sourcepackages) > 0:\n return True\nclass SeriesReleasePair:\n \"\"\"Class for holding a series and release.\n Replaces the use of a (series, release) tuple so that it can be more\n clearly addressed in the view class.\n \"\"\"\n def __init__(self, series, release):\n self.series = series\n self.release = release\nclass ProductDownloadFilesView(LaunchpadView,\n SortSeriesMixin,\n ProductDownloadFileMixin):\n \"\"\"View class for the product's file downloads page.\"\"\"\n batch_size = config.launchpad.download_batch_size\n @property\n def page_title(self):\n return \"%s project files\" % self.context.displayname\n def initialize(self):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n self.form = self.request.form\n # Manually process action for the 'Delete' button.\n self.processDeleteFiles()\n def getReleases(self):\n \"\"\"See `ProductDownloadFileMixin`.\"\"\"\n releases = set()\n for series in self.product.series:\n releases.update(series.releases)\n return releases\n @cachedproperty\n def series_and_releases_batch(self):\n \"\"\"Get a batch of series and release\n Each entry returned is a tuple of (series, release).\n \"\"\"\n series_and_releases = []\n for series in self.sorted_series_list:\n for release in series.releases:\n if len(release.files) > 0:\n pair = SeriesReleasePair(series, release)\n if pair not in series_and_releases:\n series_and_releases.append(pair)\n batch = BatchNavigator(series_and_releases, self.request,\n size=self.batch_size)\n batch.setHeadings(\"release\", \"releases\")\n return batch\n @cachedproperty\n def has_download_files(self):\n \"\"\"Across series and releases do any download files exist?\"\"\"\n for series in self.product.series:\n if series.has_release_files:\n return True\n return False\n @cachedproperty\n def any_download_files_with_signatures(self):\n \"\"\"Do any series or release download files have signatures?\"\"\"\n for series in self.product.series:\n for release in series.releases:\n for file in release.files:\n if file.signature:\n return True\n return False\n @cachedproperty\n def milestones(self):\n \"\"\"A mapping between series and releases that are milestones.\"\"\"\n result = dict()\n for series in self.product.series:\n result[series.name] = set()\n milestone_list = [m.name for m in series.milestones]\n for release in series.releases:\n if release.version in milestone_list:\n result[series.name].add(release.version)\n return result\n def is_milestone(self, series, release):\n \"\"\"Determine whether a release is milestone for the series.\"\"\"\n return (series.name in self.milestones and\n release.version in self.milestones[series.name])\nclass ProductBrandingView(BrandingChangeView):\n \"\"\"A view to set branding.\"\"\"\n implements(IProductEditMenu)\n label = \"Change branding\"\n schema = IProduct\n field_names = ['icon', 'logo', 'mugshot']\n @property\n def page_title(self):\n \"\"\"The HTML page title.\"\"\"\n return \"Change %s's branding\" % self.context.title\n @property\n def cancel_url(self):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n return canonical_url(self.context)\nclass ProductConfigureBase(ReturnToReferrerMixin, LaunchpadEditFormView):\n implements(IProductEditMenu)\n schema = IProduct\n usage_fieldname = None\n def setUpFields(self):\n super(ProductConfigureBase, self).setUpFields()\n if self.usage_fieldname is not None:\n # The usage fields are shared among pillars. But when referring\n # to an individual object in Launchpad it is better to call it by\n # its real name, i.e. 'project' instead of 'pillar'.\n usage_field = self.form_fields.get(self.usage_fieldname)\n if usage_field:\n usage_field.custom_widget = CustomWidgetFactory(\n LaunchpadRadioWidget, orientation='vertical')\n # Copy the field or else the description in the interface will\n # be modified in-place.\n field = copy_field(usage_field.field)\n field.description = (\n field.description.replace('pillar', 'project'))\n usage_field.field = field\n if (self.usage_fieldname in\n ('answers_usage', 'translations_usage') and\n self.context.information_type in\n PROPRIETARY_INFORMATION_TYPES):\n values = usage_field.field.vocabulary.items\n terms = [SimpleTerm(value, value.name, value.title)\n for value in values\n if value != ServiceUsage.LAUNCHPAD]\n usage_field.field.vocabulary = SimpleVocabulary(terms)\n @property\n def field_names(self):\n return [self.usage_fieldname]\n @property\n def page_title(self):\n return self.label\n @action(\"Change\", name='change')\n def change_action(self, action, data):\n self.updateContextFromData(data)\nclass ProductConfigureBlueprintsView(ProductConfigureBase):\n \"\"\"View class to configure the Launchpad Blueprints for a project.\"\"\"\n label = \"Configure blueprints\"\n usage_fieldname = 'blueprints_usage'\nclass ProductConfigureAnswersView(ProductConfigureBase):\n \"\"\"View class to configure the Launchpad Answers for a project.\"\"\"\n label = \"Configure answers\"\n usage_fieldname = 'answers_usage'\nclass ProductEditView(ProductLicenseMixin, LaunchpadEditFormView):\n \"\"\"View class that lets you edit a Product object.\"\"\"\n implements(IProductEditMenu)\n label = \"Edit details\"\n schema = IProduct\n field_names = [\n \"displayname\",\n \"title\",\n \"summary\",\n \"description\",\n \"project\",\n \"homepageurl\",\n \"information_type\",\n \"sourceforgeproject\",\n \"freshmeatproject\",\n \"wikiurl\",\n \"screenshotsurl\",\n \"downloadurl\",\n \"programminglang\",\n \"development_focus\",\n \"licenses\",\n \"license_info\",\n ]\n custom_widget('licenses', LicenseWidget)\n custom_widget('license_info', GhostWidget)\n custom_widget(\n 'information_type', LaunchpadRadioWidgetWithDescription,\n vocabulary=InformationTypeVocabulary(\n types=PUBLIC_PROPRIETARY_INFORMATION_TYPES))\n @property\n def next_url(self):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n if self.context.active:\n if len(self.errors) > 0:\n return None\n return canonical_url(self.context)\n else:\n return canonical_url(getUtility(IProductSet))\n cancel_url = next_url\n @property\n def page_title(self):\n \"\"\"The HTML page title.\"\"\"\n return \"Change %s's details\" % self.context.title\n def initialize(self):\n # The JSON cache must be populated before the super call, since\n # the form is rendered during LaunchpadFormView's initialize()\n # when an action is invoked.\n cache = IJSONRequestCache(self.request)\n json_dump_information_types(\n cache, PUBLIC_PROPRIETARY_INFORMATION_TYPES)\n super(ProductEditView, self).initialize()\n def validate(self, data):\n \"\"\"Validate 'licenses' and 'license_info'.\n 'licenses' must not be empty unless the product already\n exists and never has had a licence set.\n 'license_info' must not be empty if \"Other/Proprietary\"\n or \"Other/Open Source\" is checked.\n \"\"\"\n super(ProductEditView, self).validate(data)\n information_type = data.get('information_type')\n if information_type:\n errors = [\n str(e) for e in self.context.checkInformationType(\n information_type)]\n if len(errors) > 0:\n self.setFieldError('information_type', ' '.join(errors))\n def showOptionalMarker(self, field_name):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n # This has the effect of suppressing the \": (Optional)\" stuff for the\n # license_info widget. It's the last piece of the puzzle for\n # manipulating the license_info widget into the table for the\n # LicenseWidget instead of the enclosing form.\n if field_name == 'license_info':\n return False\n return super(ProductEditView, self).showOptionalMarker(field_name)\n @action(\"Change\", name='change')\n def change_action(self, action, data):\n self.updateContextFromData(data)\nclass ProductValidationMixin:\n def validate_deactivation(self, data):\n \"\"\"Verify whether a product can be safely deactivated.\"\"\"\n if data['active'] == False and self.context.active == True:\n if len(self.context.sourcepackages) > 0:\n self.setFieldError('active',\n structured(\n 'This project cannot be deactivated since it is '\n 'linked to one or more '\n 'source packages.',\n canonical_url(self.context, view_name='+packages')))\nclass ProductAdminView(ProductEditView, ProductValidationMixin):\n \"\"\"View for $project/+admin\"\"\"\n label = \"Administer project details\"\n default_field_names = [\n \"name\",\n \"owner\",\n \"active\",\n \"autoupdate\",\n ]\n @property\n def page_title(self):\n \"\"\"The HTML page title.\"\"\"\n return 'Administer %s' % self.context.title\n def setUpFields(self):\n \"\"\"Setup the normal fields from the schema plus adds 'Registrant'.\n The registrant is normally a read-only field and thus does not have a\n proper widget created by default. Even though it is read-only, admins\n need the ability to change it.\n \"\"\"\n self.field_names = self.default_field_names[:]\n admin = check_permission('launchpad.Admin', self.context)\n if not admin:\n self.field_names.remove('owner')\n self.field_names.remove('autoupdate')\n super(ProductAdminView, self).setUpFields()\n self.form_fields = self._createAliasesField() + self.form_fields\n if admin:\n self.form_fields = (\n self.form_fields + self._createRegistrantField())\n def _createAliasesField(self):\n \"\"\"Return a PillarAliases field for IProduct.aliases.\"\"\"\n return form.Fields(\n PillarAliases(\n __name__='aliases', title=_('Aliases'),\n description=_('Other names (separated by space) under which '\n 'this project is known.'),\n required=False, readonly=False),\n render_context=self.render_context)\n def _createRegistrantField(self):\n \"\"\"Return a popup widget person selector for the registrant.\n This custom field is necessary because *normally* the registrant is\n read-only but we want the admins to have the ability to correct legacy\n data that was set before the registrant field existed.\n \"\"\"\n return form.Fields(\n PublicPersonChoice(\n __name__='registrant',\n title=_('Project Registrant'),\n description=_('The person who originally registered the '\n 'product. Distinct from the current '\n 'owner. This is historical data and should '\n 'not be changed without good cause.'),\n vocabulary='ValidPersonOrTeam',\n required=True,\n readonly=False,\n ),\n render_context=self.render_context\n )\n def validate(self, data):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n super(ProductAdminView, self).validate(data)\n self.validate_deactivation(data)\n @property\n def cancel_url(self):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n return canonical_url(self.context)\nclass ProductReviewLicenseView(ReturnToReferrerMixin, ProductEditView,\n ProductValidationMixin):\n \"\"\"A view to review a project and change project privileges.\"\"\"\n label = \"Review project\"\n field_names = [\n \"project_reviewed\",\n \"license_approved\",\n \"active\",\n \"reviewer_whiteboard\",\n ]\n @property\n def page_title(self):\n \"\"\"The HTML page title.\"\"\"\n return 'Review %s' % self.context.title\n def validate(self, data):\n \"\"\"See `LaunchpadFormView`.\"\"\"\n super(ProductReviewLicenseView, self).validate(data)\n # A project can only be approved if it has OTHER_OPEN_SOURCE as one of\n # its licenses and not OTHER_PROPRIETARY.\n licenses = self.context.licenses\n license_approved = data.get('license_approved', False)\n if license_approved:\n if License.OTHER_PROPRIETARY in licenses:\n self.setFieldError(\n 'license_approved',\n 'Proprietary projects may not be manually '\n 'approved to use Launchpad. Proprietary projects '\n 'must use the commercial subscription voucher system '\n 'to be allowed to use Launchpad.')\n else:\n # An Other/Open Source licence was specified so it may be\n # approved.\n pass\n self.validate_deactivation(data)\nclass ProductAddSeriesView(LaunchpadFormView):\n \"\"\"A form to add new product series\"\"\"\n schema = IProductSeries\n", "answers": [" field_names = ['name', 'summary', 'branch', 'releasefileglob']"], "length": 4413, "dataset": "lcc", "language": "python", "all_classes": null, "_id": "c87c42b130a11ba81e64078e5be1ddb51be6aa08d42fa60d"}
{"input": "", "context": "using System;\nusing Server.Items;\nusing Server.Spells;\nnamespace Server.Engines.Craft\n{\n public class DefInscription : CraftSystem\n {\n public override SkillName MainSkill\n {\n get\n {\n return SkillName.Inscribe;\n }\n }\n public override int GumpTitleNumber\n {\n get\n {\n return 1044009;\n }// INSCRIPTION MENU\n }\n private static CraftSystem m_CraftSystem;\n public static CraftSystem CraftSystem\n {\n get\n {\n if (m_CraftSystem == null)\n m_CraftSystem = new DefInscription();\n return m_CraftSystem;\n }\n }\n public override double GetChanceAtMin(CraftItem item)\n {\n return 0.0; // 0%\n }\n private DefInscription()\n : base(1, 1, 1.25)// base( 1, 1, 3.0 )\n {\n }\n public override int CanCraft(Mobile from, BaseTool tool, Type typeItem)\n {\n if (tool == null || tool.Deleted || tool.UsesRemaining < 0)\n return 1044038; // You have worn out your tool!\n else if (!BaseTool.CheckAccessible(tool, from))\n return 1044263; // The tool must be on your person to use.\n if (typeItem != null)\n {\n object o = Activator.CreateInstance(typeItem);\n if (o is SpellScroll)\n {\n SpellScroll scroll = (SpellScroll)o;\n Spellbook book = Spellbook.Find(from, scroll.SpellID);\n bool hasSpell = (book != null && book.HasSpell(scroll.SpellID));\n scroll.Delete();\n return (hasSpell ? 0 : 1042404); // null : You don't have that spell!\n }\n else if (o is Item)\n {\n ((Item)o).Delete();\n }\n }\n return 0;\n }\n public override void PlayCraftEffect(Mobile from)\n {\n from.PlaySound(0x249);\n }\n private static readonly Type typeofSpellScroll = typeof(SpellScroll);\n public override int PlayEndingEffect(Mobile from, bool failed, bool lostMaterial, bool toolBroken, int quality, bool makersMark, CraftItem item)\n {\n if (toolBroken)\n from.SendLocalizedMessage(1044038); // You have worn out your tool\n if (!typeofSpellScroll.IsAssignableFrom(item.ItemType)) // not a scroll\n {\n if (failed)\n {\n if (lostMaterial)\n return 1044043; // You failed to create the item, and some of your materials are lost.\n else\n return 1044157; // You failed to create the item, but no materials were lost.\n }\n else\n {\n if (quality == 0)\n return 502785; // You were barely able to make this item. It's quality is below average.\n else if (makersMark && quality == 2)\n return 1044156; // You create an exceptional quality item and affix your maker's mark.\n else if (quality == 2)\n return 1044155; // You create an exceptional quality item.\n else\n return 1044154; // You create the item.\n }\n }\n else\n {\n if (failed)\n return 501630; // You fail to inscribe the scroll, and the scroll is ruined.\n else\n return 501629; // You inscribe the spell and put the scroll in your backpack.\n }\n }\n private int m_Circle, m_Mana;\n private enum Reg { BlackPearl, Bloodmoss, Garlic, Ginseng, MandrakeRoot, Nightshade, SulfurousAsh, SpidersSilk, BatWing, GraveDust, DaemonBlood, NoxCrystal, PigIron, Bone, DragonBlood, FertileDirt, DaemonBone }\n private readonly Type[] m_RegTypes = new Type[]\n {\n typeof( BlackPearl ),\n\t\t\ttypeof( Bloodmoss ),\n\t\t\ttypeof( Garlic ),\n\t\t\ttypeof( Ginseng ),\n\t\t\ttypeof( MandrakeRoot ),\n\t\t\ttypeof( Nightshade ),\n\t\t\ttypeof( SulfurousAsh ),\t\n\t\t\ttypeof( SpidersSilk ),\n typeof( BatWing ),\n typeof( GraveDust ),\n typeof( DaemonBlood ),\n typeof( NoxCrystal ),\n typeof( PigIron ),\n\t\t\ttypeof( Bone ),\n\t\t\ttypeof( DragonBlood ),\n\t\t\ttypeof( FertileDirt ),\n\t\t\ttypeof( DaemonBone )\t\t\t\n };\n private int m_Index;\n private void AddSpell(Type type, params Reg[] regs)\n {\n double minSkill, maxSkill;\n int cliloc;\n switch (m_Circle)\n {\n default:\n case 0: minSkill = -25.0; maxSkill = 25.0; cliloc = 1111691; break;\n case 1: minSkill = -10.8; maxSkill = 39.2; cliloc = 1111691; break;\n case 2: minSkill = 03.5; maxSkill = 53.5; cliloc = 1111692; break;\n case 3: minSkill = 17.8; maxSkill = 67.8; cliloc = 1111692; break;\n case 4: minSkill = 32.1; maxSkill = 82.1; cliloc = 1111693; break;\n case 5: minSkill = 46.4; maxSkill = 96.4; cliloc = 1111693; break;\n case 6: minSkill = 60.7; maxSkill = 110.7; cliloc = 1111694; break;\n case 7: minSkill = 75.0; maxSkill = 125.0; cliloc = 1111694; break;\n }\n int index = AddCraft(type, cliloc, 1044381 + m_Index++, minSkill, maxSkill, m_RegTypes[(int)regs[0]], 1044353 + (int)regs[0], 1, 1044361 + (int)regs[0]);\n for (int i = 1; i < regs.Length; ++i)\n AddRes(index, m_RegTypes[(int)regs[i]], 1044353 + (int)regs[i], 1, 1044361 + (int)regs[i]);\n AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);\n SetManaReq(index, m_Mana);\n }\n private void AddNecroSpell(int spell, int mana, double minSkill, Type type, params Reg[] regs)\n {\n int id = GetRegLocalization(regs[0]);\n int index = AddCraft(type, 1061677, 1060509 + spell, minSkill, minSkill + 1.0, m_RegTypes[(int)regs[0]], id, 1, 501627);\n for (int i = 1; i < regs.Length; ++i)\n {\n id = GetRegLocalization(regs[i]);\n AddRes(index, m_RegTypes[(int)regs[0]], id, 1, 501627);\n }\n AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);\n SetManaReq(index, mana);\n }\n private void AddMysticSpell(int id, int mana, double minSkill, Type type, params Reg[] regs)\n {\n int index = AddCraft(type, 1111671, id, minSkill, minSkill + 1.0, m_RegTypes[(int)regs[0]], GetRegLocalization(regs[0]), 1, 501627);\t//Yes, on OSI it's only 1.0 skill diff'. Don't blame me, blame OSI.\n for (int i = 1; i < regs.Length; ++i)\n AddRes(index, m_RegTypes[(int)regs[0]], GetRegLocalization(regs[i]), 1, 501627);\n AddRes(index, typeof(BlankScroll), 1044377, 1, 1044378);\n SetManaReq(index, mana);\n }\n private int GetRegLocalization(Reg reg)\n {\n int loc = 0;\n switch (reg)\n {\n case Reg.BatWing: loc = 1023960; break;\n case Reg.GraveDust: loc = 1023983; break;\n case Reg.DaemonBlood: loc = 1023965; break;\n case Reg.NoxCrystal: loc = 1023982; break;\n case Reg.PigIron: loc = 1023978; break;\n case Reg.Bone: loc = 1023966; break;\n case Reg.DragonBlood: loc = 1023970; break;\n case Reg.FertileDirt: loc = 1023969; break;\n case Reg.DaemonBone: loc = 1023968; break;\n }\n if (loc == 0)\n loc = 1044353 + (int)reg;\n return loc;\n }\n public override void InitCraftList()\n {\n m_Circle = 0;\n\t\t\tm_Mana = 4;\n\t\t\tAddSpell( typeof( ReactiveArmorScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ClumsyScroll ), Reg.Bloodmoss, Reg.Nightshade );\n\t\t\tAddSpell( typeof( CreateFoodScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( FeeblemindScroll ), Reg.Nightshade, Reg.Ginseng );\n\t\t\tAddSpell( typeof( HealScroll ), Reg.Garlic, Reg.Ginseng, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( MagicArrowScroll ), Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( NightSightScroll ), Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( WeakenScroll ), Reg.Garlic, Reg.Nightshade );\n\t\t\tm_Circle = 1;\n\t\t\tm_Mana = 6;\n\t\t\tAddSpell( typeof( AgilityScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( CunningScroll ), Reg.Nightshade, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( CureScroll ), Reg.Garlic, Reg.Ginseng );\n\t\t\tAddSpell( typeof( HarmScroll ), Reg.Nightshade, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( MagicTrapScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( MagicUnTrapScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ProtectionScroll ), Reg.Garlic, Reg.Ginseng, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( StrengthScroll ), Reg.Nightshade, Reg.MandrakeRoot );\n\t\t\tm_Circle = 2;\n\t\t\tm_Mana = 9;\n\t\t\tAddSpell( typeof( BlessScroll ), Reg.Garlic, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( FireballScroll ), Reg.BlackPearl );\n\t\t\tAddSpell( typeof( MagicLockScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( PoisonScroll ), Reg.Nightshade );\n\t\t\tAddSpell( typeof( TelekinisisScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( TeleportScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( UnlockScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( WallOfStoneScroll ), Reg.Bloodmoss, Reg.Garlic );\n\t\t\tm_Circle = 3;\n\t\t\tm_Mana = 11;\n\t\t\tAddSpell( typeof( ArchCureScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( ArchProtectionScroll ), Reg.Garlic, Reg.Ginseng, Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( CurseScroll ), Reg.Garlic, Reg.Nightshade, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( FireFieldScroll ), Reg.BlackPearl, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( GreaterHealScroll ), Reg.Garlic, Reg.SpidersSilk, Reg.MandrakeRoot, Reg.Ginseng );\n\t\t\tAddSpell( typeof( LightningScroll ), Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ManaDrainScroll ), Reg.BlackPearl, Reg.SpidersSilk, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( RecallScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot );\n\t\t\tm_Circle = 4;\n\t\t\tm_Mana = 14;\n\t\t\tAddSpell( typeof( BladeSpiritsScroll ), Reg.BlackPearl, Reg.Nightshade, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( DispelFieldScroll ), Reg.BlackPearl, Reg.Garlic, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( IncognitoScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.Nightshade );\n\t\t\tAddSpell( typeof( MagicReflectScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( MindBlastScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.Nightshade, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ParalyzeScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( PoisonFieldScroll ), Reg.BlackPearl, Reg.Nightshade, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( SummonCreatureScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tm_Circle = 5;\n\t\t\tm_Mana = 20;\n\t\t\tAddSpell( typeof( DispelScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( EnergyBoltScroll ), Reg.BlackPearl, Reg.Nightshade );\n\t\t\tAddSpell( typeof( ExplosionScroll ), Reg.Bloodmoss, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( InvisibilityScroll ), Reg.Bloodmoss, Reg.Nightshade );\n\t\t\tAddSpell( typeof( MarkScroll ), Reg.Bloodmoss, Reg.BlackPearl, Reg.MandrakeRoot );\n\t\t\tAddSpell( typeof( MassCurseScroll ), Reg.Garlic, Reg.MandrakeRoot, Reg.Nightshade, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ParalyzeFieldScroll ), Reg.BlackPearl, Reg.Ginseng, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( RevealScroll ), Reg.Bloodmoss, Reg.SulfurousAsh );\n\t\t\tm_Circle = 6;\n\t\t\tm_Mana = 40;\n\t\t\tAddSpell( typeof( ChainLightningScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( EnergyFieldScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( FlamestrikeScroll ), Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( GateTravelScroll ), Reg.BlackPearl, Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( ManaVampireScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( MassDispelScroll ), Reg.BlackPearl, Reg.Garlic, Reg.MandrakeRoot, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( MeteorSwarmScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SulfurousAsh, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( PolymorphScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tm_Circle = 7;\n\t\t\tm_Mana = 50;\n\t\t\tAddSpell( typeof( EarthquakeScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.Ginseng, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( EnergyVortexScroll ), Reg.BlackPearl, Reg.Bloodmoss, Reg.MandrakeRoot, Reg.Nightshade );\n\t\t\tAddSpell( typeof( ResurrectionScroll ), Reg.Bloodmoss, Reg.Garlic, Reg.Ginseng );\n\t\t\tAddSpell( typeof( SummonAirElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( SummonDaemonScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( SummonEarthElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tAddSpell( typeof( SummonFireElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk, Reg.SulfurousAsh );\n\t\t\tAddSpell( typeof( SummonWaterElementalScroll ), Reg.Bloodmoss, Reg.MandrakeRoot, Reg.SpidersSilk );\n\t\t\tif ( Core.SE )\n\t\t\t{\n\t\t\t\tAddNecroSpell( 0, 23, 39.6, typeof( AnimateDeadScroll ), Reg.GraveDust, Reg.DaemonBlood );\n\t\t\t\tAddNecroSpell( 1, 13, 19.6, typeof( BloodOathScroll ), Reg.DaemonBlood );\n\t\t\t\tAddNecroSpell( 2, 11, 19.6, typeof( CorpseSkinScroll ), Reg.BatWing, Reg.GraveDust );\n\t\t\t\tAddNecroSpell( 3, 7, 19.6, typeof( CurseWeaponScroll ), Reg.PigIron );\n\t\t\t\tAddNecroSpell( 4, 11, 19.6, typeof( EvilOmenScroll ), Reg.BatWing, Reg.NoxCrystal );\n\t\t\t\tAddNecroSpell( 5, 11, 39.6, typeof( HorrificBeastScroll ), Reg.BatWing, Reg.DaemonBlood );\n\t\t\t\tAddNecroSpell( 6, 23, 69.6, typeof( LichFormScroll ), Reg.GraveDust, Reg.DaemonBlood, Reg.NoxCrystal );\n\t\t\t\tAddNecroSpell( 7, 17, 29.6, typeof( MindRotScroll ), Reg.BatWing, Reg.DaemonBlood, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 8, 5, 19.6, typeof( PainSpikeScroll ), Reg.GraveDust, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 9, 17, 49.6, typeof( PoisonStrikeScroll ), Reg.NoxCrystal );\n\t\t\t\tAddNecroSpell( 10, 29, 64.6, typeof( StrangleScroll ), Reg.DaemonBlood, Reg.NoxCrystal );\n\t\t\t\tAddNecroSpell( 11, 17, 29.6, typeof( SummonFamiliarScroll ), Reg.BatWing, Reg.GraveDust, Reg.DaemonBlood );\n\t\t\t\tAddNecroSpell( 12, 23, 98.6, typeof( VampiricEmbraceScroll ), Reg.BatWing, Reg.NoxCrystal, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 13, 41, 79.6, typeof( VengefulSpiritScroll ), Reg.BatWing, Reg.GraveDust, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 14, 23, 59.6, typeof( WitherScroll ), Reg.GraveDust, Reg.NoxCrystal, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 15, 17, 79.6, typeof( WraithFormScroll ), Reg.NoxCrystal, Reg.PigIron );\n\t\t\t\tAddNecroSpell( 16, 40, 79.6, typeof( ExorcismScroll ), Reg.NoxCrystal, Reg.GraveDust );\n\t\t\t}\n int index;\n\t\t\t\n if (Core.ML)\n {\n index = this.AddCraft(typeof(EnchantedSwitch), 1044294, 1072893, 45.0, 95.0, typeof(BlankScroll), 1044377, 1, 1044378);\n this.AddRes(index, typeof(SpidersSilk), 1044360, 1, 1044253);\n this.AddRes(index, typeof(BlackPearl), 1044353, 1, 1044253);\n this.AddRes(index, typeof(SwitchItem), 1073464, 1, 1044253);\n this.ForceNonExceptional(index);\n this.SetNeededExpansion(index, Expansion.ML);\n\t\t\t\t\n index = this.AddCraft(typeof(RunedPrism), 1044294, 1073465, 45.0, 95.0, typeof(BlankScroll), 1044377, 1, 1044378);\n this.AddRes(index, typeof(SpidersSilk), 1044360, 1, 1044253);\n", "answers": [" this.AddRes(index, typeof(BlackPearl), 1044353, 1, 1044253);"], "length": 1615, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "faf59e122b5cf0c3acab0447bcd6a53f208c972065c8414a"}
{"input": "", "context": "/*\nCopyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved.\nContact:\n SYSTAP, LLC DBA Blazegraph\n 2501 Calvert ST NW #106\n Washington, DC 20008\n licenses@blazegraph.com\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; version 2 of the License.\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*/\n/*\n * Created on Nov 14, 2008\n */\npackage com.bigdata.rdf.store;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.Properties;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.FutureTask;\nimport org.apache.log4j.Logger;\nimport org.openrdf.model.Statement;\nimport com.bigdata.journal.Journal;\nimport com.bigdata.journal.TimestampUtility;\nimport com.bigdata.rdf.axioms.Axioms;\nimport com.bigdata.rdf.axioms.NoAxioms;\nimport com.bigdata.rdf.internal.IV;\nimport com.bigdata.rdf.model.BigdataStatement;\nimport com.bigdata.rdf.rio.AbstractStatementBuffer.StatementBuffer2;\nimport com.bigdata.rdf.rio.StatementBuffer;\nimport com.bigdata.rdf.rules.BackchainAccessPath;\nimport com.bigdata.rdf.spo.ISPO;\nimport com.bigdata.rdf.spo.SPO;\nimport com.bigdata.rdf.store.AbstractTripleStore.Options;\nimport com.bigdata.relation.accesspath.BlockingBuffer;\nimport com.bigdata.relation.accesspath.IAccessPath;\nimport com.bigdata.striterator.IChunkedOrderedIterator;\nimport cutthecrap.utils.striterators.ICloseableIterator;\n/**\n * Utility class for comparing graphs for equality, bulk export, etc.\n * \n * @author Bryan Thompson\n * @version $Id$\n */\npublic class TripleStoreUtility {\n \n protected static final Logger log = Logger.getLogger(TripleStoreUtility.class);\n /**\n * Compares two RDF graphs for equality (same statements).\n * \n * Note: This does NOT handle bnodes, which much be treated as variables for\n * RDF semantics.\n *
\n * Note: Comparison is performed in terms of the externalized RDF\n * {@link Statement}s rather than {@link SPO}s since different graphs use\n * different lexicons.\n *
\n * Note: If the graphs differ in which entailments they are storing in their\n * data and which entailments are backchained then you MUST make them\n * consistent in this regard. You can do this by exporting one or both using\n * {@link #bulkExport(AbstractTripleStore)}, which will cause all\n * entailments to be materialized in the returned {@link TempTripleStore}.\n * \n * @param expected\n * One graph.\n * \n * @param actual\n * Another graph with a consistent policy for forward and\n * backchained entailments.\n * \n * @return true if all statements in the expected graph are in the actual\n * graph and if the actual graph does not contain any statements\n * that are not also in the expected graph.\n */\n public static boolean modelsEqual(AbstractTripleStore expected,\n AbstractTripleStore actual) throws Exception {\n // int actualSize = 0;\n int notExpecting = 0;\n int expecting = 0;\n boolean sameStatements1 = true;\n {\n final ICloseableIterator it = notFoundInTarget(actual, expected);\n try {\n while (it.hasNext()) {\n final BigdataStatement stmt = it.next();\n sameStatements1 = false;\n log(\"Not expecting: \" + stmt);\n notExpecting++;\n // actualSize++; // count #of statements actually visited.\n }\n } finally {\n it.close();\n }\n log(\"all the statements in actual in expected? \" + sameStatements1);\n }\n // int expectedSize = 0;\n boolean sameStatements2 = true;\n {\n final ICloseableIterator it = notFoundInTarget(expected, actual);\n try {\n while (it.hasNext()) {\n final BigdataStatement stmt = it.next();\n sameStatements2 = false;\n log(\" Expecting: \" + stmt);\n expecting++;\n // expectedSize++; // counts statements actually visited.\n }\n } finally {\n it.close();\n }\n // BigdataStatementIterator it = expected.asStatementIterator(expected\n // .getInferenceEngine().backchainIterator(\n // expected.getAccessPath(NULL, NULL, NULL)));\n //\n // try {\n //\n // while(it.hasNext()) {\n //\n // BigdataStatement stmt = it.next();\n //\n // if (!hasStatement(actual,//\n // (Resource)actual.getValueFactory().asValue(stmt.getSubject()),//\n // (URI)actual.getValueFactory().asValue(stmt.getPredicate()),//\n // (Value)actual.getValueFactory().asValue(stmt.getObject()))//\n // ) {\n //\n // sameStatements2 = false;\n //\n // log(\" Expecting: \" + stmt);\n // \n // expecting++;\n //\n // }\n // \n // expectedSize++; // counts statements actually visited.\n //\n // }\n // \n // } finally {\n // \n // it.close();\n // \n // }\n log(\"all the statements in expected in actual? \" + sameStatements2);\n }\n // final boolean sameSize = expectedSize == actualSize;\n // \n // log(\"size of 'expected' repository: \" + expectedSize);\n //\n // log(\"size of 'actual' repository: \" + actualSize);\n log(\"# expected but not found: \" + expecting);\n log(\"# not expected but found: \" + notExpecting);\n return /*sameSize &&*/sameStatements1 && sameStatements2;\n }\n public static void log(final String s) {\n \tif(log.isInfoEnabled())\n \t\tlog.info(s);\n }\n /**\n * Visits expected {@link BigdataStatement}s not found in actual.\n * \n * @param expected\n * @param actual\n * \n * @return An iterator visiting {@link BigdataStatement}s present in\n * expected but not found in actual.\n * \n * @throws ExecutionException\n * @throws InterruptedException\n */\n public static ICloseableIterator notFoundInTarget(//\n final AbstractTripleStore expected,//\n final AbstractTripleStore actual //\n ) throws InterruptedException, ExecutionException {\n /*\n * The source access path is a full scan of the SPO index.\n */\n final IAccessPath expectedAccessPath = expected.getAccessPath(\n (IV) null, (IV) null, (IV) null);\n /*\n * Efficiently convert SPOs to BigdataStatements (externalizes\n * statements).\n */\n final BigdataStatementIterator itr2 = expected\n .asStatementIterator(expectedAccessPath.iterator());\n final int capacity = 100000;\n final BlockingBuffer buffer = new BlockingBuffer(\n capacity);\n final StatementBuffer2 sb = new StatementBuffer2(\n actual, true/* readOnly */, capacity) {\n /**\n * Statements not found in [actual] are written on the\n * BlockingBuffer.\n * \n * @return The #of statements that were not found.\n */\n @Override\n protected int handleProcessedStatements(final BigdataStatement[] a) {\n if (log.isInfoEnabled())\n log.info(\"Given \" + a.length + \" statements\");\n // bulk filter for statements not present in [actual].\n final IChunkedOrderedIterator notFoundItr = actual\n .bulkFilterStatements(a, a.length, false/* present */);\n int nnotFound = 0;\n try {\n while (notFoundItr.hasNext()) {\n final ISPO notFoundStmt = notFoundItr.next();\n if (log.isInfoEnabled())\n log.info(\"Not found: \" + notFoundStmt);\n buffer.add((BigdataStatement) notFoundStmt);\n nnotFound++;\n }\n } finally {\n notFoundItr.close();\n }\n if (log.isInfoEnabled())\n log.info(\"Given \" + a.length + \" statements, \" + nnotFound\n + \" of them were not found\");\n return nnotFound;\n }\n };\n /**\n * Run task. The task consumes externalized statements from [expected]\n * and writes statements not found in [actual] onto the blocking buffer.\n */\n final Callable myTask = new Callable() {\n public Void call() throws Exception {\n try {\n while (itr2.hasNext()) {\n // a statement from the source db.\n final BigdataStatement stmt = itr2.next();\n // if (log.isInfoEnabled()) log.info(\"Source: \"\n // + stmt);\n // add to the buffer.\n sb.add(stmt);\n }\n } finally {\n itr2.close();\n }\n /*\n * Flush everything in the StatementBuffer so that it\n * shows up in the BlockingBuffer's iterator().\n */\n final long nnotFound = sb.flush();\n if (log.isInfoEnabled())\n log.info(\"Flushed: #notFound=\" + nnotFound);\n return null;\n }\n };\n /**\n * @see \n * BlockingBuffer.close() does not unblock threads \n */\n // Wrap computation as FutureTask.\n final FutureTask ft = new FutureTask(myTask);\n \n // Set Future on BlockingBuffer.\n buffer.setFuture(ft);\n \n // Submit computation for evaluation.\n actual.getExecutorService().submit(ft);\n /*\n * Return iterator reading \"not found\" statements from the blocking\n * buffer.\n */\n return buffer.iterator();\n }\n /**\n * Exports all statements found in the data and all backchained entailments\n * for the db into a {@link TempTripleStore}. This may be used to\n * compare graphs purely in their data by pre-generation of all backchained\n * entailments.\n * \n * Note: This is not a general purpose bulk export as it uses only a single\n * access path, does not store justifications, and does retain the\n * {@link Axioms} model of the source graph. This method is specifically\n * designed to export \"just the triples\", e.g., for purposes of comparison.\n * \n * @param db\n * The source database.\n * \n * @return The {@link TempTripleStore}.\n */\n static public TempTripleStore bulkExport(final AbstractTripleStore db) {\n \n final Properties properties = new Properties();\n \n properties.setProperty(Options.ONE_ACCESS_PATH, \"true\");\n \n properties.setProperty(Options.JUSTIFY, \"false\");\n \n properties.setProperty(Options.AXIOMS_CLASS,\n NoAxioms.class.getName());\n properties.setProperty(Options.STATEMENT_IDENTIFIERS,\n \"\" + db.isStatementIdentifiers());\n final TempTripleStore tmp = new TempTripleStore(properties);\n try {\n\t\t\tfinal StatementBuffer sb = new StatementBuffer(tmp, 100000/* capacity */,\n\t\t\t\t\t10/* queueCapacity */);\n final IV NULL = null;\n final IChunkedOrderedIterator itr1 = new BackchainAccessPath(\n db, db.getAccessPath(NULL, NULL, NULL)).iterator();\n final BigdataStatementIterator itr2 = db.asStatementIterator(itr1);\n try {\n while (itr2.hasNext()) {\n final BigdataStatement stmt = itr2.next();\n sb.add(stmt);\n }\n } finally {\n itr2.close();\n }\n sb.flush();\n } catch (Throwable t) {\n tmp.close();\n throw new RuntimeException(t);\n }\n \n return tmp;\n \n }\n /**\n * Compares two {@link LocalTripleStore}s\n * \n * @param args\n * filename filename (namespace)\n * \n * @throws Exception\n * \n * @todo namespace for each, could be the same file, and timestamp for each.\n * \n * @todo handle other database modes.\n */\n public static void main(String[] args) throws Exception {\n \n", "answers": [" if (args.length < 2 || args.length > 3) {"], "length": 1331, "dataset": "lcc", "language": "java", "all_classes": null, "_id": "0ab3fa6fa37f02b5f789515e8bd2a7357fa959242a06e4e3"}
{"input": "", "context": "package org.ovirt.engine.core.bll;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyList;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.spy;\nimport static org.mockito.Mockito.when;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport javax.validation.ConstraintViolation;\nimport org.junit.Test;\nimport org.mockito.Mockito;\nimport org.ovirt.engine.core.bll.context.EngineContext;\nimport org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolManagerStrategy;\nimport org.ovirt.engine.core.common.action.ImportVmTemplateParameters;\nimport org.ovirt.engine.core.common.businessentities.BusinessEntitiesDefinitions;\nimport org.ovirt.engine.core.common.businessentities.StorageDomain;\nimport org.ovirt.engine.core.common.businessentities.StorageDomainStatic;\nimport org.ovirt.engine.core.common.businessentities.StorageDomainStatus;\nimport org.ovirt.engine.core.common.businessentities.StorageDomainType;\nimport org.ovirt.engine.core.common.businessentities.StoragePool;\nimport org.ovirt.engine.core.common.businessentities.VDSGroup;\nimport org.ovirt.engine.core.common.businessentities.VmDevice;\nimport org.ovirt.engine.core.common.businessentities.VmTemplate;\nimport org.ovirt.engine.core.common.businessentities.storage.DiskImage;\nimport org.ovirt.engine.core.common.businessentities.storage.StorageType;\nimport org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;\nimport org.ovirt.engine.core.common.businessentities.storage.VolumeType;\nimport org.ovirt.engine.core.common.errors.EngineMessage;\nimport org.ovirt.engine.core.common.queries.VdcQueryParametersBase;\nimport org.ovirt.engine.core.common.queries.VdcQueryReturnValue;\nimport org.ovirt.engine.core.common.queries.VdcQueryType;\nimport org.ovirt.engine.core.common.utils.ValidationUtils;\nimport org.ovirt.engine.core.compat.Guid;\nimport org.ovirt.engine.core.dao.StorageDomainDao;\nimport org.ovirt.engine.core.dao.StorageDomainStaticDao;\nimport org.ovirt.engine.core.dao.StoragePoolDao;\nimport org.ovirt.engine.core.dao.VmTemplateDao;\nimport org.springframework.util.Assert;\npublic class ImportVmTemplateCommandTest {\n @Test\n public void insufficientDiskSpace() {\n // The following is enough since the validation is mocked out anyway. Just want to make sure the flow in CDA is correct.\n // Full test for the scenarios is done in the inherited class.\n final ImportVmTemplateCommand command = setupVolumeFormatAndTypeTest(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);\n doReturn(false).when(command).validateSpaceRequirements(anyList());\n assertFalse(command.canDoAction());\n }\n @Test\n public void validVolumeFormatAndTypeCombinations() throws Exception {\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.NFS);\n assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.NFS);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.ISCSI);\n assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.ISCSI);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.ISCSI);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.FCP);\n assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.FCP);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.FCP);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.LOCALFS);\n assertValidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Sparse, StorageType.LOCALFS);\n assertValidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Sparse, StorageType.LOCALFS);\n }\n @Test\n public void invalidVolumeFormatAndTypeCombinations() throws Exception {\n assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.NFS);\n assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.ISCSI);\n assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.FCP);\n assertInvalidVolumeInfoCombination(VolumeFormat.COW, VolumeType.Preallocated, StorageType.LOCALFS);\n assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.NFS);\n assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.ISCSI);\n assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.FCP);\n assertInvalidVolumeInfoCombination(VolumeFormat.RAW, VolumeType.Unassigned, StorageType.LOCALFS);\n assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.NFS);\n assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.ISCSI);\n assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.FCP);\n assertInvalidVolumeInfoCombination(VolumeFormat.Unassigned, VolumeType.Preallocated, StorageType.LOCALFS);\n }\n public void testValidateUniqueTemplateNameInDC() {\n ImportVmTemplateCommand command =\n setupVolumeFormatAndTypeTest(VolumeFormat.RAW, VolumeType.Preallocated, StorageType.NFS);\n doReturn(true).when(command).isVmTemplateWithSameNameExist();\n CanDoActionTestUtils.runAndAssertCanDoActionFailure(command,\n EngineMessage.VM_CANNOT_IMPORT_TEMPLATE_NAME_EXISTS);\n }\n private void assertValidVolumeInfoCombination(VolumeFormat volumeFormat,\n VolumeType volumeType,\n StorageType storageType) {\n CanDoActionTestUtils.runAndAssertCanDoActionSuccess(\n setupVolumeFormatAndTypeTest(volumeFormat, volumeType, storageType));\n }\n private void assertInvalidVolumeInfoCombination(VolumeFormat volumeFormat,\n VolumeType volumeType,\n StorageType storageType) {\n CanDoActionTestUtils.runAndAssertCanDoActionFailure(\n setupVolumeFormatAndTypeTest(volumeFormat, volumeType, storageType),\n EngineMessage.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED);\n }\n /**\n * Prepare a command for testing the given volume format and type combination.\n *\n * @param volumeFormat\n * The volume format of the \"imported\" image.\n * @param volumeType\n * The volume type of the \"imported\" image.\n * @param storageType\n * The target domain's storage type.\n * @return The command which can be called to test the given combination.\n */\n private ImportVmTemplateCommand setupVolumeFormatAndTypeTest(\n VolumeFormat volumeFormat,\n VolumeType volumeType,\n StorageType storageType) {\n ImportVmTemplateCommand command = spy(new ImportVmTemplateCommand(createParameters()){\n @Override\n public VDSGroup getVdsGroup() {\n return null;\n }\n });\n Backend backend = mock(Backend.class);\n doReturn(backend).when(command).getBackend();\n doReturn(false).when(command).isVmTemplateWithSameNameExist();\n doReturn(true).when(command).isVDSGroupCompatible();\n doReturn(true).when(command).validateNoDuplicateDiskImages(any(Iterable.class));\n mockGetTemplatesFromExportDomainQuery(volumeFormat, volumeType, command);\n mockStorageDomainStatic(command, storageType);\n doReturn(mock(VmTemplateDao.class)).when(command).getVmTemplateDao();\n doReturn(Mockito.mock(MacPoolManagerStrategy.class)).when(command).getMacPool();\n mockStoragePool(command);\n mockStorageDomains(command);\n doReturn(true).when(command).setAndValidateDiskProfiles();\n doReturn(true).when(command).setAndValidateCpuProfile();\n doReturn(true).when(command).validateSpaceRequirements(anyList());\n return command;\n }\n private static void mockStorageDomains(ImportVmTemplateCommand command) {\n final ImportVmTemplateParameters parameters = command.getParameters();\n final StorageDomainDao dao = mock(StorageDomainDao.class);\n final StorageDomain srcDomain = new StorageDomain();\n srcDomain.setStorageDomainType(StorageDomainType.ImportExport);\n srcDomain.setStatus(StorageDomainStatus.Active);\n when(dao.getForStoragePool(parameters.getSourceDomainId(), parameters.getStoragePoolId()))\n .thenReturn(srcDomain);\n final StorageDomain destDomain = new StorageDomain();\n destDomain.setStorageDomainType(StorageDomainType.Data);\n destDomain.setUsedDiskSize(0);\n destDomain.setAvailableDiskSize(1000);\n destDomain.setStatus(StorageDomainStatus.Active);\n when(dao.getForStoragePool(parameters.getDestDomainId(), parameters.getStoragePoolId()))\n .thenReturn(destDomain);\n doReturn(dao).when(command).getStorageDomainDao();\n }\n private static void mockStoragePool(ImportVmTemplateCommand command) {\n final StoragePoolDao dao = mock(StoragePoolDao.class);\n final StoragePool pool = new StoragePool();\n pool.setId(command.getParameters().getStoragePoolId());\n when(dao.get(any(Guid.class))).thenReturn(pool);\n doReturn(dao).when(command).getStoragePoolDao();\n }\n private static void mockGetTemplatesFromExportDomainQuery(VolumeFormat volumeFormat,\n VolumeType volumeType,\n ImportVmTemplateCommand command) {\n final VdcQueryReturnValue result = new VdcQueryReturnValue();\n Map> resultMap = new HashMap>();\n DiskImage image = new DiskImage();\n image.setActualSizeInBytes(2);\n image.setvolumeFormat(volumeFormat);\n image.setVolumeType(volumeType);\n resultMap.put(new VmTemplate(), Arrays.asList(image));\n result.setReturnValue(resultMap);\n result.setSucceeded(true);\n when(command.getBackend().runInternalQuery(eq(VdcQueryType.GetTemplatesFromExportDomain),\n any(VdcQueryParametersBase.class), any(EngineContext.class))).thenReturn(result);\n }\n private static void mockStorageDomainStatic(\n ImportVmTemplateCommand command,\n StorageType storageType) {\n final StorageDomainStaticDao dao = mock(StorageDomainStaticDao.class);\n final StorageDomainStatic domain = new StorageDomainStatic();\n domain.setStorageType(storageType);\n when(dao.get(any(Guid.class))).thenReturn(domain);\n doReturn(dao).when(command).getStorageDomainStaticDao();\n }\n protected ImportVmTemplateParameters createParameters() {\n VmTemplate t = new VmTemplate();\n t.setName(\"testTemplate\");\n final ImportVmTemplateParameters p =\n new ImportVmTemplateParameters(Guid.newGuid(), Guid.newGuid(), Guid.newGuid(), Guid.newGuid(), t);\n return p;\n }\n private final String string100 = \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\" +\n \"0987654321\";\n @Test\n public void testValidateNameSizeImportAsCloned() {\n checkTemplateName(true, string100);\n }\n @Test\n public void testDoNotValidateNameSizeImport() {\n checkTemplateName(false, string100);\n }\n @Test\n public void testValidateNameSpecialCharImportAsCloned() {\n checkTemplateName(true, \"vm_$%$#%#$\");\n }\n @Test\n public void testDoNotValidateNameSpecialCharImport() {\n checkTemplateName(false, \"vm_$%$#%#$\");\n }\n private void checkTemplateName(boolean isImportAsNewEntity, String name) {\n", "answers": [" ImportVmTemplateParameters parameters = createParameters();"], "length": 616, "dataset": "lcc", "language": "java", "all_classes": null, "_id": "b8a0388946b2d3e0cf2a7f1db681ccb8c70cc44275b2f173"}
{"input": "", "context": "\n// This file has been generated by the GUI designer. Do not modify.\nnamespace BlinkStickClient\n{\n\tpublic partial class CpuEditorWidget\n\t{\n\t\tprivate global::Gtk.VBox vbox2;\n\t\t\n\t\tprivate global::Gtk.Frame frame1;\n\t\t\n\t\tprivate global::Gtk.Alignment GtkAlignment;\n\t\t\n\t\tprivate global::Gtk.VBox vbox3;\n\t\t\n\t\tprivate global::Gtk.RadioButton radiobuttonMonitor;\n\t\t\n\t\tprivate global::Gtk.Label labelMonitorHint;\n\t\t\n\t\tprivate global::Gtk.RadioButton radiobuttonAlert;\n\t\t\n\t\tprivate global::Gtk.Label labelAlertHint;\n\t\t\n\t\tprivate global::Gtk.Alignment alignment2;\n\t\t\n\t\tprivate global::Gtk.Table table1;\n\t\t\n\t\tprivate global::Gtk.ComboBox comboboxTriggerType;\n\t\t\n\t\tprivate global::Gtk.Label labelCheck;\n\t\t\n\t\tprivate global::Gtk.Label labelMinutes;\n\t\t\n\t\tprivate global::Gtk.Label labelPercent;\n\t\t\n\t\tprivate global::Gtk.Label labelWhen;\n\t\t\n\t\tprivate global::Gtk.SpinButton spinbuttonCheckPeriod;\n\t\t\n\t\tprivate global::Gtk.SpinButton spinbuttonCpuPercent;\n\t\t\n\t\tprivate global::Gtk.Label GtkLabel2;\n\t\t\n\t\tprivate global::Gtk.Frame frame3;\n\t\t\n\t\tprivate global::Gtk.Alignment GtkAlignment1;\n\t\t\n\t\tprivate global::Gtk.HBox hbox1;\n\t\t\n\t\tprivate global::Gtk.Label labelCurrentValue;\n\t\t\n\t\tprivate global::Gtk.Button buttonRefresh;\n\t\t\n\t\tprivate global::Gtk.Label GtkLabel3;\n\t\tprotected virtual void Build ()\n\t\t{\n\t\t\tglobal::Stetic.Gui.Initialize (this);\n\t\t\t// Widget BlinkStickClient.CpuEditorWidget\n\t\t\tglobal::Stetic.BinContainer.Attach (this);\n\t\t\tthis.Name = \"BlinkStickClient.CpuEditorWidget\";\n\t\t\t// Container child BlinkStickClient.CpuEditorWidget.Gtk.Container+ContainerChild\n\t\t\tthis.vbox2 = new global::Gtk.VBox ();\n\t\t\tthis.vbox2.Name = \"vbox2\";\n\t\t\tthis.vbox2.Spacing = 6;\n\t\t\t// Container child vbox2.Gtk.Box+BoxChild\n\t\t\tthis.frame1 = new global::Gtk.Frame ();\n\t\t\tthis.frame1.Name = \"frame1\";\n\t\t\tthis.frame1.ShadowType = ((global::Gtk.ShadowType)(0));\n\t\t\t// Container child frame1.Gtk.Container+ContainerChild\n\t\t\tthis.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F);\n\t\t\tthis.GtkAlignment.Name = \"GtkAlignment\";\n\t\t\tthis.GtkAlignment.LeftPadding = ((uint)(12));\n\t\t\tthis.GtkAlignment.TopPadding = ((uint)(12));\n\t\t\t// Container child GtkAlignment.Gtk.Container+ContainerChild\n\t\t\tthis.vbox3 = new global::Gtk.VBox ();\n\t\t\tthis.vbox3.Name = \"vbox3\";\n\t\t\tthis.vbox3.Spacing = 6;\n\t\t\t// Container child vbox3.Gtk.Box+BoxChild\n\t\t\tthis.radiobuttonMonitor = new global::Gtk.RadioButton (global::Mono.Unix.Catalog.GetString (\"Monitor\"));\n\t\t\tthis.radiobuttonMonitor.CanFocus = true;\n\t\t\tthis.radiobuttonMonitor.Name = \"radiobuttonMonitor\";\n\t\t\tthis.radiobuttonMonitor.DrawIndicator = true;\n\t\t\tthis.radiobuttonMonitor.UseUnderline = true;\n\t\t\tthis.radiobuttonMonitor.Group = new global::GLib.SList (global::System.IntPtr.Zero);\n\t\t\tthis.vbox3.Add (this.radiobuttonMonitor);\n\t\t\tglobal::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.radiobuttonMonitor]));\n\t\t\tw1.Position = 0;\n\t\t\tw1.Expand = false;\n\t\t\tw1.Fill = false;\n\t\t\t// Container child vbox3.Gtk.Box+BoxChild\n\t\t\tthis.labelMonitorHint = new global::Gtk.Label ();\n\t\t\tthis.labelMonitorHint.Name = \"labelMonitorHint\";\n\t\t\tthis.labelMonitorHint.Xpad = 20;\n\t\t\tthis.labelMonitorHint.Xalign = 0F;\n\t\t\tthis.labelMonitorHint.LabelProp = global::Mono.Unix.Catalog.GetString (\"Uses pattern\\'s first animation color to display 0% and second to transition to\" +\n\t\t\t\" 100%. Define a pattern with two Set Color animations for this to take effect\");\n\t\t\tthis.labelMonitorHint.UseMarkup = true;\n\t\t\tthis.labelMonitorHint.Wrap = true;\n\t\t\tthis.vbox3.Add (this.labelMonitorHint);\n\t\t\tglobal::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.labelMonitorHint]));\n\t\t\tw2.Position = 1;\n\t\t\tw2.Expand = false;\n\t\t\tw2.Fill = false;\n\t\t\t// Container child vbox3.Gtk.Box+BoxChild\n\t\t\tthis.radiobuttonAlert = new global::Gtk.RadioButton (global::Mono.Unix.Catalog.GetString (\"Alert\"));\n\t\t\tthis.radiobuttonAlert.CanFocus = true;\n\t\t\tthis.radiobuttonAlert.Name = \"radiobuttonAlert\";\n\t\t\tthis.radiobuttonAlert.DrawIndicator = true;\n\t\t\tthis.radiobuttonAlert.UseUnderline = true;\n\t\t\tthis.radiobuttonAlert.Group = this.radiobuttonMonitor.Group;\n\t\t\tthis.vbox3.Add (this.radiobuttonAlert);\n\t\t\tglobal::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.radiobuttonAlert]));\n\t\t\tw3.Position = 2;\n\t\t\tw3.Expand = false;\n\t\t\tw3.Fill = false;\n\t\t\t// Container child vbox3.Gtk.Box+BoxChild\n\t\t\tthis.labelAlertHint = new global::Gtk.Label ();\n\t\t\tthis.labelAlertHint.Name = \"labelAlertHint\";\n\t\t\tthis.labelAlertHint.Xpad = 20;\n\t\t\tthis.labelAlertHint.Xalign = 0F;\n\t\t\tthis.labelAlertHint.LabelProp = global::Mono.Unix.Catalog.GetString (\"When event occurs triggers pattern playback\");\n\t\t\tthis.labelAlertHint.UseMarkup = true;\n\t\t\tthis.labelAlertHint.Wrap = true;\n\t\t\tthis.vbox3.Add (this.labelAlertHint);\n\t\t\tglobal::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.labelAlertHint]));\n\t\t\tw4.Position = 3;\n\t\t\tw4.Expand = false;\n\t\t\tw4.Fill = false;\n\t\t\t// Container child vbox3.Gtk.Box+BoxChild\n\t\t\tthis.alignment2 = new global::Gtk.Alignment (0.5F, 0.5F, 1F, 1F);\n\t\t\tthis.alignment2.Name = \"alignment2\";\n\t\t\tthis.alignment2.LeftPadding = ((uint)(40));\n\t\t\t// Container child alignment2.Gtk.Container+ContainerChild\n\t\t\tthis.table1 = new global::Gtk.Table (((uint)(2)), ((uint)(5)), false);\n\t\t\tthis.table1.Name = \"table1\";\n\t\t\tthis.table1.RowSpacing = ((uint)(6));\n\t\t\tthis.table1.ColumnSpacing = ((uint)(6));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.comboboxTriggerType = global::Gtk.ComboBox.NewText ();\n\t\t\tthis.comboboxTriggerType.AppendText (global::Mono.Unix.Catalog.GetString (\"increases above\"));\n\t\t\tthis.comboboxTriggerType.AppendText (global::Mono.Unix.Catalog.GetString (\"drops below\"));\n\t\t\tthis.comboboxTriggerType.Name = \"comboboxTriggerType\";\n\t\t\tthis.table1.Add (this.comboboxTriggerType);\n\t\t\tglobal::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table1 [this.comboboxTriggerType]));\n\t\t\tw5.LeftAttach = ((uint)(1));\n\t\t\tw5.RightAttach = ((uint)(2));\n\t\t\tw5.XOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\tw5.YOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.labelCheck = new global::Gtk.Label ();\n\t\t\tthis.labelCheck.Name = \"labelCheck\";\n\t\t\tthis.labelCheck.Xalign = 1F;\n\t\t\tthis.labelCheck.LabelProp = global::Mono.Unix.Catalog.GetString (\"Check every\");\n\t\t\tthis.table1.Add (this.labelCheck);\n\t\t\tglobal::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelCheck]));\n\t\t\tw6.TopAttach = ((uint)(1));\n\t\t\tw6.BottomAttach = ((uint)(2));\n\t\t\tw6.XOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\tw6.YOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.labelMinutes = new global::Gtk.Label ();\n\t\t\tthis.labelMinutes.Name = \"labelMinutes\";\n\t\t\tthis.labelMinutes.Xalign = 0F;\n\t\t\tthis.labelMinutes.LabelProp = global::Mono.Unix.Catalog.GetString (\"min\");\n\t\t\tthis.table1.Add (this.labelMinutes);\n\t\t\tglobal::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelMinutes]));\n\t\t\tw7.TopAttach = ((uint)(1));\n\t\t\tw7.BottomAttach = ((uint)(2));\n\t\t\tw7.LeftAttach = ((uint)(3));\n\t\t\tw7.RightAttach = ((uint)(4));\n\t\t\tw7.XOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\tw7.YOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.labelPercent = new global::Gtk.Label ();\n\t\t\tthis.labelPercent.Name = \"labelPercent\";\n\t\t\tthis.labelPercent.Xalign = 0F;\n\t\t\tthis.labelPercent.LabelProp = global::Mono.Unix.Catalog.GetString (\"%\");\n\t\t\tthis.table1.Add (this.labelPercent);\n\t\t\tglobal::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelPercent]));\n\t\t\tw8.LeftAttach = ((uint)(3));\n\t\t\tw8.RightAttach = ((uint)(4));\n\t\t\tw8.XOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\tw8.YOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.labelWhen = new global::Gtk.Label ();\n\t\t\tthis.labelWhen.Name = \"labelWhen\";\n\t\t\tthis.labelWhen.Xalign = 1F;\n\t\t\tthis.labelWhen.LabelProp = global::Mono.Unix.Catalog.GetString (\"When\");\n\t\t\tthis.table1.Add (this.labelWhen);\n\t\t\tglobal::Gtk.Table.TableChild w9 = ((global::Gtk.Table.TableChild)(this.table1 [this.labelWhen]));\n\t\t\tw9.XOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\tw9.YOptions = ((global::Gtk.AttachOptions)(4));\n\t\t\t// Container child table1.Gtk.Table+TableChild\n\t\t\tthis.spinbuttonCheckPeriod = new global::Gtk.SpinButton (1D, 120D, 1D);\n\t\t\tthis.spinbuttonCheckPeriod.CanFocus = true;\n\t\t\tthis.spinbuttonCheckPeriod.Name = \"spinbuttonCheckPeriod\";\n\t\t\tthis.spinbuttonCheckPeriod.Adjustment.PageIncrement = 10D;\n\t\t\tthis.spinbuttonCheckPeriod.ClimbRate = 1D;\n\t\t\tthis.spinbuttonCheckPeriod.Numeric = true;\n\t\t\tthis.spinbuttonCheckPeriod.Value = 1D;\n\t\t\tthis.table1.Add (this.spinbuttonCheckPeriod);\n\t\t\tglobal::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table1 [this.spinbuttonCheckPeriod]));\n", "answers": ["\t\t\tw10.TopAttach = ((uint)(1));"], "length": 650, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "6261fc22209c7ae19b5098f7004853c527e546aedd74f793"}
{"input": "", "context": "/*\n * Copyright (c) 2003-2009 jMonkeyEngine\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * * Neither the name of 'jMonkeyEngine' nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage com.jme.scene;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.nio.FloatBuffer;\nimport java.nio.IntBuffer;\nimport java.util.logging.Logger;\nimport com.jme.intersection.CollisionResults;\nimport com.jme.math.Vector3f;\nimport com.jme.renderer.Renderer;\nimport com.jme.system.JmeException;\nimport com.jme.util.export.InputCapsule;\nimport com.jme.util.export.JMEExporter;\nimport com.jme.util.export.JMEImporter;\nimport com.jme.util.export.OutputCapsule;\nimport com.jme.util.geom.BufferUtils;\n/**\n * QuadMesh defines a geometry mesh. This mesh defines a three\n * dimensional object via a collection of points, colors, normals and textures.\n * The points are referenced via a indices array. This array instructs the\n * renderer the order in which to draw the points, creating quads based on the mode set.\n * \n * @author Joshua Slack\n * @version $Id: $\n */\npublic class QuadMesh extends Geometry implements Serializable {\n private static final Logger logger = Logger.getLogger(QuadMesh.class\n .getName());\n private static final long serialVersionUID = 2L;\n public enum Mode {\n /**\n * Every four vertices referenced by the indexbuffer will be considered\n * a stand-alone quad.\n */\n Quads,\n /**\n * The first four vertices referenced by the indexbuffer create a\n * triangle, from there, every two additional vertices are paired with\n * the two preceding vertices to make a new quad.\n */\n Strip;\n }\n protected transient IntBuffer indexBuffer;\n protected Mode mode = Mode.Quads;\n protected int quadQuantity;\n private static Vector3f[] quads;\n /**\n * Empty Constructor to be used internally only.\n */\n public QuadMesh() {\n super();\n }\n /**\n * Constructor instantiates a new TriMesh object.\n * \n * @param name\n * the name of the scene element. This is required for\n * identification and comparision purposes.\n */\n public QuadMesh(String name) {\n super(name);\n }\n /**\n * Constructor instantiates a new TriMesh object. Provided\n * are the attributes that make up the mesh all attributes may be null,\n * except for vertices and indices.\n * \n * @param name\n * the name of the scene element. This is required for\n * identification and comparision purposes.\n * @param vertices\n * the vertices of the geometry.\n * @param normal\n * the normals of the geometry.\n * @param color\n * the colors of the geometry.\n * @param coords\n * the texture coordinates of the mesh.\n * @param indices\n * the indices of the vertex array.\n */\n public QuadMesh(String name, FloatBuffer vertices, FloatBuffer normal,\n FloatBuffer color, TexCoords coords, IntBuffer indices) {\n super(name);\n reconstruct(vertices, normal, color, coords);\n if (null == indices) {\n logger.severe(\"Indices may not be null.\");\n throw new JmeException(\"Indices may not be null.\");\n }\n setIndexBuffer(indices);\n logger.info(\"QuadMesh created.\");\n }\n /**\n * Recreates the geometric information of this TriMesh from scratch. The\n * index and vertex array must not be null, but the others may be. Every 3\n * indices define an index in the vertices array that\n * refrences a vertex of a triangle.\n * \n * @param vertices\n * The vertex information for this TriMesh.\n * @param normal\n * The normal information for this TriMesh.\n * @param color\n * The color information for this TriMesh.\n * @param coords\n * The texture information for this TriMesh.\n * @param indices\n * The index information for this TriMesh.\n */\n public void reconstruct(FloatBuffer vertices, FloatBuffer normal,\n FloatBuffer color, TexCoords coords, IntBuffer indices) {\n super.reconstruct(vertices, normal, color, coords);\n if (null == indices) {\n logger.severe(\"Indices may not be null.\");\n throw new JmeException(\"Indices may not be null.\");\n }\n setIndexBuffer(indices);\n }\n public void setMode(Mode mode) {\n this.mode = mode;\n }\n public Mode getMode() {\n return mode;\n }\n public IntBuffer getIndexBuffer() {\n return indexBuffer;\n }\n public void setIndexBuffer(IntBuffer indices) {\n this.indexBuffer = indices;\n recalcQuadQuantity();\n }\n protected void recalcQuadQuantity() {\n if (indexBuffer == null) {\n quadQuantity = 0;\n return;\n }\n \n switch (mode) {\n case Quads:\n quadQuantity = indexBuffer.limit() / 4;\n break;\n case Strip:\n quadQuantity = indexBuffer.limit() / 2 - 1;\n break;\n }\n }\n /**\n * Returns the number of triangles contained in this mesh.\n */\n public int getQuadCount() {\n return quadQuantity;\n }\n public void setQuadQuantity(int quadQuantity) {\n this.quadQuantity = quadQuantity;\n }\n /**\n * Clears the buffers of this QuadMesh. The buffers include its indexBuffer\n * only.\n */\n public void clearBuffers() {\n super.clearBuffers();\n setIndexBuffer(null);\n }\n \n public static Vector3f[] getQuads() {\n return quads;\n }\n public static void setQuads(Vector3f[] quads) {\n QuadMesh.quads = quads;\n }\n /**\n * Stores in the storage array the indices of quad\n * i. If i is an invalid index, or if\n * storage.length<4, then nothing happens\n * \n * @param i\n * The index of the quad to get.\n * @param storage\n * The array that will hold the i's indexes.\n */\n public void getQuad(int i, int[] storage) {\n if (i < getQuadCount() && storage.length >= 4) {\n IntBuffer indices = getIndexBuffer();\n storage[0] = indices.get(getVertIndex(i, 0));\n storage[1] = indices.get(getVertIndex(i, 1));\n storage[2] = indices.get(getVertIndex(i, 2));\n storage[3] = indices.get(getVertIndex(i, 3));\n }\n }\n /**\n * Stores in the vertices array the vertex values of quad\n * i. If i is an invalid quad index,\n * nothing happens.\n * \n * @param i\n * @param vertices\n */\n public void getQuad(int i, Vector3f[] vertices) {\n if (i < getQuadCount() && i >= 0) {\n for (int x = 0; x < 4; x++) {\n if (vertices[x] == null)\n", "answers": [" vertices[x] = new Vector3f();"], "length": 1059, "dataset": "lcc", "language": "java", "all_classes": null, "_id": "1354213b38f26ed15b8f898742ff5002cfb7db09baf32dd7"}
{"input": "", "context": "using System;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\nnamespace mRemoteNG.UI.TaskDialog\n{\n public sealed partial class CommandButton : Button\n {\n //--------------------------------------------------------------------------------\n #region PRIVATE MEMBERS\n //--------------------------------------------------------------------------------\n Image imgArrow1;\n Image imgArrow2;\n const int LEFT_MARGIN = 10;\n const int TOP_MARGIN = 10;\n const int ARROW_WIDTH = 19;\n enum eButtonState { Normal, MouseOver, Down }\n eButtonState m_State = eButtonState.Normal;\n #endregion\n //--------------------------------------------------------------------------------\n #region PUBLIC PROPERTIES\n //--------------------------------------------------------------------------------\n // Override this to make sure the control is invalidated (repainted) when 'Text' is changed\n public override string Text\n {\n get { return base.Text; }\n set\n {\n base.Text = value;\n if (m_autoHeight)\n Height = GetBestHeight();\n Invalidate(); \n }\n }\n // SmallFont is the font used for secondary lines\n private Font SmallFont { get; set; }\n // AutoHeight determines whether the button automatically resizes itself to fit the Text\n bool m_autoHeight = true;\n [Browsable(true)]\n [Category(\"Behavior\")]\n [DefaultValue(true)]\n public bool AutoHeight { get { return m_autoHeight; } set { m_autoHeight = value; if (m_autoHeight) Invalidate(); } }\n #endregion\n //--------------------------------------------------------------------------------\n #region CONSTRUCTOR\n //--------------------------------------------------------------------------------\n public CommandButton()\n {\n InitializeComponent();\n Font = new Font(\"Segoe UI\", 11.75F, FontStyle.Regular, GraphicsUnit.Point, 0);\n SmallFont = new Font(\"Segoe UI\", 8F, FontStyle.Regular, GraphicsUnit.Point, 0);\n }\n \n #endregion\n //--------------------------------------------------------------------------------\n #region PUBLIC ROUTINES\n //--------------------------------------------------------------------------------\n public int GetBestHeight()\n {\n return (TOP_MARGIN * 2) + (int)GetSmallTextSizeF().Height + (int)GetLargeTextSizeF().Height;\n }\n #endregion\n //--------------------------------------------------------------------------------\n #region PRIVATE ROUTINES\n //--------------------------------------------------------------------------------\n string GetLargeText()\n {\n string[] lines = Text.Split('\\n');\n return lines[0];\n }\n string GetSmallText()\n {\n if (Text.IndexOf('\\n') < 0)\n return \"\";\n string s = Text;\n string[] lines = s.Split('\\n');\n s = \"\";\n for (int i = 1; i < lines.Length; i++)\n s += lines[i] + \"\\n\";\n return s.Trim('\\n');\n }\n SizeF GetLargeTextSizeF()\n {\n int x = LEFT_MARGIN + ARROW_WIDTH + 5;\n SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN\n Graphics g = Graphics.FromHwnd(Handle);\n SizeF textSize = g.MeasureString(GetLargeText(), Font, mzSize);\n return textSize;\n }\n SizeF GetSmallTextSizeF()\n {\n string s = GetSmallText();\n if (s == \"\") return new SizeF(0, 0);\n int x = LEFT_MARGIN + ARROW_WIDTH + 8; // <- indent small text slightly more\n SizeF mzSize = new SizeF(Width - x - LEFT_MARGIN, 5000.0F); // presume RIGHT_MARGIN = LEFT_MARGIN\n Graphics g = Graphics.FromHwnd(Handle);\n SizeF textSize = g.MeasureString(s, SmallFont, mzSize);\n return textSize;\n }\n #endregion\n //--------------------------------------------------------------------------------\n #region OVERRIDEs\n //--------------------------------------------------------------------------------\n protected override void OnCreateControl()\n {\n base.OnCreateControl();\n imgArrow1 = Resources.green_arrow1;\n imgArrow2 = Resources.green_arrow2;\n }\n //--------------------------------------------------------------------------------\n protected override void OnPaint(PaintEventArgs e)\n {\n e.Graphics.SmoothingMode = SmoothingMode.HighQuality;\n e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;\n LinearGradientBrush brush;\n LinearGradientMode mode = LinearGradientMode.Vertical;\n Rectangle newRect = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);\n Color text_color = SystemColors.WindowText;\n Image img = imgArrow1;\n \n if (Enabled)\n {\n switch (m_State)\n {\n case eButtonState.Normal:\n e.Graphics.FillRectangle(SystemBrushes.Control, newRect);\n e.Graphics.DrawRectangle(Focused ? new Pen(Color.Silver, 1) : new Pen(SystemColors.Control, 1), newRect);\n text_color = Color.DarkBlue;\n break;\n case eButtonState.MouseOver:\n brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);\n e.Graphics.FillRectangle(brush, newRect);\n e.Graphics.DrawRectangle(new Pen(Color.Silver, 1), newRect);\n img = imgArrow2;\n text_color = Color.Blue;\n break;\n case eButtonState.Down:\n brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);\n e.Graphics.FillRectangle(brush, newRect);\n e.Graphics.DrawRectangle(new Pen(Color.DarkGray, 1), newRect);\n text_color = Color.DarkBlue;\n break;\n }\n }\n else\n {\n brush = new LinearGradientBrush(newRect, SystemColors.Control, SystemColors.Control, mode);\n e.Graphics.FillRectangle(brush, newRect);\n e.Graphics.DrawRectangle(new Pen(Color.DarkGray, 1), newRect);\n text_color = Color.DarkBlue;\n }\n string largetext = GetLargeText();\n string smalltext = GetSmallText();\n SizeF szL = GetLargeTextSizeF();\n //e.Graphics.DrawString(largetext, base.Font, new SolidBrush(text_color), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN), szL));\n TextRenderer.DrawText(e.Graphics, largetext, Font, new Rectangle(LEFT_MARGIN + imgArrow1.Width + 5, TOP_MARGIN, (int)szL.Width, (int)szL.Height), text_color, TextFormatFlags.Default);\n if (smalltext != \"\")\n {\n SizeF szS = GetSmallTextSizeF();\n e.Graphics.DrawString(smalltext, SmallFont, new SolidBrush(text_color), new RectangleF(new PointF(LEFT_MARGIN + imgArrow1.Width + 8, TOP_MARGIN + (int)szL.Height), szS));\n }\n e.Graphics.DrawImage(img, new Point(LEFT_MARGIN, TOP_MARGIN + (int)(szL.Height / 2) - img.Height / 2));\n }\n //--------------------------------------------------------------------------------\n protected override void OnMouseLeave(EventArgs e)\n {\n m_State = eButtonState.Normal;\n Invalidate();\n base.OnMouseLeave(e);\n }\n //--------------------------------------------------------------------------------\n protected override void OnMouseEnter(EventArgs e)\n {\n m_State = eButtonState.MouseOver;\n Invalidate();\n base.OnMouseEnter(e);\n }\n //--------------------------------------------------------------------------------\n protected override void OnMouseUp(MouseEventArgs e)\n {\n m_State = eButtonState.MouseOver;\n Invalidate();\n base.OnMouseUp(e);\n }\n //--------------------------------------------------------------------------------\n protected override void OnMouseDown(MouseEventArgs e)\n {\n m_State = eButtonState.Down;\n Invalidate();\n base.OnMouseDown(e);\n }\n //--------------------------------------------------------------------------------\n protected override void OnSizeChanged(EventArgs e)\n {\n if (m_autoHeight)\n {\n", "answers": [" int h = GetBestHeight();"], "length": 638, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "9ee2a42b13526dd952de8a27bb5404cee70aa93dc9e35ee7"}
{"input": "", "context": "#\n# Copyright (C) 2019 Red Hat, Inc.\n#\n# This copyrighted material is made available to anyone wishing to use,\n# modify, copy, or redistribute it subject to the terms and conditions of\n# the GNU General Public License v.2, or (at your option) any later version.\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY expressed or implied, including the implied warranties of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n# Public License for more details. You should have received a copy of the\n# GNU General Public License along with this program; if not, write to the\n# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the\n# source code or documentation are not subject to the GNU General Public\n# License and may only be used or replicated with the express permission of\n# Red Hat, Inc.\n#\nfrom collections import OrderedDict, namedtuple\nfrom pyanaconda.core.constants import PayloadRequirementType\nfrom pyanaconda.payload.errors import PayloadRequirementsMissingApply\nfrom pyanaconda.anaconda_loggers import get_module_logger\nlog = get_module_logger(__name__)\nPayloadRequirementReason = namedtuple('PayloadRequirementReason', ['reason', 'strong'])\n__all__ = [\"PayloadRequirements\", \"PayloadRequirement\"]\nclass PayloadRequirement(object):\n \"\"\"An object to store a payload requirement with info about its reasons.\n For each requirement multiple reasons together with their strength\n can be stored in this object using the add_reason method.\n A reason should be just a string with description (ie for tracking purposes).\n Strength is a boolean flag that can be used to indicate whether missing the\n requirement should be considered fatal. Strength of the requirement is\n given by strength of all its reasons.\n \"\"\"\n def __init__(self, req_id, reasons=None):\n self._id = req_id\n self._reasons = reasons or []\n @property\n def id(self):\n \"\"\"Identifier of the requirement (eg a package name)\"\"\"\n return self._id\n @property\n def reasons(self):\n \"\"\"List of reasons for the requirement\"\"\"\n return [reason for reason, strong in self._reasons]\n @property\n def strong(self):\n \"\"\"Strength of the requirement (ie should it be considered fatal?)\"\"\"\n return any(strong for reason, strong in self._reasons)\n def add_reason(self, reason, strong=False):\n \"\"\"Adds a reason to the requirement with optional strength of the reason\"\"\"\n self._reasons.append(PayloadRequirementReason(reason, strong))\n def __str__(self):\n return \"PayloadRequirement(id=%s, reasons=%s, strong=%s)\" % (self.id,\n self.reasons,\n self.strong)\n def __repr__(self):\n return 'PayloadRequirement(id=%s, reasons=%s)' % (self.id, self._reasons)\nclass PayloadRequirements(object):\n \"\"\"A container for payload requirements imposed by installed functionality.\n Stores names of packages and groups required by used installer features,\n together with descriptions of reasons why the object is required and if the\n requirement is strong. Not satisfying strong requirement would be fatal for\n installation.\n \"\"\"\n def __init__(self):\n self._apply_called_for_all_requirements = True\n self._apply_cb = None\n self._reqs = {}\n for req_type in PayloadRequirementType:\n self._reqs[req_type] = OrderedDict()\n def add_packages(self, package_names, reason, strong=True):\n \"\"\"Add packages required for the reason.\n If a package is already required, the new reason will be\n added and the strength of the requirement will be updated.\n :param package_names: names of packages to be added\n :type package_names: list of str\n :param reason: description of reason for adding the packages\n :type reason: str\n :param strong: is the requirement strong (ie is not satisfying it fatal?)\n :type strong: bool\n \"\"\"\n self._add(PayloadRequirementType.package, package_names, reason, strong)\n def add_groups(self, group_ids, reason, strong=True):\n \"\"\"Add groups required for the reason.\n If a group is already required, the new reason will be\n added and the strength of the requirement will be updated.\n :param group_ids: ids of groups to be added\n :type group_ids: list of str\n :param reason: descripiton of reason for adding the groups\n :type reason: str\n :param strong: is the requirement strong\n :type strong: bool\n \"\"\"\n self._add(PayloadRequirementType.group, group_ids, reason, strong)\n def add_requirements(self, requirements):\n \"\"\"Add requirements from a list of Requirement instances.\n :param requirements: list of Requirement instances\n \"\"\"\n for requirement in requirements:\n # check requirement type and add a payload requirement appropriately\n if requirement.type == \"package\":\n self.add_packages([requirement.name], reason=requirement.reason)\n elif requirement.type == \"group\":\n self.add_groups([requirement.name], reason=requirement.reason)\n else:\n log.warning(\"Unknown type: %s in requirement: %s, skipping.\", requirement.type, requirement)\n def _add(self, req_type, ids, reason, strong):\n if not ids:\n log.debug(\"no %s requirement added for %s\", req_type.value, reason)\n reqs = self._reqs[req_type]\n for r_id in ids:\n if r_id not in reqs:\n reqs[r_id] = PayloadRequirement(r_id)\n reqs[r_id].add_reason(reason, strong)\n self._apply_called_for_all_requirements = False\n log.debug(\"added %s requirement '%s' for %s, strong=%s\",\n req_type.value, r_id, reason, strong)\n @property\n def packages(self):\n \"\"\"List of package requirements.\n return: list of package requirements\n rtype: list of PayloadRequirement\n \"\"\"\n return list(self._reqs[PayloadRequirementType.package].values())\n @property\n def groups(self):\n \"\"\"List of group requirements.\n return: list of group requirements\n rtype: list of PayloadRequirement\n \"\"\"\n return list(self._reqs[PayloadRequirementType.group].values())\n def set_apply_callback(self, callback):\n \"\"\"Set the callback for applying requirements.\n The callback will be called by apply() method.\n param callback: callback function to be called by apply() method\n type callback: a function taking one argument (requirements object)\n \"\"\"\n self._apply_cb = callback\n def apply(self):\n \"\"\"Apply requirements using callback function.\n Calls the callback supplied via set_apply_callback() method. If no\n callback was set, an axception is raised.\n return: return value of the callback\n rtype: type of the callback return value\n raise PayloadRequirementsMissingApply: if there is no callback set\n \"\"\"\n if self._apply_cb:\n self._apply_called_for_all_requirements = True\n rv = self._apply_cb(self)\n log.debug(\"apply with result %s called on requirements %s\", rv, self)\n return rv\n else:\n raise PayloadRequirementsMissingApply\n @property\n def applied(self):\n \"\"\"Was all requirements applied?\n return: Was apply called for all current requirements?\n rtype: bool\n \"\"\"\n return self.empty or self._apply_called_for_all_requirements\n @property\n def empty(self):\n \"\"\"Are requirements empty?\n return: True if there are no requirements, else False\n rtype: bool\n \"\"\"\n", "answers": [" return not any(self._reqs.values())"], "length": 879, "dataset": "lcc", "language": "python", "all_classes": null, "_id": "59b6354e9591524b4ada354f2fa122917bcd1253262c12f2"}
{"input": "", "context": "#!/usr/bin/python\n# -*-*- encoding: utf-8 -*-*-\n#\n# Copyright (C) 2006 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n__author__ = 'j.s@google.com (Jeff Scudder)'\nimport sys\nimport unittest\ntry:\n from xml.etree import ElementTree\nexcept ImportError:\n from elementtree import ElementTree\nimport atom\nfrom gdata import test_data\nimport gdata.test_config as conf\nclass AuthorTest(unittest.TestCase):\n \n def setUp(self):\n self.author = atom.Author()\n \n def testEmptyAuthorShouldHaveEmptyExtensionsList(self):\n self.assert_(isinstance(self.author.extension_elements, list))\n self.assert_(len(self.author.extension_elements) == 0)\n \n def testNormalAuthorShouldHaveNoExtensionElements(self):\n self.author.name = atom.Name(text='Jeff Scudder')\n self.assert_(self.author.name.text == 'Jeff Scudder')\n self.assert_(len(self.author.extension_elements) == 0)\n new_author = atom.AuthorFromString(self.author.ToString())\n self.assert_(len(self.author.extension_elements) == 0)\n \n self.author.extension_elements.append(atom.ExtensionElement(\n 'foo', text='bar'))\n self.assert_(len(self.author.extension_elements) == 1)\n self.assert_(self.author.name.text == 'Jeff Scudder')\n new_author = atom.AuthorFromString(self.author.ToString())\n self.assert_(len(self.author.extension_elements) == 1)\n self.assert_(new_author.name.text == 'Jeff Scudder')\n def testEmptyAuthorToAndFromStringShouldMatch(self):\n string_from_author = self.author.ToString()\n new_author = atom.AuthorFromString(string_from_author)\n string_from_new_author = new_author.ToString()\n self.assert_(string_from_author == string_from_new_author)\n \n def testAuthorWithNameToAndFromStringShouldMatch(self):\n self.author.name = atom.Name()\n self.author.name.text = 'Jeff Scudder'\n string_from_author = self.author.ToString()\n new_author = atom.AuthorFromString(string_from_author)\n string_from_new_author = new_author.ToString()\n self.assert_(string_from_author == string_from_new_author)\n self.assert_(self.author.name.text == new_author.name.text)\n \n def testExtensionElements(self):\n self.author.extension_attributes['foo1'] = 'bar'\n self.author.extension_attributes['foo2'] = 'rab'\n self.assert_(self.author.extension_attributes['foo1'] == 'bar')\n self.assert_(self.author.extension_attributes['foo2'] == 'rab')\n new_author = atom.AuthorFromString(self.author.ToString())\n self.assert_(new_author.extension_attributes['foo1'] == 'bar')\n self.assert_(new_author.extension_attributes['foo2'] == 'rab')\n \n def testConvertFullAuthorToAndFromString(self):\n author = atom.AuthorFromString(test_data.TEST_AUTHOR)\n self.assert_(author.name.text == 'John Doe')\n self.assert_(author.email.text == 'johndoes@someemailadress.com')\n self.assert_(author.uri.text == 'http://www.google.com')\n \n \nclass EmailTest(unittest.TestCase):\n \n def setUp(self):\n self.email = atom.Email()\n \n def testEmailToAndFromString(self):\n self.email.text = 'This is a test'\n new_email = atom.EmailFromString(self.email.ToString())\n self.assert_(self.email.text == new_email.text)\n self.assert_(self.email.extension_elements == \n new_email.extension_elements)\n \n \nclass NameTest(unittest.TestCase):\n def setUp(self):\n self.name = atom.Name()\n \n def testEmptyNameToAndFromStringShouldMatch(self):\n string_from_name = self.name.ToString()\n new_name = atom.NameFromString(string_from_name)\n string_from_new_name = new_name.ToString()\n self.assert_(string_from_name == string_from_new_name)\n \n def testText(self):\n self.assert_(self.name.text is None)\n self.name.text = 'Jeff Scudder'\n self.assert_(self.name.text == 'Jeff Scudder')\n new_name = atom.NameFromString(self.name.ToString())\n self.assert_(new_name.text == self.name.text)\n \n def testExtensionElements(self):\n self.name.extension_attributes['foo'] = 'bar'\n self.assert_(self.name.extension_attributes['foo'] == 'bar')\n new_name = atom.NameFromString(self.name.ToString())\n self.assert_(new_name.extension_attributes['foo'] == 'bar')\n \n \nclass ExtensionElementTest(unittest.TestCase):\n \n def setUp(self):\n self.ee = atom.ExtensionElement('foo')\n \n def testEmptyEEShouldProduceEmptyString(self):\n pass\n \n def testEEParsesTreeCorrectly(self):\n deep_tree = atom.ExtensionElementFromString(test_data.EXTENSION_TREE)\n self.assert_(deep_tree.tag == 'feed')\n self.assert_(deep_tree.namespace == 'http://www.w3.org/2005/Atom')\n self.assert_(deep_tree.children[0].tag == 'author')\n self.assert_(deep_tree.children[0].namespace == 'http://www.google.com')\n self.assert_(deep_tree.children[0].children[0].tag == 'name')\n self.assert_(deep_tree.children[0].children[0].namespace == \n 'http://www.google.com')\n self.assert_(deep_tree.children[0].children[0].text.strip() == 'John Doe')\n self.assert_(deep_tree.children[0].children[0].children[0].text.strip() ==\n 'Bar')\n foo = deep_tree.children[0].children[0].children[0]\n self.assert_(foo.tag == 'foo')\n self.assert_(foo.namespace == 'http://www.google.com')\n self.assert_(foo.attributes['up'] == 'down')\n self.assert_(foo.attributes['yes'] == 'no')\n self.assert_(foo.children == [])\n \n def testEEToAndFromStringShouldMatch(self):\n string_from_ee = self.ee.ToString()\n new_ee = atom.ExtensionElementFromString(string_from_ee)\n string_from_new_ee = new_ee.ToString()\n self.assert_(string_from_ee == string_from_new_ee)\n \n deep_tree = atom.ExtensionElementFromString(test_data.EXTENSION_TREE) \n string_from_deep_tree = deep_tree.ToString()\n new_deep_tree = atom.ExtensionElementFromString(string_from_deep_tree)\n string_from_new_deep_tree = new_deep_tree.ToString()\n self.assert_(string_from_deep_tree == string_from_new_deep_tree)\n \n \nclass LinkTest(unittest.TestCase):\n \n def setUp(self):\n self.link = atom.Link()\n \n def testLinkToAndFromString(self):\n self.link.href = 'test href'\n self.link.hreflang = 'english'\n self.link.type = 'text/html'\n self.link.extension_attributes['foo'] = 'bar'\n self.assert_(self.link.href == 'test href')\n self.assert_(self.link.hreflang == 'english')\n self.assert_(self.link.type == 'text/html')\n self.assert_(self.link.extension_attributes['foo'] == 'bar')\n new_link = atom.LinkFromString(self.link.ToString())\n self.assert_(self.link.href == new_link.href)\n self.assert_(self.link.type == new_link.type)\n self.assert_(self.link.hreflang == new_link.hreflang)\n self.assert_(self.link.extension_attributes['foo'] == \n new_link.extension_attributes['foo'])\n def testLinkType(self):\n test_link = atom.Link(link_type='text/html')\n self.assert_(test_link.type == 'text/html')\nclass GeneratorTest(unittest.TestCase):\n def setUp(self):\n self.generator = atom.Generator()\n def testGeneratorToAndFromString(self):\n self.generator.uri = 'www.google.com'\n self.generator.version = '1.0'\n self.generator.extension_attributes['foo'] = 'bar'\n self.assert_(self.generator.uri == 'www.google.com')\n self.assert_(self.generator.version == '1.0')\n self.assert_(self.generator.extension_attributes['foo'] == 'bar')\n new_generator = atom.GeneratorFromString(self.generator.ToString())\n self.assert_(self.generator.uri == new_generator.uri)\n self.assert_(self.generator.version == new_generator.version)\n self.assert_(self.generator.extension_attributes['foo'] ==\n new_generator.extension_attributes['foo'])\nclass TitleTest(unittest.TestCase):\n def setUp(self):\n self.title = atom.Title()\n def testTitleToAndFromString(self):\n self.title.type = 'text'\n self.title.text = 'Less: <'\n self.assert_(self.title.type == 'text')\n self.assert_(self.title.text == 'Less: <')\n new_title = atom.TitleFromString(self.title.ToString())\n self.assert_(self.title.type == new_title.type)\n self.assert_(self.title.text == new_title.text)\nclass SubtitleTest(unittest.TestCase):\n def setUp(self):\n self.subtitle = atom.Subtitle()\n def testTitleToAndFromString(self):\n self.subtitle.type = 'text'\n self.subtitle.text = 'sub & title'\n self.assert_(self.subtitle.type == 'text')\n self.assert_(self.subtitle.text == 'sub & title')\n new_subtitle = atom.SubtitleFromString(self.subtitle.ToString())\n self.assert_(self.subtitle.type == new_subtitle.type)\n self.assert_(self.subtitle.text == new_subtitle.text)\nclass SummaryTest(unittest.TestCase):\n def setUp(self):\n self.summary = atom.Summary()\n def testTitleToAndFromString(self):\n self.summary.type = 'text'\n self.summary.text = 'Less: <'\n self.assert_(self.summary.type == 'text')\n self.assert_(self.summary.text == 'Less: <')\n new_summary = atom.SummaryFromString(self.summary.ToString())\n self.assert_(self.summary.type == new_summary.type)\n self.assert_(self.summary.text == new_summary.text)\nclass CategoryTest(unittest.TestCase):\n def setUp(self):\n", "answers": [" self.category = atom.Category()"], "length": 629, "dataset": "lcc", "language": "python", "all_classes": null, "_id": "0bad08e092a4b3c97228cda53b001b7ddfd62dc3a8be077b"}
{"input": "", "context": "\"\"\"\nBuilds out filesystem trees/data based on the object tree.\nThis is the code behind 'cobbler sync'.\nCopyright 2006-2009, Red Hat, Inc and Others\nMichael DeHaan \nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n02110-1301 USA\n\"\"\"\nimport os\nimport os.path\nimport glob\nimport shutil\nimport time\nimport yaml # Howell-Clark version\nimport sys\nimport glob\nimport traceback\nimport errno\nimport utils\nfrom cexceptions import *\nimport templar \nimport pxegen\nimport item_distro\nimport item_profile\nimport item_repo\nimport item_system\nfrom Cheetah.Template import Template\nimport clogger\nfrom utils import _\nimport cobbler.module_loader as module_loader\nclass BootSync:\n \"\"\"\n Handles conversion of internal state to the tftpboot tree layout\n \"\"\"\n def __init__(self,config,verbose=True,dhcp=None,dns=None,logger=None,tftpd=None):\n \"\"\"\n Constructor\n \"\"\"\n self.logger = logger\n if logger is None:\n self.logger = clogger.Logger()\n self.verbose = verbose\n self.config = config\n self.api = config.api\n self.distros = config.distros()\n self.profiles = config.profiles()\n self.systems = config.systems()\n self.settings = config.settings()\n self.repos = config.repos()\n self.templar = templar.Templar(config, self.logger)\n self.pxegen = pxegen.PXEGen(config, self.logger)\n self.dns = dns\n self.dhcp = dhcp\n self.tftpd = tftpd\n self.bootloc = utils.tftpboot_location()\n self.pxegen.verbose = verbose\n self.dns.verbose = verbose\n self.dhcp.verbose = verbose\n self.pxelinux_dir = os.path.join(self.bootloc, \"pxelinux.cfg\")\n self.grub_dir = os.path.join(self.bootloc, \"grub\")\n self.images_dir = os.path.join(self.bootloc, \"images\")\n self.yaboot_bin_dir = os.path.join(self.bootloc, \"ppc\")\n self.yaboot_cfg_dir = os.path.join(self.bootloc, \"etc\")\n self.s390_dir = os.path.join(self.bootloc, \"s390x\")\n self.rendered_dir = os.path.join(self.settings.webdir, \"rendered\")\n def run(self):\n \"\"\"\n Syncs the current configuration file with the config tree.\n Using the Check().run_ functions previously is recommended\n \"\"\"\n if not os.path.exists(self.bootloc):\n utils.die(self.logger,\"cannot find directory: %s\" % self.bootloc)\n self.logger.info(\"running pre-sync triggers\")\n # run pre-triggers...\n utils.run_triggers(self.api, None, \"/var/lib/cobbler/triggers/sync/pre/*\")\n self.distros = self.config.distros()\n self.profiles = self.config.profiles()\n self.systems = self.config.systems()\n self.settings = self.config.settings()\n self.repos = self.config.repos()\n # execute the core of the sync operation\n self.logger.info(\"cleaning trees\")\n self.clean_trees()\n # Have the tftpd module handle copying bootloaders,\n # distros, images, and all_system_files\n self.tftpd.sync(self.verbose)\n # Copy distros to the webdir\n # Adding in the exception handling to not blow up if files have\n # been moved (or the path references an NFS directory that's no longer\n # mounted)\n\tfor d in self.distros:\n try:\n self.logger.info(\"copying files for distro: %s\" % d.name)\n self.pxegen.copy_single_distro_files(d,\n self.settings.webdir,True)\n self.pxegen.write_templates(d,write_file=True)\n except CX, e:\n self.logger.error(e.value)\n # make the default pxe menu anyway...\n self.pxegen.make_pxe_menu()\n if self.settings.manage_dhcp:\n self.write_dhcp()\n if self.settings.manage_dns:\n self.logger.info(\"rendering DNS files\")\n self.dns.regen_hosts()\n self.dns.write_dns_files()\n if self.settings.manage_tftpd:\n # xinetd.d/tftpd, basically\n self.logger.info(\"rendering TFTPD files\")\n self.tftpd.write_tftpd_files()\n # copy in boot_files\n self.tftpd.write_boot_files()\n self.logger.info(\"cleaning link caches\")\n self.clean_link_cache()\n if self.settings.manage_rsync:\n self.logger.info(\"rendering Rsync files\")\n self.rsync_gen()\n # run post-triggers\n self.logger.info(\"running post-sync triggers\")\n utils.run_triggers(self.api, None, \"/var/lib/cobbler/triggers/sync/post/*\", logger=self.logger)\n utils.run_triggers(self.api, None, \"/var/lib/cobbler/triggers/change/*\", logger=self.logger)\n return True\n def make_tftpboot(self):\n \"\"\"\n Make directories for tftpboot images\n \"\"\"\n if not os.path.exists(self.pxelinux_dir):\n utils.mkdir(self.pxelinux_dir,logger=self.logger)\n if not os.path.exists(self.grub_dir):\n utils.mkdir(self.grub_dir,logger=self.logger)\n grub_images_link = os.path.join(self.grub_dir, \"images\")\n if not os.path.exists(grub_images_link):\n os.symlink(\"../images\", grub_images_link)\n if not os.path.exists(self.images_dir):\n utils.mkdir(self.images_dir,logger=self.logger)\n if not os.path.exists(self.s390_dir):\n utils.mkdir(self.s390_dir,logger=self.logger)\n if not os.path.exists(self.rendered_dir):\n utils.mkdir(self.rendered_dir,logger=self.logger)\n if not os.path.exists(self.yaboot_bin_dir):\n utils.mkdir(self.yaboot_bin_dir,logger=self.logger)\n if not os.path.exists(self.yaboot_cfg_dir):\n utils.mkdir(self.yaboot_cfg_dir,logger=self.logger)\n def clean_trees(self):\n \"\"\"\n Delete any previously built pxelinux.cfg tree and virt tree info and then create\n directories.\n Note: for SELinux reasons, some information goes in /tftpboot, some in /var/www/cobbler\n and some must be duplicated in both. This is because PXE needs tftp, and auto-kickstart\n and Virt operations need http. Only the kernel and initrd images are duplicated, which is\n unfortunate, though SELinux won't let me give them two contexts, so symlinks are not\n a solution. *Otherwise* duplication is minimal.\n \"\"\"\n # clean out parts of webdir and all of /tftpboot/images and /tftpboot/pxelinux.cfg\n for x in os.listdir(self.settings.webdir):\n path = os.path.join(self.settings.webdir,x)\n if os.path.isfile(path):\n if not x.endswith(\".py\"):\n utils.rmfile(path,logger=self.logger)\n if os.path.isdir(path):\n if not x in [\"aux\", \"web\", \"webui\", \"localmirror\",\"repo_mirror\",\"ks_mirror\",\"images\",\"links\",\"pub\",\"repo_profile\",\"repo_system\",\"svc\",\"rendered\",\".link_cache\"] :\n # delete directories that shouldn't exist\n utils.rmtree(path,logger=self.logger)\n if x in [\"kickstarts\",\"kickstarts_sys\",\"images\",\"systems\",\"distros\",\"profiles\",\"repo_profile\",\"repo_system\",\"rendered\"]:\n # clean out directory contents\n utils.rmtree_contents(path,logger=self.logger)\n #\n self.make_tftpboot()\n utils.rmtree_contents(self.pxelinux_dir,logger=self.logger)\n utils.rmtree_contents(self.grub_dir,logger=self.logger)\n utils.rmtree_contents(self.images_dir,logger=self.logger)\n utils.rmtree_contents(self.s390_dir,logger=self.logger)\n utils.rmtree_contents(self.yaboot_bin_dir,logger=self.logger)\n utils.rmtree_contents(self.yaboot_cfg_dir,logger=self.logger)\n utils.rmtree_contents(self.rendered_dir,logger=self.logger)\n def write_dhcp(self):\n self.logger.info(\"rendering DHCP files\")\n self.dhcp.write_dhcp_file()\n self.dhcp.regen_ethers()\n def sync_dhcp(self):\n restart_dhcp = str(self.settings.restart_dhcp).lower()\n which_dhcp_module = module_loader.get_module_from_file(\"dhcp\",\"module\",just_name=True).strip()\n if self.settings.manage_dhcp:\n self.write_dhcp()\n if which_dhcp_module == \"manage_isc\":\n service_name = utils.dhcp_service_name(self.api)\n if restart_dhcp != \"0\":\n rc = utils.subprocess_call(self.logger, \"dhcpd -t -q\", shell=True)\n if rc != 0:\n self.logger.error(\"dhcpd -t failed\")\n return False\n service_restart = \"service %s restart\" % service_name\n rc = utils.subprocess_call(self.logger, service_restart, shell=True)\n if rc != 0:\n", "answers": [" self.logger.error(\"%s failed\" % service_name)"], "length": 750, "dataset": "lcc", "language": "python", "all_classes": null, "_id": "3cc6d50befc6ded615d39d3b18b791d8f06b80ca3b2642b3"}
{"input": "", "context": "/*\nBullet Continuous Collision Detection and Physics Library\nCopyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com\nThis software is provided 'as-is', without any express or implied warranty.\nIn no event will the authors be held liable for any damages arising from the use of this software.\nPermission is granted to anyone to use this software for any purpose, \nincluding commercial applications, and to alter it and redistribute it freely, \nsubject to the following restrictions:\n1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n*/\n#include \n#include \"LinearMath/btIDebugDraw.h\"\n#include \"BulletCollision/CollisionDispatch/btGhostObject.h\"\n#include \"BulletCollision/CollisionShapes/btMultiSphereShape.h\"\n#include \"BulletCollision/BroadphaseCollision/btOverlappingPairCache.h\"\n#include \"BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h\"\n#include \"BulletCollision/CollisionDispatch/btCollisionWorld.h\"\n#include \"LinearMath/btDefaultMotionState.h\"\n#include \"btKinematicCharacterController.h\"\n// static helper method\nstatic btVector3\ngetNormalizedVector(ref btVector3 v)\n{\n\tbtVector3 n(0, 0, 0);\n\tif (v.length() > SIMD_EPSILON) {\n\t\tn = v.normalized();\n\t}\n\treturn n;\n}\n///@todo Interact with dynamic objects,\n///Ride kinematicly animated platforms properly\n///More realistic (or maybe just a config option) falling\n/// . Should integrate falling velocity manually and use that in stepDown()\n///Support jumping\n///Support ducking\nclass btKinematicClosestNotMeRayResultCallback : btCollisionWorld::ClosestRayResultCallback\n{\npublic:\n\tbtKinematicClosestNotMeRayResultCallback (btCollisionObject me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))\n\t{\n\t\tm_me = me;\n\t}\n\tvirtual double addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)\n\t{\n\t\tif (rayResult.m_collisionObject == m_me)\n\t\t\treturn 1.0;\n\t\treturn ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);\n\t}\nprotected:\n\tbtCollisionObject m_me;\n};\nclass btKinematicClosestNotMeConvexResultCallback : btCollisionWorld::ClosestConvexResultCallback\n{\npublic:\n\tbtKinematicClosestNotMeConvexResultCallback (btCollisionObject me, ref btVector3 up, double minSlopeDot)\n\t: btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))\n\t, m_me(me)\n\t, m_up(up)\n\t, m_minSlopeDot(minSlopeDot)\n\t{\n\t}\n\tvirtual double addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)\n\t{\n\t\tif (convexResult.m_hitCollisionObject == m_me)\n\t\t\treturn (double)(1.0);\n\t\tif (!convexResult.m_hitCollisionObject.hasContactResponse())\n\t\t\treturn (double)(1.0);\n\t\tbtVector3 hitNormalWorld;\n\t\tif (normalInWorldSpace)\n\t\t{\n\t\t\thitNormalWorld = convexResult.m_hitNormalLocal;\n\t\t} else\n\t\t{\n\t\t\t///need to transform normal into worldspace\n\t\t\thitNormalWorld = convexResult.m_hitCollisionObject.getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;\n\t\t}\n\t\tdouble dotUp = m_up.dot(hitNormalWorld);\n\t\tif (dotUp < m_minSlopeDot) {\n\t\t\treturn (double)(1.0);\n\t\t}\n\t\treturn ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);\n\t}\nprotected:\n\tbtCollisionObject m_me;\n\tbtVector3 m_up;\n\tdouble m_minSlopeDot;\n};\n/*\n * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'\n *\n * from: http://www-cs-students.stanford.edu/~adityagp/final/node3.html\n */\nbtVector3 btKinematicCharacterController::computeReflectionDirection (ref btVector3 direction, ref btVector3 normal)\n{\n\treturn direction - ((double)(2.0) * direction.dot(normal)) * normal;\n}\n/*\n * Returns the portion of 'direction' that is parallel to 'normal'\n */\nbtVector3 btKinematicCharacterController::parallelComponent (ref btVector3 direction, ref btVector3 normal)\n{\n\tdouble magnitude = direction.dot(normal);\n\treturn normal * magnitude;\n}\n/*\n * Returns the portion of 'direction' that is perpindicular to 'normal'\n */\nbtVector3 btKinematicCharacterController::perpindicularComponent (ref btVector3 direction, ref btVector3 normal)\n{\n\treturn direction - parallelComponent(direction, normal);\n}\nbtKinematicCharacterController::btKinematicCharacterController (btPairCachingGhostObject* ghostObject,btConvexShape* convexShape,double stepHeight, int upAxis)\n{\n\tm_upAxis = upAxis;\n\tm_addedMargin = 0.02;\n\tm_walkDirection.setValue(0,0,0);\n\tm_useGhostObjectSweepTest = true;\n\tm_ghostObject = ghostObject;\n\tm_stepHeight = stepHeight;\n\tm_turnAngle = (double)(0.0);\n\tm_convexShape=convexShape;\t\n\tm_useWalkDirection = true;\t// use walk direction by default, legacy behavior\n\tm_velocityTimeInterval = 0.0;\n\tm_verticalVelocity = 0.0;\n\tm_verticalOffset = 0.0;\n\tm_gravity = 9.8 * 3 ; // 3G acceleration.\n\tm_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.\n\tm_jumpSpeed = 10.0; // ?\n\tm_wasOnGround = false;\n\tm_wasJumping = false;\n\tm_interpolateUp = true;\n\tsetMaxSlope(btRadians(45.0));\n\tm_currentStepOffset = 0;\n\tfull_drop = false;\n\tbounce_fix = false;\n}\nbtKinematicCharacterController::~btKinematicCharacterController ()\n{\n}\nbtPairCachingGhostObject* btKinematicCharacterController::getGhostObject()\n{\n\treturn m_ghostObject;\n}\nbool btKinematicCharacterController::recoverFromPenetration ( btCollisionWorld* collisionWorld)\n{\n\t// Here we must refresh the overlapping paircache as the penetrating movement itself or the\n\t// previous recovery iteration might have used setWorldTransform and pushed us into an object\n\t// that is not in the previous cache contents from the last timestep, as will happen if we\n\t// are pushed into a new AABB overlap. Unhandled this means the next convex sweep gets stuck.\n\t//\n\t// Do this by calling the broadphase's setAabb with the moved AABB, this will update the broadphase\n\t// paircache and the ghostobject's internal paircache at the same time. /BW\n\tbtVector3 minAabb, maxAabb;\n\tm_convexShape.getAabb(m_ghostObject.getWorldTransform(), minAabb,maxAabb);\n\tcollisionWorld.getBroadphase().setAabb(m_ghostObject.getBroadphaseHandle(), \n\t\t\t\t\t\t minAabb, \n\t\t\t\t\t\t maxAabb, \n\t\t\t\t\t\t collisionWorld.getDispatcher());\n\t\t\t\t\t\t \n\tbool penetration = false;\n\tcollisionWorld.getDispatcher().dispatchAllCollisionPairs(m_ghostObject.getOverlappingPairCache(), collisionWorld.getDispatchInfo(), collisionWorld.getDispatcher());\n\tm_currentPosition = m_ghostObject.getWorldTransform().getOrigin();\n\t\n\tdouble maxPen = (double)(0.0);\n\tfor (int i = 0; i < m_ghostObject.getOverlappingPairCache().getNumOverlappingPairs(); i++)\n\t{\n\t\tm_manifoldArray.resize(0);\n\t\tbtBroadphasePair* collisionPair = &m_ghostObject.getOverlappingPairCache().getOverlappingPairArray()[i];\n\t\tbtCollisionObject obj0 = static_cast(collisionPair.m_pProxy0.m_clientObject);\n btCollisionObject obj1 = static_cast(collisionPair.m_pProxy1.m_clientObject);\n\t\tif ((obj0 && !obj0.hasContactResponse()) || (obj1 && !obj1.hasContactResponse()))\n\t\t\tcontinue;\n\t\t\n\t\tif (collisionPair.m_algorithm)\n\t\t\tcollisionPair.m_algorithm.getAllContactManifolds(m_manifoldArray);\n\t\t\n\t\tfor (int j=0;j 0?m_verticalOffset:0));\n\tstart.setIdentity ();\n\tend.setIdentity ();\n\t/* FIXME: Handle penetration properly */\n\tstart.setOrigin (m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_convexShape.getMargin() + m_addedMargin));\n\tend.setOrigin (m_targetPosition);\n\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, -getUpAxisDirections()[m_upAxis], (double)(0.7071));\n\tcallback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n\tcallback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\t\n\tif (m_useGhostObjectSweepTest)\n\t{\n\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, world.getDispatchInfo().m_allowedCcdPenetration);\n\t}\n\telse\n\t{\n\t\tworld.convexSweepTest (m_convexShape, start, end, callback);\n\t}\n\t\n\tif (callback.hasHit())\n\t{\n\t\t// Only modify the position if the hit was a slope and not a wall or ceiling.\n\t\tif(callback.m_hitNormalWorld.dot(getUpAxisDirections()[m_upAxis]) > 0.0)\n\t\t{\n\t\t\t// we moved up only a fraction of the step height\n\t\t\tm_currentStepOffset = m_stepHeight * callback.m_closestHitFraction;\n\t\t\tif (m_interpolateUp == true)\n\t\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\t\telse\n\t\t\t\tm_currentPosition = m_targetPosition;\n\t\t}\n\t\tm_verticalVelocity = 0.0;\n\t\tm_verticalOffset = 0.0;\n\t} else {\n\t\tm_currentStepOffset = m_stepHeight;\n\t\tm_currentPosition = m_targetPosition;\n\t}\n}\nvoid btKinematicCharacterController::updateTargetPositionBasedOnCollision (ref btVector3 hitNormal, double tangentMag, double normalMag)\n{\n\tbtVector3 movementDirection = m_targetPosition - m_currentPosition;\n\tdouble movementLength = movementDirection.length();\n\tif (movementLength>SIMD_EPSILON)\n\t{\n\t\tmovementDirection.normalize();\n\t\tbtVector3 reflectDir = computeReflectionDirection (movementDirection, hitNormal);\n\t\treflectDir.normalize();\n\t\tbtVector3 parallelDir, perpindicularDir;\n\t\tparallelDir = parallelComponent (reflectDir, hitNormal);\n\t\tperpindicularDir = perpindicularComponent (reflectDir, hitNormal);\n\t\tm_targetPosition = m_currentPosition;\n\t\tif (0)//tangentMag != 0.0)\n\t\t{\n\t\t\tbtVector3 parComponent = parallelDir * double (tangentMag*movementLength);\n//\t\t\tConsole.WriteLine(\"parComponent=%f,%f,%f\\n\",parComponent[0],parComponent[1],parComponent[2]);\n\t\t\tm_targetPosition += parComponent;\n\t\t}\n\t\tif (normalMag != 0.0)\n\t\t{\n\t\t\tbtVector3 perpComponent = perpindicularDir * double (normalMag*movementLength);\n//\t\t\tConsole.WriteLine(\"perpComponent=%f,%f,%f\\n\",perpComponent[0],perpComponent[1],perpComponent[2]);\n\t\t\tm_targetPosition += perpComponent;\n\t\t}\n\t} else\n\t{\n//\t\tConsole.WriteLine(\"movementLength don't normalize a zero vector\\n\");\n\t}\n}\nvoid btKinematicCharacterController::stepForwardAndStrafe ( btCollisionWorld* collisionWorld, ref btVector3 walkMove)\n{\n\t// Console.WriteLine(\"m_normalizedDirection=%f,%f,%f\\n\",\n\t// \tm_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);\n\t// phase 2: forward and strafe\n\tbtTransform start, end;\n\tm_targetPosition = m_currentPosition + walkMove;\n\tstart.setIdentity ();\n\tend.setIdentity ();\n\t\n\tdouble fraction = 1.0;\n\tdouble distance2 = (m_currentPosition-m_targetPosition).length2();\n//\tConsole.WriteLine(\"distance2=%f\\n\",distance2);\n\tif (m_touchingContact)\n\t{\n\t\tif (m_normalizedDirection.dot(m_touchingNormal) > (double)(0.0))\n\t\t{\n\t\t\t//interferes with step movement\n\t\t\t//updateTargetPositionBasedOnCollision (m_touchingNormal);\n\t\t}\n\t}\n\tint maxIter = 10;\n\twhile (fraction > (double)(0.01) && maxIter-- > 0)\n\t{\n\t\tstart.setOrigin (m_currentPosition);\n\t\tend.setOrigin (m_targetPosition);\n\t\tbtVector3 sweepDirNegative(m_currentPosition - m_targetPosition);\n\t\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, sweepDirNegative, (double)(0.0));\n\t\tcallback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n\t\tcallback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\t\tdouble margin = m_convexShape.getMargin();\n\t\tm_convexShape.setMargin(margin + m_addedMargin);\n\t\tif (m_useGhostObjectSweepTest)\n\t\t{\n\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t} else\n\t\t{\n\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t}\n\t\t\n\t\tm_convexShape.setMargin(margin);\n\t\t\n\t\tfraction -= callback.m_closestHitFraction;\n\t\tif (callback.hasHit())\n\t\t{\t\n\t\t\t// we moved only a fraction\n\t\t\t//double hitDistance;\n\t\t\t//hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();\n//\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\t\tupdateTargetPositionBasedOnCollision (callback.m_hitNormalWorld);\n\t\t\tbtVector3 currentDir = m_targetPosition - m_currentPosition;\n\t\t\tdistance2 = currentDir.length2();\n\t\t\tif (distance2 > SIMD_EPSILON)\n\t\t\t{\n\t\t\t\tcurrentDir.normalize();\n\t\t\t\t/* See Quake2: \"If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners.\" */\n\t\t\t\tif (currentDir.dot(m_normalizedDirection) <= (double)(0.0))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t{\n//\t\t\t\tConsole.WriteLine(\"currentDir: don't normalize a zero vector\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\t// we moved whole way\n\t\t\tm_currentPosition = m_targetPosition;\n\t\t}\n\t//\tif (callback.m_closestHitFraction == 0)\n\t//\t\tbreak;\n\t}\n}\nvoid btKinematicCharacterController::stepDown ( btCollisionWorld* collisionWorld, double dt)\n{\n\tbtTransform start, end, end_double;\n\tbool runonce = false;\n\t// phase 3: down\n\t/*double additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;\n\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + additionalDownStep);\n\tdouble downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;\n\tbtVector3 gravity_drop = getUpAxisDirections()[m_upAxis] * downVelocity; \n\tm_targetPosition -= (step_drop + gravity_drop);*/\n\tbtVector3 orig_position = m_targetPosition;\n\t\n\tdouble downVelocity = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\tif(downVelocity > 0.0 && downVelocity > m_fallSpeed\n\t\t&& (m_wasOnGround || !m_wasJumping))\n\t\tdownVelocity = m_fallSpeed;\n\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\tm_targetPosition -= step_drop;\n\tbtKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);\n callback.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n callback.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n btKinematicClosestNotMeConvexResultCallback callback2 (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);\n callback2.m_collisionFilterGroup = getGhostObject().getBroadphaseHandle().m_collisionFilterGroup;\n callback2.m_collisionFilterMask = getGhostObject().getBroadphaseHandle().m_collisionFilterMask;\n\twhile (1)\n\t{\n\t\tstart.setIdentity ();\n\t\tend.setIdentity ();\n\t\tend_double.setIdentity ();\n\t\tstart.setOrigin (m_currentPosition);\n\t\tend.setOrigin (m_targetPosition);\n\t\t//set double test for 2x the step drop, to check for a large drop vs small drop\n\t\tend_double.setOrigin (m_targetPosition - step_drop);\n\t\tif (m_useGhostObjectSweepTest)\n\t\t{\n\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\tif (!callback.hasHit())\n\t\t\t{\n\t\t\t\t//test a double fall height, to see if the character should interpolate it's fall (full) or not (partial)\n\t\t\t\tm_ghostObject.convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\t}\n\t\t} else\n\t\t{\n\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end, callback, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\tif (!callback.hasHit())\n\t\t\t\t\t{\n\t\t\t\t\t\t\t//test a double fall height, to see if the character should interpolate it's fall (large) or not (small)\n\t\t\t\t\t\t\tcollisionWorld.convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld.getDispatchInfo().m_allowedCcdPenetration);\n\t\t\t\t\t}\n\t\t}\n\t\n\t\tdouble downVelocity2 = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\t\tbool has_hit = false;\n\t\tif (bounce_fix == true)\n\t\t\thas_hit = callback.hasHit() || callback2.hasHit();\n\t\telse\n\t\t\thas_hit = callback2.hasHit();\n\t\tif(downVelocity2 > 0.0 && downVelocity2 < m_stepHeight && has_hit == true && runonce == false\n\t\t\t\t\t&& (m_wasOnGround || !m_wasJumping))\n\t\t{\n\t\t\t//redo the velocity calculation when falling a small amount, for fast stairs motion\n\t\t\t//for larger falls, use the smoother/slower interpolated movement by not touching the target position\n\t\t\tm_targetPosition = orig_position;\n\t\t\t\t\tdownVelocity = m_stepHeight;\n\t\t\t\tbtVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\t\t\tm_targetPosition -= step_drop;\n\t\t\trunonce = true;\n\t\t\tcontinue; //re-run previous tests\n\t\t}\n\t\tbreak;\n\t}\n\tif (callback.hasHit() || runonce == true)\n\t{\n\t\t// we dropped a fraction of the height . hit floor\n\t\tdouble fraction = (m_currentPosition.y - callback.m_hitPointWorld.y) / 2;\n\t\t//Console.WriteLine(\"hitpoint: %g - pos %g\\n\", callback.m_hitPointWorld.y, m_currentPosition.y);\n\t\tif (bounce_fix == true)\n\t\t{\n\t\t\tif (full_drop == true)\n m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n else\n //due to errors in the closestHitFraction variable when used with large polygons, calculate the hit fraction manually\n m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, fraction);\n\t\t}\n\t\telse\n\t\t\tm_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);\n\t\tfull_drop = false;\n\t\tm_verticalVelocity = 0.0;\n\t\tm_verticalOffset = 0.0;\n\t\tm_wasJumping = false;\n\t} else {\n\t\t// we dropped the full height\n\t\t\n\t\tfull_drop = true;\n\t\tif (bounce_fix == true)\n\t\t{\n\t\t\tdownVelocity = (m_verticalVelocity<0?-m_verticalVelocity:0) * dt;\n\t\t\tif (downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))\n\t\t\t{\n\t\t\t\tm_targetPosition += step_drop; //undo previous target change\n\t\t\t\tdownVelocity = m_fallSpeed;\n\t\t\t\tstep_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);\n\t\t\t\tm_targetPosition -= step_drop;\n\t\t\t}\n\t\t}\n\t\t//Console.WriteLine(\"full drop - %g, %g\\n\", m_currentPosition.y, m_targetPosition.y);\n\t\tm_currentPosition = m_targetPosition;\n\t}\n}\nvoid btKinematicCharacterController::setWalkDirection\n(\nref btVector3 walkDirection\n)\n{\n\tm_useWalkDirection = true;\n\tm_walkDirection = walkDirection;\n\tm_normalizedDirection = getNormalizedVector(m_walkDirection);\n}\nvoid btKinematicCharacterController::setVelocityForTimeInterval\n(\nref btVector3 velocity,\ndouble timeInterval\n)\n{\n//\tConsole.WriteLine(\"setVelocity!\\n\");\n//\tConsole.WriteLine(\" interval: %f\\n\", timeInterval);\n//\tConsole.WriteLine(\" velocity: (%f, %f, %f)\\n\",\n//\t\t velocity.x, velocity.y, velocity.z);\n\tm_useWalkDirection = false;\n\tm_walkDirection = velocity;\n\tm_normalizedDirection = getNormalizedVector(m_walkDirection);\n\tm_velocityTimeInterval += timeInterval;\n}\nvoid btKinematicCharacterController::reset ( btCollisionWorld* collisionWorld )\n{\n m_verticalVelocity = 0.0;\n m_verticalOffset = 0.0;\n m_wasOnGround = false;\n m_wasJumping = false;\n m_walkDirection.setValue(0,0,0);\n m_velocityTimeInterval = 0.0;\n //clear pair cache\n btHashedOverlappingPairCache *cache = m_ghostObject.getOverlappingPairCache();\n while (cache.getOverlappingPairArray().Count > 0)\n {\n cache.removeOverlappingPair(cache.getOverlappingPairArray()[0].m_pProxy0, cache.getOverlappingPairArray()[0].m_pProxy1, collisionWorld.getDispatcher());\n }\n}\nvoid btKinematicCharacterController::warp (ref btVector3 origin)\n{\n\tbtTransform xform;\n\txform.setIdentity();\n\txform.setOrigin (origin);\n\tm_ghostObject.setWorldTransform (xform);\n}\nvoid btKinematicCharacterController::preStep ( btCollisionWorld* collisionWorld)\n{\n\t\n\tint numPenetrationLoops = 0;\n\tm_touchingContact = false;\n\twhile (recoverFromPenetration (collisionWorld))\n\t{\n\t\tnumPenetrationLoops++;\n\t\tm_touchingContact = true;\n\t\tif (numPenetrationLoops > 4)\n\t\t{\n\t\t\t//Console.WriteLine(\"character could not recover from penetration = %d\\n\", numPenetrationLoops);\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_currentPosition = m_ghostObject.getWorldTransform().getOrigin();\n\tm_targetPosition = m_currentPosition;\n//\tConsole.WriteLine(\"m_targetPosition=%f,%f,%f\\n\",m_targetPosition[0],m_targetPosition[1],m_targetPosition[2]);\n\t\n}\n#include \nvoid btKinematicCharacterController::playerStep ( btCollisionWorld* collisionWorld, double dt)\n{\n//\tConsole.WriteLine(\"playerStep(): \");\n//\tConsole.WriteLine(\" dt = %f\", dt);\n\t// quick check...\n\tif (!m_useWalkDirection & (m_velocityTimeInterval <= 0.0 || m_walkDirection.fuzzyZero())) {\n//\t\tConsole.WriteLine(\"\\n\");\n\t\treturn;\t\t// no motion\n\t}\n\tm_wasOnGround = onGround();\n\t// Update fall velocity.\n\tm_verticalVelocity -= m_gravity * dt;\n\tif(m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)\n\t{\n\t\tm_verticalVelocity = m_jumpSpeed;\n\t}\n\tif(m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))\n\t{\n\t\tm_verticalVelocity = -btFabs(m_fallSpeed);\n\t}\n\tm_verticalOffset = m_verticalVelocity * dt;\n\tbtTransform xform;\n\txform = m_ghostObject.getWorldTransform ();\n//\tConsole.WriteLine(\"walkDirection(%f,%f,%f)\\n\",walkDirection,walkDirection[1],walkDirection[2]);\n//\tConsole.WriteLine(\"walkSpeed=%f\\n\",walkSpeed);\n\tstepUp (collisionWorld);\n\tif (m_useWalkDirection) {\n\t\tstepForwardAndStrafe (collisionWorld, m_walkDirection);\n\t} else {\n\t\t//Console.WriteLine(\" time: %f\", m_velocityTimeInterval);\n\t\t// still have some time left for moving!\n\t\tdouble dtMoving =\n\t\t\t(dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;\n\t\tm_velocityTimeInterval -= dt;\n\t\t// how far will we move while we are moving?\n\t\tbtVector3 move = m_walkDirection * dtMoving;\n\t\t//Console.WriteLine(\" dtMoving: %f\", dtMoving);\n\t\t// okay, step\n\t\tstepForwardAndStrafe(collisionWorld, move);\n\t}\n\tstepDown (collisionWorld, dt);\n\t// Console.WriteLine(\"\\n\");\n\txform.setOrigin (m_currentPosition);\n\tm_ghostObject.setWorldTransform (xform);\n}\nvoid btKinematicCharacterController::setFallSpeed (double fallSpeed)\n{\n\tm_fallSpeed = fallSpeed;\n}\nvoid btKinematicCharacterController::setJumpSpeed (double jumpSpeed)\n{\n\tm_jumpSpeed = jumpSpeed;\n}\nvoid btKinematicCharacterController::setMaxJumpHeight (double maxJumpHeight)\n{\n\tm_maxJumpHeight = maxJumpHeight;\n}\nbool btKinematicCharacterController::canJump ()\n{\n\treturn onGround();\n}\nvoid btKinematicCharacterController::jump ()\n{\n\tif (!canJump())\n\t\treturn;\n\tm_verticalVelocity = m_jumpSpeed;\n\tm_wasJumping = true;\n#if 0\n\tcurrently no jumping.\n\tbtTransform xform;\n\tm_rigidBody.getMotionState().getWorldTransform (xform);\n\tbtVector3 up = xform.getBasis()[1];\n\tup.normalize ();\n\tdouble magnitude = ((double)(1.0)/m_rigidBody.getInvMass()) * (double)(8.0);\n\tm_rigidBody.applyCentralImpulse (up * magnitude);\n#endif\n}\nvoid btKinematicCharacterController::setGravity(double gravity)\n{\n\tm_gravity = gravity;\n}\ndouble btKinematicCharacterController::getGravity()\n{\n\treturn m_gravity;\n}\nvoid btKinematicCharacterController::setMaxSlope(double slopeRadians)\n{\n\tm_maxSlopeRadians = slopeRadians;\n", "answers": ["\tm_maxSlopeCosine = btCos(slopeRadians);"], "length": 2149, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "f498e75d306788f63949bcfcf05c9e4bb4e190034ff80488"}
{"input": "", "context": "from django import forms\nfrom django.forms import ValidationError\nfrom django.contrib.auth.models import Group\nfrom common.forms import ModelFormWithHelper\nfrom common.helpers import SubmitCancelFormHelper\nfrom community.constants import COMMUNITY_ADMIN, COMMUNITY_PRESENCE_CHOICES\nfrom community.models import Community, CommunityPage, RequestCommunity\nfrom community.utils import get_groups\nfrom users.models import SystersUser\nclass AddCommunityForm(ModelFormWithHelper):\n \"\"\" Form to create a new Community by admin. \"\"\"\n class Meta:\n model = Community\n fields = ('name', 'slug', 'order', 'location', 'email', 'mailing_list',\n 'parent_community', 'website', 'facebook', 'googleplus',\n 'twitter')\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'index' %}\"\n def __init__(self, *args, **kwargs):\n self.admin = kwargs.pop('admin')\n super(AddCommunityForm, self).__init__(*args, **kwargs)\n def save(self, commit=True):\n \"\"\"Override save to add admin to the instance\"\"\"\n instance = super(AddCommunityForm, self).save(commit=False)\n instance.admin = self.admin\n if commit:\n instance.save()\n return instance\nclass RequestCommunityForm(ModelFormWithHelper):\n \"\"\"Form to request a new Community\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Makes some fields required and modifies a field to use widget\"\"\"\n self.user = kwargs.pop('user')\n super(RequestCommunityForm, self).__init__(*args, **kwargs)\n self.fields['social_presence'] = forms.MultipleChoiceField(\n choices=COMMUNITY_PRESENCE_CHOICES, label=\"Check off all \\\n the social media accounts you can manage for your proposed community:\",\n required=False, widget=forms.CheckboxSelectMultiple)\n self.fields['email'].required = True\n self.fields['demographic_target_count'].required = True\n self.fields['purpose'].required = True\n self.fields['content_developer'].required = True\n self.fields['selection_criteria'].required = True\n self.fields['is_real_time'].required = True\n class Meta:\n model = RequestCommunity\n fields = ('is_member', 'email_id', 'email', 'name', 'slug', 'order', 'location',\n 'type_community', 'other_community_type', 'parent_community',\n 'community_channel', 'mailing_list', 'website', 'facebook',\n 'googleplus', 'twitter', 'social_presence', 'other_account',\n 'demographic_target_count',\n 'purpose', 'is_avail_volunteer', 'count_avail_volunteer', 'content_developer',\n 'selection_criteria', 'is_real_time')\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'index' %}\"\n def clean_social_presence(self):\n \"\"\"Converts the checkbox input into char to save it to the instance's field.\"\"\"\n social_presence = ', '.join(\n map(str, self.cleaned_data['social_presence']))\n return social_presence\n def save(self, commit=True):\n \"\"\"Override save to add user to the instance\"\"\"\n instance = super(RequestCommunityForm, self).save(commit=False)\n instance.user = SystersUser.objects.get(user=self.user)\n if commit:\n instance.save()\n return instance\nclass EditCommunityRequestForm(ModelFormWithHelper):\n \"\"\"Form to edit a community request\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Makes some fields required and modifies a field to use widget\"\"\"\n super(EditCommunityRequestForm, self).__init__(*args, **kwargs)\n self.fields['social_presence'] = forms.MultipleChoiceField(\n choices=COMMUNITY_PRESENCE_CHOICES, label=\"Check off all \\\n the social media accounts you can manage for your proposed community:\",\n required=False, widget=forms.CheckboxSelectMultiple)\n self.fields['email'].required = True\n self.fields['demographic_target_count'].required = True\n self.fields['purpose'].required = True\n self.fields['content_developer'].required = True\n self.fields['selection_criteria'].required = True\n self.fields['is_real_time'].required = True\n class Meta:\n model = RequestCommunity\n fields = ('is_member', 'email_id', 'email', 'name', 'slug', 'order', 'location',\n 'type_community', 'other_community_type', 'parent_community',\n 'community_channel', 'mailing_list', 'website', 'facebook',\n 'googleplus', 'twitter', 'social_presence', 'other_account',\n 'demographic_target_count',\n 'purpose', 'is_avail_volunteer', 'count_avail_volunteer', 'content_developer',\n 'selection_criteria', 'is_real_time')\n widgets = {'social_presence': forms.CheckboxSelectMultiple}\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'view_community_request' community_request.slug %}\"\n def clean_social_presence(self):\n \"\"\"Converts the checkbox input into char to save it to the instance's field.\"\"\"\n social_presence = ', '.join(\n map(str, self.cleaned_data['social_presence']))\n return social_presence\n def clean_slug(self):\n \"\"\"Checks if the slug exists in the Community objects' slug\"\"\"\n slug = self.cleaned_data['slug']\n slug_community_values = Community.objects.all().values_list('order', flat=True)\n if slug in slug_community_values:\n msg = \"Slug by this value already exists. Please choose a different slug\\\n other than {0}!\"\n string_slug_values = ', '.join(map(str, slug_community_values))\n raise ValidationError(msg.format(string_slug_values))\n else:\n return slug\n def clean_order(self):\n \"\"\"Checks if the order exists in the Community objects' order\"\"\"\n order = self.cleaned_data['order']\n order_community_values = list(\n Community.objects.all().values_list('order', flat=True))\n order_community_values.sort()\n if order is None:\n raise ValidationError(\"Order must not be None.\")\n elif order in order_community_values:\n msg = \"Choose order value other than {0}\"\n string_order_values = ', '.join(map(str, order_community_values))\n raise ValidationError(msg.format(string_order_values))\n else:\n return order\nclass EditCommunityForm(ModelFormWithHelper):\n \"\"\"Form to edit Community profile\"\"\"\n class Meta:\n model = Community\n fields = ('name', 'slug', 'order', 'location', 'email', 'mailing_list',\n 'parent_community', 'website', 'facebook', 'googleplus',\n 'twitter')\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'view_community_profile' \" \\\n \"community.slug %}\"\nclass AddCommunityPageForm(ModelFormWithHelper):\n \"\"\"Form to create new CommunityPage. The author and the community of the\n page are expected to be provided when initializing the form:\n * author - currently logged in user, aka the author of the page\n * community - to which Community the CommunityPage belongs\n \"\"\"\n class Meta:\n model = CommunityPage\n fields = ('title', 'slug', 'order', 'content')\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'view_community_landing' \" \\\n \"community.slug %}\"\n def __init__(self, *args, **kwargs):\n self.author = kwargs.pop('author')\n self.community = kwargs.pop('community')\n super(AddCommunityPageForm, self).__init__(*args, **kwargs)\n def save(self, commit=True):\n \"\"\"Override save to add author and community to the instance\"\"\"\n instance = super(AddCommunityPageForm, self).save(commit=False)\n instance.author = SystersUser.objects.get(user=self.author)\n instance.community = self.community\n if commit:\n instance.save()\n return instance\nclass EditCommunityPageForm(ModelFormWithHelper):\n \"\"\"Form to edit a CommunityPage.\"\"\"\n class Meta:\n model = CommunityPage\n fields = ('slug', 'title', 'order', 'content')\n helper_class = SubmitCancelFormHelper\n helper_cancel_href = \"{% url 'view_community_page' community.slug \" \\\n \"object.slug %}\"\nclass PermissionGroupsForm(forms.Form):\n \"\"\"Form to manage (select/deselect) user permission groups\"\"\"\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user')\n community = kwargs.pop('community')\n super(PermissionGroupsForm, self).__init__(*args, **kwargs)\n # get all community groups and remove community admin group\n # from the list of choices\n self.groups = list(get_groups(community.name))\n admin_group = Group.objects.get(\n name=COMMUNITY_ADMIN.format(community.name))\n self.groups.remove(admin_group)\n choices = [(group.pk, group.name) for group in self.groups]\n self.fields['groups'] = forms. \\\n MultipleChoiceField(choices=choices, label=\"\", required=False,\n widget=forms.CheckboxSelectMultiple)\n", "answers": [" self.member_groups = self.user.get_member_groups(self.groups)"], "length": 746, "dataset": "lcc", "language": "python", "all_classes": null, "_id": "bc922d0a7fcc0c037de90c7f575f1de8f8ac956e5c9e4e82"}
{"input": "", "context": "/*\n * Copyright (C) 2006-2010 - Frictional Games\n *\n * This file is part of HPL1 Engine.\n *\n * HPL1 Engine is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * HPL1 Engine is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with HPL1 Engine. If not, see .\n */\nusing System;\nusing System.Drawing;\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nnamespace Mapeditor\n{\n\t/// \n\t/// Summary description for PropertiesLightForm.\n\t/// \n\tpublic class frmPropertiesArea : System.Windows.Forms.Form\n\t{\n\t\tpublic bool mbOkWasPressed=false;\n\t\tcArea mArea;\n private System.Windows.Forms.Label objNameLabel;\n\t\tprivate System.Windows.Forms.Label label1;\n\t\tpublic System.Windows.Forms.Button objOkButton;\n\t\tpublic System.Windows.Forms.Button objCancelButtom;\n\t\tpublic System.Windows.Forms.TextBox objNameText;\n\t\tprivate System.Windows.Forms.Label label6;\n\t\tpublic System.Windows.Forms.ComboBox objActiveBox;\n\t\tpublic System.Windows.Forms.TextBox objXText;\n\t\tprivate System.Windows.Forms.Label objXLabel;\n\t\tprivate System.Windows.Forms.Label objYLabel;\n\t\tprivate System.Windows.Forms.Label label3;\n\t\tpublic System.Windows.Forms.TextBox objZText;\n\t\tprivate System.Windows.Forms.Label label4;\n\t\tpublic System.Windows.Forms.ComboBox objTypeBox;\n\t\tprivate System.Windows.Forms.Label label5;\n\t\tpublic System.Windows.Forms.TextBox objYText;\n\t\tprivate System.Windows.Forms.Label objZLabel;\n\t\tpublic System.Windows.Forms.TextBox objWidthText;\n\t\tprivate System.Windows.Forms.Label label7;\n\t\tpublic System.Windows.Forms.TextBox objHeightText;\n\t\tprivate System.Windows.Forms.Label label8;\n\t\t/// \n\t\t/// Required designer variable.\n\t\t/// \n\t\tprivate System.ComponentModel.Container components = null;\n\t\tpublic frmPropertiesArea(cArea aArea)\n\t\t{\n\t\t\t//\n\t\t\t// Required for Windows Form Designer support\n\t\t\t//\n\t\t\tInitializeComponent();\n\t\t\t//\n\t\t\t// TODO: Add any constructor code after InitializeComponent call\n\t\t\t//\n\t\t\tmArea = aArea;\n\t\t\tobjNameText.Text = aArea.msName;\n\t\t\tobjActiveBox.SelectedIndex = aArea.mbActive?1:0;\n\t\t\t\n\t\t\tobjHeightText.Text = aArea.mfHeight.ToString();\n\t\t\tobjWidthText.Text = aArea.mfWidth.ToString();\n\t\t\t\n\t\t\tobjXLabel.Text = ((cAreaType)aArea.mAForm.mlstTypes[aArea.mlTypeNum]).msDesc[0];\n\t\t\tobjXText.Text = aArea.mfSizeX.ToString();\n\t\t\t\n\t\t\tobjYLabel.Text = ((cAreaType)aArea.mAForm.mlstTypes[aArea.mlTypeNum]).msDesc[1];\n\t\t\tobjYText.Text = aArea.mfSizeY.ToString();\n\t\t\t\n\t\t\tobjZLabel.Text = ((cAreaType)aArea.mAForm.mlstTypes[aArea.mlTypeNum]).msDesc[2];\n\t\t\tobjZText.Text = aArea.mfSizeZ.ToString();\n\t\t\t\n\t\t\tforeach(string sN in aArea.mAForm.objTypeList.Items)\n\t\t\t{\n\t\t\t\tobjTypeBox.Items.Add(sN);\n\t\t\t}\n\t\t\tobjTypeBox.SelectedIndex = aArea.mlTypeNum;\n\t }\n\t\t/// \n\t\t/// Clean up any resources being used.\n\t\t/// \n\t\tprotected override void Dispose( bool disposing )\n\t\t{\n\t\t\tif( disposing )\n\t\t\t{\n\t\t\t\tif(components != null)\n\t\t\t\t{\n\t\t\t\t\tcomponents.Dispose();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbase.Dispose( disposing );\n\t\t}\n\t\t#region Windows Form Designer generated code\n\t\t/// \n\t\t/// Required method for Designer support - do not modify\n\t\t/// the contents of this method with the code editor.\n\t\t/// \n\t\tprivate void InitializeComponent()\n\t\t{\n\t\t\tthis.objNameLabel = new System.Windows.Forms.Label();\n\t\t\tthis.label1 = new System.Windows.Forms.Label();\n\t\t\tthis.objNameText = new System.Windows.Forms.TextBox();\n\t\t\tthis.objXText = new System.Windows.Forms.TextBox();\n\t\t\tthis.objOkButton = new System.Windows.Forms.Button();\n\t\t\tthis.objCancelButtom = new System.Windows.Forms.Button();\n\t\t\tthis.objXLabel = new System.Windows.Forms.Label();\n\t\t\tthis.label6 = new System.Windows.Forms.Label();\n\t\t\tthis.objActiveBox = new System.Windows.Forms.ComboBox();\n\t\t\tthis.objYLabel = new System.Windows.Forms.Label();\n\t\t\tthis.objYText = new System.Windows.Forms.TextBox();\n\t\t\tthis.label3 = new System.Windows.Forms.Label();\n\t\t\tthis.objZLabel = new System.Windows.Forms.Label();\n\t\t\tthis.objZText = new System.Windows.Forms.TextBox();\n\t\t\tthis.label4 = new System.Windows.Forms.Label();\n\t\t\tthis.objTypeBox = new System.Windows.Forms.ComboBox();\n\t\t\tthis.label5 = new System.Windows.Forms.Label();\n\t\t\tthis.objWidthText = new System.Windows.Forms.TextBox();\n\t\t\tthis.label7 = new System.Windows.Forms.Label();\n\t\t\tthis.objHeightText = new System.Windows.Forms.TextBox();\n\t\t\tthis.label8 = new System.Windows.Forms.Label();\n\t\t\tthis.SuspendLayout();\n\t\t\t// \n\t\t\t// objNameLabel\n\t\t\t// \n\t\t\tthis.objNameLabel.Location = new System.Drawing.Point(16, 16);\n\t\t\tthis.objNameLabel.Name = \"objNameLabel\";\n\t\t\tthis.objNameLabel.Size = new System.Drawing.Size(64, 16);\n\t\t\tthis.objNameLabel.TabIndex = 0;\n\t\t\tthis.objNameLabel.Text = \"Name:\";\n\t\t\t// \n\t\t\t// label1\n\t\t\t// \n\t\t\tthis.label1.Location = new System.Drawing.Point(16, 200);\n\t\t\tthis.label1.Name = \"label1\";\n\t\t\tthis.label1.Size = new System.Drawing.Size(48, 16);\n\t\t\tthis.label1.TabIndex = 1;\n\t\t\tthis.label1.Text = \"Var X:\";\n\t\t\t// \n\t\t\t// objNameText\n\t\t\t// \n\t\t\tthis.objNameText.Location = new System.Drawing.Point(104, 16);\n\t\t\tthis.objNameText.MaxLength = 40;\n\t\t\tthis.objNameText.Name = \"objNameText\";\n\t\t\tthis.objNameText.Size = new System.Drawing.Size(104, 20);\n\t\t\tthis.objNameText.TabIndex = 3;\n\t\t\tthis.objNameText.Text = \"\";\n\t\t\t// \n\t\t\t// objXText\n\t\t\t// \n\t\t\tthis.objXText.Location = new System.Drawing.Point(104, 192);\n\t\t\tthis.objXText.MaxLength = 40;\n\t\t\tthis.objXText.Name = \"objXText\";\n\t\t\tthis.objXText.Size = new System.Drawing.Size(104, 20);\n\t\t\tthis.objXText.TabIndex = 4;\n\t\t\tthis.objXText.Text = \"\";\n\t\t\t// \n\t\t\t// objOkButton\n\t\t\t// \n\t\t\tthis.objOkButton.Location = new System.Drawing.Point(24, 432);\n\t\t\tthis.objOkButton.Name = \"objOkButton\";\n\t\t\tthis.objOkButton.Size = new System.Drawing.Size(72, 24);\n\t\t\tthis.objOkButton.TabIndex = 7;\n\t\t\tthis.objOkButton.Text = \"OK\";\n\t\t\tthis.objOkButton.Click += new System.EventHandler(this.objOkButton_Click);\n\t\t\t// \n\t\t\t// objCancelButtom\n\t\t\t// \n\t\t\tthis.objCancelButtom.Location = new System.Drawing.Point(120, 432);\n\t\t\tthis.objCancelButtom.Name = \"objCancelButtom\";\n\t\t\tthis.objCancelButtom.Size = new System.Drawing.Size(72, 24);\n\t\t\tthis.objCancelButtom.TabIndex = 8;\n\t\t\tthis.objCancelButtom.Text = \"Cancel\";\n\t\t\tthis.objCancelButtom.Click += new System.EventHandler(this.objCancelButtom_Click);\n\t\t\t// \n\t\t\t// objXLabel\n\t\t\t// \n\t\t\tthis.objXLabel.Font = new System.Drawing.Font(\"Microsoft Sans Serif\", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));\n\t\t\tthis.objXLabel.Location = new System.Drawing.Point(16, 160);\n\t\t\tthis.objXLabel.Name = \"objXLabel\";\n\t\t\tthis.objXLabel.Size = new System.Drawing.Size(200, 32);\n\t\t\tthis.objXLabel.TabIndex = 12;\n\t\t\tthis.objXLabel.Text = \"Description...\";\n\t\t\t// \n\t\t\t// label6\n\t\t\t// \n\t\t\tthis.label6.Location = new System.Drawing.Point(16, 48);\n\t\t\tthis.label6.Name = \"label6\";\n\t\t\tthis.label6.Size = new System.Drawing.Size(48, 16);\n\t\t\tthis.label6.TabIndex = 15;\n\t\t\tthis.label6.Text = \"Active:\";\n\t\t\t// \n\t\t\t// objActiveBox\n\t\t\t// \n\t\t\tthis.objActiveBox.Items.AddRange(new object[] {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"False\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"True\"});\n\t\t\tthis.objActiveBox.Location = new System.Drawing.Point(104, 48);\n\t\t\tthis.objActiveBox.Name = \"objActiveBox\";\n\t\t\tthis.objActiveBox.Size = new System.Drawing.Size(104, 21);\n\t\t\tthis.objActiveBox.TabIndex = 16;\n\t\t\t// \n\t\t\t// objYLabel\n\t\t\t// \n\t\t\tthis.objYLabel.Font = new System.Drawing.Font(\"Microsoft Sans Serif\", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));\n\t\t\tthis.objYLabel.Location = new System.Drawing.Point(16, 224);\n\t\t\tthis.objYLabel.Name = \"objYLabel\";\n", "answers": ["\t\t\tthis.objYLabel.Size = new System.Drawing.Size(200, 32);"], "length": 722, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "7176f682200a0adf4ae5cf5e13ef2ec7cb669d6f638cffd3"}
{"input": "", "context": "// CommonSecurityDescriptorTest.cs - NUnit Test Cases for CommonSecurityDescriptor\n//\n// Authors:\n//\tJames Bellinger \n//\n// Copyright (C) 2012 James Bellinger\nusing System;\nusing System.Collections.Generic;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing NUnit.Framework;\nnamespace MonoTests.System.Security.AccessControl\n{\n\t[TestFixture]\n\tpublic class CommonSecurityDescriptorTest\n\t{\n\t\t[Test]\n\t\tpublic void DefaultOwnerAndGroup ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(false, false, ControlFlags.None, null, null, null, null);\n\t\t\tAssert.IsNull (csd.Owner);\n\t\t\tAssert.IsNull (csd.Group);\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent\n\t\t\t | ControlFlags.SelfRelative, csd.ControlFlags);\n\t\t}\n\t\t[Test]\n\t\tpublic void GetBinaryForm ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(false, false, ControlFlags.None, null, null, null, null);\n\t\t\tAssert.AreEqual (20, csd.BinaryLength);\n\t\t\tbyte[] binaryForm = new byte[csd.BinaryLength];\n\t\t\tcsd.GetBinaryForm (binaryForm, 0);\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent | ControlFlags.SelfRelative,\n\t\t\t csd.ControlFlags);\n\t\t\t// The default 'Allow Everyone Full Access' serializes as NOT having a\n\t\t\t// DiscretionaryAcl, as the above demonstrates (byte 3 is 0 not 4).\n\t\t\tAssert.AreEqual (new byte[20] {\n\t\t\t\t1, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\t\t\t}, binaryForm);\n\t\t\t// Changing SystemAcl protection does nothing special.\n\t\t\tcsd.SetSystemAclProtection (true, true);\n\t\t\tAssert.AreEqual (20, csd.BinaryLength);\n\t\t\t// Modifying the DiscretionaryAcl (even effective no-ops like this) causes serialization.\n\t\t\tcsd.SetDiscretionaryAclProtection (false, true);\n\t\t\tAssert.AreEqual (48, csd.BinaryLength);\n\t\t}\n\t\t[Test, ExpectedException (typeof (ArgumentOutOfRangeException))]\n\t\tpublic void GetBinaryFormOffset ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(false, false, ControlFlags.None, null, null, null, null);\n\t\t\tcsd.GetBinaryForm (new byte[csd.BinaryLength], 1);\n\t\t}\n\t\t[Test, ExpectedException (typeof (ArgumentNullException))]\n\t\tpublic void GetBinaryFormNull ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(false, false, ControlFlags.None, null, null, null, null);\n\t\t\tcsd.GetBinaryForm (null, 0);\n\t\t}\n\t\t[Test]\n\t\tpublic void AefaModifiedFlagIsStoredOnDiscretionaryAcl ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd1, csd2;\n\t\t\t// Incidentally this shows the DiscretionaryAcl is NOT cloned.\n\t\t\tcsd1 = new CommonSecurityDescriptor (false, false, ControlFlags.None, null, null, null, null);\n\t\t\tcsd2 = new CommonSecurityDescriptor (false, false, ControlFlags.None, null, null, null, csd1.DiscretionaryAcl);\n\t\t\tAssert.AreSame (csd1.DiscretionaryAcl, csd2.DiscretionaryAcl);\n\t\t\tAssert.AreEqual (\"\", csd1.GetSddlForm (AccessControlSections.Access));\n\t\t\tcsd2.SetDiscretionaryAclProtection (false, true);\n\t\t\tAssert.AreEqual (\"D:(A;;0xffffffff;;;WD)\", csd1.GetSddlForm (AccessControlSections.Access));\n\t\t\tAssert.AreEqual (\"D:(A;;0xffffffff;;;WD)\", csd2.GetSddlForm (AccessControlSections.Access));\n\t\t}\n\t\t[Test]\n\t\tpublic void AefaRoundtrip ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd;\n\t\t\tcsd = new CommonSecurityDescriptor (false, false, ControlFlags.None, null, null, null, null);\n\t\t\tAssert.AreEqual (20, csd.BinaryLength);\n\t\t\tbyte[] binaryForm1 = new byte[csd.BinaryLength];\n\t\t\tcsd.GetBinaryForm (binaryForm1, 0);\n\t\t\tcsd = new CommonSecurityDescriptor (false, false, new RawSecurityDescriptor (binaryForm1, 0));\n\t\t\tbyte[] binaryForm2 = new byte[csd.BinaryLength];\n\t\t\tcsd.GetBinaryForm (binaryForm2, 0);\n\t\t\tAssert.AreEqual (binaryForm1, binaryForm2);\n\t\t}\n\t\t[Test]\n\t\tpublic void GetSddlFormAefaRemovesDacl ()\n\t\t{\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(false, false, ControlFlags.None, null, null, null, null);\n\t\t\tAssert.AreEqual (1, csd.DiscretionaryAcl.Count);\n\t\t\tAssert.AreEqual (\"\", csd.GetSddlForm (AccessControlSections.Access));\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent\n\t\t\t | ControlFlags.SelfRelative,\n\t\t\t csd.ControlFlags);\n\t\t\tAssert.AreSame (csd.DiscretionaryAcl, csd.DiscretionaryAcl);\n\t\t\tAssert.AreNotSame (csd.DiscretionaryAcl[0], csd.DiscretionaryAcl[0]);\n\t\t\tAssert.AreEqual (\"\", csd.GetSddlForm (AccessControlSections.Access));\n\t\t\tcsd.SetDiscretionaryAclProtection (false, true);\n\t\t\tAssert.AreEqual (\"D:(A;;0xffffffff;;;WD)\", csd.GetSddlForm (AccessControlSections.Access));\n\t\t\tAssert.AreSame (csd.DiscretionaryAcl, csd.DiscretionaryAcl);\n\t\t\tAssert.AreNotSame (csd.DiscretionaryAcl[0], csd.DiscretionaryAcl[0]);\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent\n\t\t\t | ControlFlags.SelfRelative,\n\t\t\t csd.ControlFlags);\n\t\t\tcsd.SetDiscretionaryAclProtection (true, true);\n\t\t\tAssert.AreEqual (1, csd.DiscretionaryAcl.Count);\n\t\t\tAssert.AreEqual (\"D:P(A;;0xffffffff;;;WD)\", csd.GetSddlForm (AccessControlSections.Access));\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent\n\t\t\t | ControlFlags.DiscretionaryAclProtected\n\t\t\t | ControlFlags.SelfRelative,\n\t\t\t csd.ControlFlags);\n\t\t\tcsd.SetDiscretionaryAclProtection (false, false);\n\t\t\tAssert.AreEqual (1, csd.DiscretionaryAcl.Count);\n\t\t\tAssert.AreEqual (\"D:(A;;0xffffffff;;;WD)\", csd.GetSddlForm (AccessControlSections.Access));\n\t\t\tAssert.AreEqual (ControlFlags.DiscretionaryAclPresent\n\t\t\t | ControlFlags.SelfRelative,\n\t\t\t csd.ControlFlags);\n\t\t}\n\t\t[Test, ExpectedException (typeof (ArgumentException))]\n\t\tpublic void ContainerAndDSConsistencyEnforcedA ()\n\t\t{\n\t\t\tSecurityIdentifier userSid = new SecurityIdentifier (WellKnownSidType.LocalSystemSid, null);\n\t\t\tSecurityIdentifier groupSid = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);\n\t\t\tDiscretionaryAcl dacl = new DiscretionaryAcl (true, true, 0);\n\t\t\tnew CommonSecurityDescriptor (true, false, ControlFlags.None, userSid, groupSid, null, dacl);\n\t\t}\n\t\t[Test, ExpectedException (typeof (ArgumentException))]\n\t\tpublic void ContainerAndDSConsistencyEnforcedB ()\n\t\t{\n\t\t\tSecurityIdentifier userSid = new SecurityIdentifier (WellKnownSidType.LocalSystemSid, null);\n\t\t\tSecurityIdentifier groupSid = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);\n\t\t\tSystemAcl sacl = new SystemAcl (false, false, 0);\n\t\t\tnew CommonSecurityDescriptor (true, false, ControlFlags.None, userSid, groupSid, sacl, null);\n\t\t}\n\t\t[Test, ExpectedException (typeof (ArgumentException))]\n\t\tpublic void ContainerAndDSConsistencyEnforcedInSetter ()\n\t\t{\n\t\t\tSecurityIdentifier userSid = new SecurityIdentifier (WellKnownSidType.LocalSystemSid, null);\n\t\t\tSecurityIdentifier groupSid = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);\n\t\t\tCommonSecurityDescriptor csd = new CommonSecurityDescriptor\n\t\t\t\t(true, false, ControlFlags.None, userSid, groupSid, null, null);\n\t\t\tcsd.DiscretionaryAcl = new DiscretionaryAcl (true, true, 0);\n\t\t}\n\t\t[Test]\n\t\tpublic void DefaultDaclIsAllowEveryoneFullAccess ()\n\t\t{\n\t\t\tSecurityIdentifier userSid = new SecurityIdentifier (\"SY\");\n\t\t\tSecurityIdentifier groupSid = new SecurityIdentifier (\"BA\");\n\t\t\tSecurityIdentifier everyoneSid = new SecurityIdentifier (\"WD\");\n\t\t\tCommonSecurityDescriptor csd; DiscretionaryAcl dacl; CommonAce ace;\n\t\t\tcsd = new CommonSecurityDescriptor (false, false, ControlFlags.None, userSid, groupSid, null, null);\n\t\t\tdacl = csd.DiscretionaryAcl;\n\t\t\tAssert.AreEqual (1, dacl.Count);\n\t\t\tace = (CommonAce)dacl [0];\n\t\t\tAssert.AreEqual (-1, ace.AccessMask);\n\t\t\tAssert.AreEqual (AceFlags.None, ace.AceFlags);\n\t\t\tAssert.AreEqual (AceType.AccessAllowed, ace.AceType);\n\t\t\tAssert.AreEqual (20, ace.BinaryLength);\n\t\t\tAssert.IsFalse (ace.IsCallback);\n\t\t\tAssert.IsFalse (ace.IsInherited);\n\t\t\tAssert.AreEqual (0, ace.OpaqueLength);\n\t\t\tAssert.AreEqual (ace.SecurityIdentifier, everyoneSid);\n\t\t\tcsd = new CommonSecurityDescriptor (true, false, ControlFlags.None, userSid, groupSid, null, null);\n\t\t\tdacl = csd.DiscretionaryAcl;\n\t\t\tAssert.AreEqual (1, dacl.Count);\n\t\t\tace = (CommonAce)dacl [0];\n\t\t\tAssert.AreEqual (-1, ace.AccessMask);\n\t\t\tAssert.AreEqual (AceFlags.ObjectInherit | AceFlags.ContainerInherit, ace.AceFlags);\n\t\t\tAssert.AreEqual (AceType.AccessAllowed, ace.AceType);\n\t\t\tAssert.AreEqual (20, ace.BinaryLength);\n\t\t\tAssert.IsFalse (ace.IsCallback);\n\t\t\tAssert.IsFalse (ace.IsInherited);\n\t\t\tAssert.AreEqual (0, ace.OpaqueLength);\n\t\t\tAssert.AreEqual (ace.SecurityIdentifier, everyoneSid);\n\t\t}\n\t\t[Test]\n\t\tpublic void PurgeDefaultDacl ()\n\t\t{\n", "answers": ["\t\t\tSecurityIdentifier userSid = new SecurityIdentifier (\"SY\");"], "length": 692, "dataset": "lcc", "language": "csharp", "all_classes": null, "_id": "a179ca21c89046426dbe560130d12a91ef853ad8e707e8c2"}
{"input": "", "context": "/**\n * Copyright (c) 2002-2012 \"Neo Technology,\"\n * Network Engine for Objects in Lund AB [http://neotechnology.com]\n *\n * This file is part of Neo4j.\n *\n * Neo4j is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\npackage org.neo4j.graphmatching;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphmatching.filter.AbstractFilterExpression;\nimport org.neo4j.graphmatching.filter.FilterBinaryNode;\nimport org.neo4j.graphmatching.filter.FilterExpression;\nimport org.neo4j.graphmatching.filter.FilterValueGetter;\nimport org.neo4j.helpers.Predicate;\nimport org.neo4j.helpers.collection.FilteringIterable;\n/**\n * The PatternMatcher is the engine that performs the matching of a graph\n * pattern with the actual graph.\n */\n@Deprecated\npublic class PatternMatcher\n{\n\tprivate static PatternMatcher matcher = new PatternMatcher();\n\tprivate PatternMatcher()\n\t{\n\t}\n /**\n * Get the sole instance of the {@link PatternMatcher}.\n *\n * @return the instance of {@link PatternMatcher}.\n */\n\tpublic static PatternMatcher getMatcher()\n\t{\n\t\treturn matcher;\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @return all matching instances of the pattern.\n */\n public Iterable match( PatternNode start,\n Node startNode )\n {\n return match( start, startNode, null );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable match( PatternNode start,\n\t\tNode startNode, Map objectVariables )\n\t{\n\t\treturn match( start, startNode, objectVariables,\n\t\t ( Collection ) null );\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n public Iterable match( PatternNode start,\n Map objectVariables,\n PatternNode... optional )\n {\n return match( start, objectVariables,\n Arrays.asList( optional ) );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable match( PatternNode start,\n\t Map objectVariables,\n\t Collection optional )\n {\n\t Node startNode = start.getAssociation();\n if ( startNode == null )\n {\n throw new IllegalStateException(\n \"Associating node for start pattern node is null\" );\n }\n\t return match( start, startNode, objectVariables, optional );\n }\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable match( PatternNode start,\n\t\tNode startNode, Map objectVariables,\n\t\tCollection optional )\n\t{\n Node currentStartNode = start.getAssociation();\n if ( currentStartNode != null && !currentStartNode.equals( startNode ) )\n {\n throw new IllegalStateException(\n \"Start patter node already has associated \" +\n currentStartNode + \", can not start with \" + startNode );\n }\n\t Iterable result = null;\n\t\tif ( optional == null || optional.size() < 1 )\n\t\t{\n\t\t\tresult = new PatternFinder( this, start, startNode );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = new PatternFinder( this, start, startNode, false,\n\t\t\t optional );\n\t\t}\n\t\tif ( objectVariables != null )\n\t\t{\n \t\t// Uses the FILTER expressions\n \t\tresult = new FilteredPatternFinder( result, objectVariables );\n\t\t}\n\t\treturn result;\n\t}\n /**\n * Find occurrences of the pattern defined by the given {@link PatternNode}\n * where the given {@link PatternNode} starts matching at the given\n * {@link Node}.\n *\n * @param start the {@link PatternNode} to start matching at.\n * @param startNode the {@link Node} to start matching at.\n * @param objectVariables mapping from names to {@link PatternNode}s.\n * @param optional nodes that form sub-patterns connected to this pattern.\n * @return all matching instances of the pattern.\n */\n\tpublic Iterable match( PatternNode start,\n\t\tNode startNode, Map objectVariables,\n\t\tPatternNode... optional )\n\t{\n\t\treturn match( start, startNode, objectVariables,\n\t\t Arrays.asList( optional ) );\n\t}\n\tprivate static class SimpleRegexValueGetter implements FilterValueGetter\n\t{\n\t private PatternMatch match;\n\t private Map labelToNode =\n\t new HashMap();\n\t private Map labelToProperty =\n\t new HashMap();\n\t SimpleRegexValueGetter( Map objectVariables,\n\t PatternMatch match, FilterExpression[] expressions )\n\t {\n this.match = match;\n for ( FilterExpression expression : expressions )\n {\n mapFromExpression( expression );\n }\n this.labelToNode = objectVariables;\n\t }\n\t private void mapFromExpression( FilterExpression expression )\n\t {\n\t if ( expression instanceof FilterBinaryNode )\n\t {\n\t FilterBinaryNode node = ( FilterBinaryNode ) expression;\n\t mapFromExpression( node.getLeftExpression() );\n\t mapFromExpression( node.getRightExpression() );\n\t }\n\t else\n\t {\n\t AbstractFilterExpression pattern =\n\t ( AbstractFilterExpression ) expression;\n\t labelToProperty.put( pattern.getLabel(),\n\t pattern.getProperty() );\n\t }\n\t }\n public String[] getValues( String label )\n {\n PatternNode pNode = labelToNode.get( label );\n if ( pNode == null )\n {\n throw new RuntimeException( \"No node for label '\" + label +\n \"'\" );\n }\n Node node = this.match.getNodeFor( pNode );\n String propertyKey = labelToProperty.get( label );\n if ( propertyKey == null )\n {\n throw new RuntimeException( \"No property key for label '\" +\n label + \"'\" );\n }\n Object rawValue = node.getProperty( propertyKey, null );\n if ( rawValue == null )\n {\n return new String[ 0 ];\n }\n Collection