input
stringlengths
0
1.96k
context
stringlengths
1.23k
257k
answers
listlengths
1
5
length
int32
399
40.5k
dataset
stringclasses
10 values
language
stringclasses
5 values
all_classes
listlengths
_id
stringlengths
48
48
"""Tests for django comment client views.""" from contextlib import contextmanager import logging import json import ddt from django.conf import settings from django.core.cache import get_cache from django.test.client import Client, RequestFactory from django.contrib.auth.models import User from django.core.management import call_command from django.core.urlresolvers import reverse from request_cache.middleware import RequestCache from mock import patch, ANY, Mock from nose.tools import assert_true, assert_equal # pylint: disable=no-name-in-module from opaque_keys.edx.locations import SlashSeparatedCourseKey from lms.lib.comment_client import Thread from common.test.utils import MockSignalHandlerMixin, disable_signal from django_comment_client.base import views from django_comment_client.tests.group_id import CohortedTopicGroupIdTestMixin, NonCohortedTopicGroupIdTestMixin, GroupIdAssertionMixin from django_comment_client.tests.utils import CohortedTestCase from django_comment_client.tests.unicode import UnicodeTestMixin from django_comment_common.models import Role from django_comment_common.utils import seed_permissions_roles, ThreadContext from student.tests.factories import CourseEnrollmentFactory, UserFactory, CourseAccessRoleFactory from util.testing import UrlResetMixin from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import check_mongo_calls from xmodule.modulestore.django import modulestore from xmodule.modulestore import ModuleStoreEnum from teams.tests.factories import CourseTeamFactory log = logging.getLogger(__name__) CS_PREFIX = "http://localhost:4567/api/v1" # pylint: disable=missing-docstring class MockRequestSetupMixin(object): def _create_response_mock(self, data): return Mock(text=json.dumps(data), json=Mock(return_value=data)) def _set_mock_request_data(self, mock_request, data): mock_request.return_value = self._create_response_mock(data) @patch('lms.lib.comment_client.utils.requests.request') class CreateThreadGroupIdTestCase( MockRequestSetupMixin, CohortedTestCase, CohortedTopicGroupIdTestMixin, NonCohortedTopicGroupIdTestMixin ): cs_endpoint = "/threads" def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True): self._set_mock_request_data(mock_request, {}) mock_request.return_value.status_code = 200 request_data = {"body": "body", "title": "title", "thread_type": "discussion"} if pass_group_id: request_data["group_id"] = group_id request = RequestFactory().post("dummy_url", request_data) request.user = user request.view_name = "create_thread" return views.create_thread( request, course_id=unicode(self.course.id), commentable_id=commentable_id ) def test_group_info_in_response(self, mock_request): response = self.call_view( mock_request, "cohorted_topic", self.student, None ) self._assert_json_response_contains_group_info(response) @patch('lms.lib.comment_client.utils.requests.request') @disable_signal(views, 'thread_edited') @disable_signal(views, 'thread_voted') @disable_signal(views, 'thread_deleted') class ThreadActionGroupIdTestCase( MockRequestSetupMixin, CohortedTestCase, GroupIdAssertionMixin ): def call_view( self, view_name, mock_request, user=None, post_params=None, view_args=None ): self._set_mock_request_data( mock_request, { "user_id": str(self.student.id), "group_id": self.student_cohort.id, "closed": False, "type": "thread", "commentable_id": "non_team_dummy_id" } ) mock_request.return_value.status_code = 200 request = RequestFactory().post("dummy_url", post_params or {}) request.user = user or self.student request.view_name = view_name return getattr(views, view_name)( request, course_id=unicode(self.course.id), thread_id="dummy", **(view_args or {}) ) def test_update(self, mock_request): response = self.call_view( "update_thread", mock_request, post_params={"body": "body", "title": "title"} ) self._assert_json_response_contains_group_info(response) def test_delete(self, mock_request): response = self.call_view("delete_thread", mock_request) self._assert_json_response_contains_group_info(response) def test_vote(self, mock_request): response = self.call_view( "vote_for_thread", mock_request, view_args={"value": "up"} ) self._assert_json_response_contains_group_info(response) response = self.call_view("undo_vote_for_thread", mock_request) self._assert_json_response_contains_group_info(response) def test_flag(self, mock_request): response = self.call_view("flag_abuse_for_thread", mock_request) self._assert_json_response_contains_group_info(response) response = self.call_view("un_flag_abuse_for_thread", mock_request) self._assert_json_response_contains_group_info(response) def test_pin(self, mock_request): response = self.call_view( "pin_thread", mock_request, user=self.moderator ) self._assert_json_response_contains_group_info(response) response = self.call_view( "un_pin_thread", mock_request, user=self.moderator ) self._assert_json_response_contains_group_info(response) def test_openclose(self, mock_request): response = self.call_view( "openclose_thread", mock_request, user=self.moderator ) self._assert_json_response_contains_group_info( response, lambda d: d['content'] ) class ViewsTestCaseMixin(object): """ This class is used by both ViewsQueryCountTestCase and ViewsTestCase. By breaking out set_up_course into its own method, ViewsQueryCountTestCase can build a course in a particular modulestore, while ViewsTestCase can just run it in setUp for all tests. """ def set_up_course(self, module_count=0): """ Creates a course, optionally with module_count discussion modules, and a user with appropriate permissions. """ # create a course self.course = CourseFactory.create( org='MITx', course='999', discussion_topics={"Some Topic": {"id": "some_topic"}}, display_name='Robot Super Course', ) self.course_id = self.course.id # add some discussion modules for i in range(module_count): ItemFactory.create( parent_location=self.course.location, category='discussion', discussion_id='id_module_{}'.format(i), discussion_category='Category {}'.format(i), discussion_target='Discussion {}'.format(i) ) # seed the forums permissions and roles call_command('seed_permissions_roles', unicode(self.course_id)) # Patch the comment client user save method so it does not try # to create a new cc user when creating a django user with patch('student.models.cc.User.save'): uname = 'student' email = 'student@edx.org' self.password = 'test' # pylint: disable=attribute-defined-outside-init # Create the user and make them active so we can log them in. self.student = User.objects.create_user(uname, email, self.password) # pylint: disable=attribute-defined-outside-init self.student.is_active = True self.student.save() # Add a discussion moderator self.moderator = UserFactory.create(password=self.password) # pylint: disable=attribute-defined-outside-init # Enroll the student in the course CourseEnrollmentFactory(user=self.student, course_id=self.course_id) # Enroll the moderator and give them the appropriate roles CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id) self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id)) self.client = Client() assert_true(self.client.login(username='student', password=self.password)) def _setup_mock_request(self, mock_request, include_depth=False): """ Ensure that mock_request returns the data necessary to make views function correctly """ mock_request.return_value.status_code = 200 data = { "user_id": str(self.student.id), "closed": False, "commentable_id": "non_team_dummy_id" } if include_depth: data["depth"] = 0 self._set_mock_request_data(mock_request, data) def create_thread_helper(self, mock_request, extra_request_data=None, extra_response_data=None): """ Issues a request to create a thread and verifies the result. """ mock_request.return_value.status_code = 200 self._set_mock_request_data(mock_request, { "thread_type": "discussion", "title": "Hello", "body": "this is a post", "course_id": "MITx/999/Robot_Super_Course", "anonymous": False, "anonymous_to_peers": False, "commentable_id": "i4x-MITx-999-course-Robot_Super_Course", "created_at": "2013-05-10T18:53:43Z", "updated_at": "2013-05-10T18:53:43Z", "at_position_list": [], "closed": False, "id": "518d4237b023791dca00000d", "user_id": "1", "username": "robot", "votes": { "count": 0, "up_count": 0, "down_count": 0, "point": 0 }, "abuse_flaggers": [], "type": "thread", "group_id": None, "pinned": False, "endorsed": False, "unread_comments_count": 0, "read": False, "comments_count": 0, }) thread = { "thread_type": "discussion", "body": ["this is a post"], "anonymous_to_peers": ["false"], "auto_subscribe": ["false"], "anonymous": ["false"], "title": ["Hello"], } if extra_request_data: thread.update(extra_request_data) url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course', 'course_id': unicode(self.course_id)}) response = self.client.post(url, data=thread) assert_true(mock_request.called) expected_data = { 'thread_type': 'discussion', 'body': u'this is a post', 'context': ThreadContext.COURSE, 'anonymous_to_peers': False, 'user_id': 1, 'title': u'Hello', 'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course', 'anonymous': False, 'course_id': unicode(self.course_id), } if extra_response_data: expected_data.update(extra_response_data) mock_request.assert_called_with( 'post', '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX), data=expected_data, params={'request_id': ANY}, headers=ANY, timeout=5 ) assert_equal(response.status_code, 200) def update_thread_helper(self, mock_request): """ Issues a request to update a thread and verifies the result. """ self._setup_mock_request(mock_request) # Mock out saving in order to test that content is correctly # updated. Otherwise, the call to thread.save() receives the # same mocked request data that the original call to retrieve # the thread did, overwriting any changes. with patch.object(Thread, 'save'): response = self.client.post( reverse("update_thread", kwargs={ "thread_id": "dummy", "course_id": unicode(self.course_id) }), data={"body": "foo", "title": "foo", "commentable_id": "some_topic"} ) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEqual(data['body'], 'foo') self.assertEqual(data['title'], 'foo') self.assertEqual(data['commentable_id'], 'some_topic') @ddt.ddt @patch('lms.lib.comment_client.utils.requests.request') @disable_signal(views, 'thread_created') @disable_signal(views, 'thread_edited') class ViewsQueryCountTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin, ViewsTestCaseMixin): @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True}) def setUp(self): super(ViewsQueryCountTestCase, self).setUp(create_user=False) def clear_caches(self): """Clears caches so that query count numbers are accurate.""" for cache in settings.CACHES: get_cache(cache).clear() RequestCache.clear_request_cache() def count_queries(func): # pylint: disable=no-self-argument """ Decorates test methods to count mongo and SQL calls for a particular modulestore. """ def inner(self, default_store, module_count, mongo_calls, sql_queries, *args, **kwargs): with modulestore().default_store(default_store): self.set_up_course(module_count=module_count) self.clear_caches() with self.assertNumQueries(sql_queries): with check_mongo_calls(mongo_calls): func(self, *args, **kwargs) return inner @ddt.data( (ModuleStoreEnum.Type.mongo, 3, 4, 22), (ModuleStoreEnum.Type.mongo, 20, 4, 22), (ModuleStoreEnum.Type.split, 3, 13, 22), (ModuleStoreEnum.Type.split, 20, 13, 22), ) @ddt.unpack @count_queries def test_create_thread(self, mock_request): self.create_thread_helper(mock_request) @ddt.data( (ModuleStoreEnum.Type.mongo, 3, 3, 16), (ModuleStoreEnum.Type.mongo, 20, 3, 16), (ModuleStoreEnum.Type.split, 3, 10, 16), (ModuleStoreEnum.Type.split, 20, 10, 16), ) @ddt.unpack @count_queries def test_update_thread(self, mock_request): self.update_thread_helper(mock_request) @ddt.ddt @patch('lms.lib.comment_client.utils.requests.request') class ViewsTestCase( UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin, ViewsTestCaseMixin, MockSignalHandlerMixin ): @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True}) def setUp(self): # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py, # so we need to call super.setUp() which reloads urls.py (because # of the UrlResetMixin) super(ViewsTestCase, self).setUp(create_user=False) self.set_up_course() @contextmanager def assert_discussion_signals(self, signal, user=None): if user is None: user = self.student with self.assert_signal_sent(views, signal, sender=None, user=user, exclude_args=('post',)): yield def test_create_thread(self, mock_request): with self.assert_discussion_signals('thread_created'): self.create_thread_helper(mock_request) def test_create_thread_standalone(self, mock_request): team = CourseTeamFactory.create( name="A Team", course_id=self.course_id, topic_id='topic_id', discussion_topic_id="i4x-MITx-999-course-Robot_Super_Course" ) # Add the student to the team so they can post to the commentable. team.add_user(self.student) # create_thread_helper verifies that extra data are passed through to the comments service self.create_thread_helper(mock_request, extra_response_data={'context': ThreadContext.STANDALONE}) def test_delete_thread(self, mock_request): self._set_mock_request_data(mock_request, { "user_id": str(self.student.id), "closed": False, }) test_thread_id = "test_thread_id" request = RequestFactory().post("dummy_url", {"id": test_thread_id}) request.user = self.student request.view_name = "delete_thread" with self.assert_discussion_signals('thread_deleted'): response = views.delete_thread( request, course_id=unicode(self.course.id), thread_id=test_thread_id ) self.assertEqual(response.status_code, 200) self.assertTrue(mock_request.called) def test_delete_comment(self, mock_request): self._set_mock_request_data(mock_request, { "user_id": str(self.student.id), "closed": False, }) test_comment_id = "test_comment_id" request = RequestFactory().post("dummy_url", {"id": test_comment_id}) request.user = self.student request.view_name = "delete_comment" with self.assert_discussion_signals('comment_deleted'): response = views.delete_comment( request, course_id=unicode(self.course.id), comment_id=test_comment_id ) self.assertEqual(response.status_code, 200) self.assertTrue(mock_request.called) args = mock_request.call_args[0] self.assertEqual(args[0], "delete") self.assertTrue(args[1].endswith("/{}".format(test_comment_id))) def _test_request_error(self, view_name, view_kwargs, data, mock_request): """ Submit a request against the given view with the given data and ensure that the result is a 400 error and that no data was posted using mock_request """ self._setup_mock_request(mock_request, include_depth=(view_name == "create_sub_comment")) response = self.client.post(reverse(view_name, kwargs=view_kwargs), data=data) self.assertEqual(response.status_code, 400) for call in mock_request.call_args_list: self.assertEqual(call[0][0].lower(), "get") def test_create_thread_no_title(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": unicode(self.course_id)}, {"body": "foo"}, mock_request ) def test_create_thread_empty_title(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": unicode(self.course_id)}, {"body": "foo", "title": " "}, mock_request ) def test_create_thread_no_body(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": unicode(self.course_id)}, {"title": "foo"}, mock_request ) def test_create_thread_empty_body(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": unicode(self.course_id)}, {"body": " ", "title": "foo"}, mock_request ) def test_update_thread_no_title(self, mock_request): self._test_request_error( "update_thread",
[ " {\"thread_id\": \"dummy\", \"course_id\": unicode(self.course_id)}," ]
1,297
lcc
python
null
f7ee18c4d9156538d22f6663060cd388cce7b7fe2ff560d3
"""SCons.Tool.mslink Tool-specific initialization for the Microsoft linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/mslink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Defaults import SCons.Errors import SCons.Platform.win32 import SCons.Tool import SCons.Tool.msvc import SCons.Tool.msvs import SCons.Util from MSCommon import msvc_setup_env_once, msvc_exists def pdbGenerator(env, target, source, for_signature): try: return ['/PDB:%s' % target[0].attributes.pdb, '/DEBUG'] except (AttributeError, IndexError): return None def _dllTargets(target, source, env, for_signature, paramtp): listCmd = [] dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp) if dll: listCmd.append("/out:%s"%dll.get_string(for_signature)) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: listCmd.append("/implib:%s"%implib.get_string(for_signature)) return listCmd def _dllSources(target, source, env, for_signature, paramtp): listCmd = [] deffile = env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX") for src in source: # Check explicitly for a non-None deffile so that the __cmp__ # method of the base SCons.Util.Proxy class used for some Node # proxies doesn't try to use a non-existent __dict__ attribute. if deffile and src == deffile: # Treat this source as a .def file. listCmd.append("/def:%s" % src.get_string(for_signature)) else: # Just treat it as a generic source file. listCmd.append(src) return listCmd def windowsShlinkTargets(target, source, env, for_signature): return _dllTargets(target, source, env, for_signature, 'SHLIB') def windowsShlinkSources(target, source, env, for_signature): return _dllSources(target, source, env, for_signature, 'SHLIB') def _windowsLdmodTargets(target, source, env, for_signature): """Get targets for loadable modules.""" return _dllTargets(target, source, env, for_signature, 'LDMODULE') def _windowsLdmodSources(target, source, env, for_signature): """Get sources for loadable modules.""" return _dllSources(target, source, env, for_signature, 'LDMODULE') def _dllEmitter(target, source, env, paramtp): """Common implementation of dll emitter.""" SCons.Tool.msvc.validate_vars(env) extratargets = [] extrasources = [] dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp) no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError('A shared library should have exactly one target with the suffix: %s' % env.subst('$%sSUFFIX' % paramtp)) insert_def = env.subst("$WINDOWS_INSERT_DEF") if not insert_def in ['', '0', 0] and \ not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"): # append a def file to the list of sources extrasources.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX")) version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0')) if version_num >= 8.0 and \ (env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)): # MSVC 8 and above automatically generate .manifest files that must be installed extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSSHLIBMANIFESTPREFIX", "WINDOWSSHLIBMANIFESTSUFFIX")) if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb if not no_import_lib and \ not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"): # Append an import library to the list of targets. extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "LIBPREFIX", "LIBSUFFIX")) # and .exp file is created if there are exports from a DLL extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX")) return (target+extratargets, source+extrasources) def windowsLibEmitter(target, source, env): return _dllEmitter(target, source, env, 'SHLIB') def ldmodEmitter(target, source, env): """Emitter for loadable modules. Loadable modules are identical to shared libraries on Windows, but building them is subject to different parameters (LDMODULE*). """ return _dllEmitter(target, source, env, 'LDMODULE') def prog_emitter(target, source, env): SCons.Tool.msvc.validate_vars(env) extratargets = [] extrasources = [] exe = env.FindIxes(target, "PROGPREFIX", "PROGSUFFIX") if not exe: raise SCons.Errors.UserError("An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX")) version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0')) if version_num >= 8.0 and \ (env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)): # MSVC 8 and above automatically generate .manifest files that have to be installed extratargets.append( env.ReplaceIxes(exe, "PROGPREFIX", "PROGSUFFIX", "WINDOWSPROGMANIFESTPREFIX", "WINDOWSPROGMANIFESTSUFFIX")) if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb if version_num >= 11.0 and env.get('PCH', 0): # MSVC 11 and above need the PCH object file to be added to the link line, # otherwise you get link error LNK2011. pchobj = SCons.Util.splitext(str(env['PCH']))[0] + '.obj' # print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj) if pchobj not in extrasources: extrasources.append(pchobj) return (target+extratargets,source+extrasources) def RegServerFunc(target, source, env): if 'register' in env and env['register']: ret = regServerAction([target[0]], [source[0]], env) if ret: raise SCons.Errors.UserError("Unable to register %s" % target[0]) else: print "Registered %s sucessfully" % target[0] return ret return 0 # These are the actual actions run to embed the manifest. # They are only called from the Check versions below. embedManifestExeAction = SCons.Action.Action('$MTEXECOM') embedManifestDllAction = SCons.Action.Action('$MTSHLIBCOM') def embedManifestDllCheck(target, source, env): """Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].abspath + '.manifest' if os.path.exists(manifestSrc):
[ " ret = (embedManifestDllAction) ([target[0]],None,env) " ]
917
lcc
python
null
970d266acb1e58959ce93048f35f32055064fc1053f60014
/** * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.navigator.actions.copied; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.actions.SelectionListenerAction; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.ide.StatusUtil; import org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog; /** * The abstract superclass for actions which invoke commands * implemented in org.eclipse.core.* on a set of selected resources. * * It iterates over all selected resources; errors are collected and * displayed to the user via a problems dialog at the end of the operation. * User requests to cancel the operation are passed along to the core. * <p> * Subclasses must implement the following methods: * <ul> * <li><code>invokeOperation</code> - to perform the operation on one of the * selected resources</li> * <li><code>getOperationMessage</code> - to furnish a title for the progress * dialog</li> * </ul> * </p> * <p> * Subclasses may override the following methods: * <ul> * <li><code>shouldPerformResourcePruning</code> - reimplement to turn off</li> * <li><code>updateSelection</code> - extend to refine enablement criteria</li> * <li><code>getProblemsTitle</code> - reimplement to furnish a title for the * problems dialog</li> * <li><code>getProblemsMessage</code> - reimplement to furnish a message for * the problems dialog</li> * <li><code>run</code> - extend to </li> * </ul> * </p> */ @SuppressWarnings("restriction") public abstract class WorkspaceAction extends SelectionListenerAction { /** * The shell in which to show the progress and problems dialog. */ private final Shell shell; /** * Creates a new action with the given text. * * @param shell the shell (for the modal progress dialog and error messages) * @param text the string used as the text for the action, * or <code>null</code> if there is no text */ protected WorkspaceAction(Shell shell, String text) { super(text); if (shell == null) { throw new IllegalArgumentException(); } this.shell = shell; } /** * Opens an error dialog to display the given message. * <p> * Note that this method must be called from UI thread. * </p> * * @param message the message */ void displayError(String message) { if (message == null) { message = IDEWorkbenchMessages.WorkbenchAction_internalError; } MessageDialog.openError(shell, getProblemsTitle(), message); } /** * Runs <code>invokeOperation</code> on each of the selected resources, reporting * progress and fielding cancel requests from the given progress monitor. * <p> * Note that if an action is running in the background, the same action instance * can be executed multiple times concurrently. This method must not access * or modify any mutable state on action class. * * @param monitor a progress monitor * @return The result of the execution */ final IStatus execute(List resources, IProgressMonitor monitor) { MultiStatus errors = null; //1FTIMQN: ITPCORE:WIN - clients required to do too much iteration work if (shouldPerformResourcePruning()) { resources = pruneResources(resources); } // 1FV0B3Y: ITPUI:ALL - sub progress monitors granularity issues monitor.beginTask("", resources.size() * 1000); //$NON-NLS-1$ // Fix for bug 31768 - Don't provide a task name in beginTask // as it will be appended to each subTask message. Need to // call setTaskName as its the only was to assure the task name is // set in the monitor (see bug 31824) monitor.setTaskName(getOperationMessage()); Iterator resourcesEnum = resources.iterator(); try { while (resourcesEnum.hasNext()) { IResource resource = (IResource) resourcesEnum.next(); try { // 1FV0B3Y: ITPUI:ALL - sub progress monitors granularity issues invokeOperation(resource, new SubProgressMonitor(monitor, 1000)); } catch (CoreException e) { errors = recordError(errors, e); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } return errors == null ? Status.OK_STATUS : errors; } finally { monitor.done(); } } /** * Returns the string to display for this action's operation. * <p> * Note that this hook method is invoked in a non-UI thread. * </p> * <p> * Subclasses must implement this method. * </p> * * @return the message * * @since 3.1 */ protected abstract String getOperationMessage(); /** * Returns the string to display for this action's problems dialog. * <p> * The <code>WorkspaceAction</code> implementation of this method returns a * vague message (localized counterpart of something like "The following * problems occurred."). Subclasses may reimplement to provide something more * suited to the particular action. * </p> * * @return the problems message * * @since 3.1 */ protected String getProblemsMessage() { return IDEWorkbenchMessages.WorkbenchAction_problemsMessage; } /** * Returns the title for this action's problems dialog. * <p> * The <code>WorkspaceAction</code> implementation of this method returns a * generic title (localized counterpart of "Problems"). Subclasses may * reimplement to provide something more suited to the particular action. * </p> * * @return the problems dialog title * * @since 3.1 */ protected String getProblemsTitle() { return IDEWorkbenchMessages.WorkspaceAction_problemsTitle; } /** * Returns the shell for this action. This shell is used for the modal progress * and error dialogs. * * @return the shell */ Shell getShell() { return shell; } /** * Performs this action's operation on each of the selected resources, reporting * progress to, and fielding cancel requests from, the given progress monitor. * <p> * Note that this method is invoked in a non-UI thread. * </p> * <p> * Subclasses must implement this method. * </p> * * @param resource one of the selected resources * @param monitor a progress monitor * @exception CoreException if the operation fails * * @since 3.1 */ protected abstract void invokeOperation(IResource resource, IProgressMonitor monitor) throws CoreException; /** * Returns whether the given resource is a descendent of any of the resources * in the given list. * * @param resources the list of resources (element type: <code>IResource</code>) * @param child the resource to check * @return <code>true</code> if <code>child</code> is a descendent of any of the * elements of <code>resources</code> */ boolean isDescendent(List resources, IResource child) { IResource parent = child.getParent(); return parent != null && (resources.contains(parent) || isDescendent(resources, parent)); } /** * Performs pruning on the given list of resources, as described in * <code>shouldPerformResourcePruning</code>. * * @param resourceCollection the list of resources (element type: * <code>IResource</code>) * @return the list of resources (element type: <code>IResource</code>) * after pruning. * @see #shouldPerformResourcePruning */ @SuppressWarnings("unchecked") List pruneResources(List resourceCollection) { List prunedList = new ArrayList(resourceCollection); Iterator elementsEnum = prunedList.iterator(); while (elementsEnum.hasNext()) { IResource currentResource = (IResource) elementsEnum.next(); if (isDescendent(prunedList, currentResource)) { elementsEnum.remove(); //Removes currentResource } } return prunedList; } /** * Records the core exception to be displayed to the user * once the action is finished. * * @param error a <code>CoreException</code> */ MultiStatus recordError(MultiStatus errors, CoreException error) { if (errors == null) { errors = new MultiStatus(IDEWorkbenchPlugin.IDE_WORKBENCH, IStatus.ERROR, getProblemsMessage(), null); } errors.merge(error.getStatus()); return errors; } /** * The <code>CoreWrapperAction</code> implementation of this <code>IAction</code> * method uses a <code>ProgressMonitorDialog</code> to run the operation. The * operation calls <code>execute</code> (which, in turn, calls * <code>invokeOperation</code>). Afterwards, any <code>CoreException</code>s * encountered while running the operation are reported to the user via a * problems dialog. * <p> * Subclasses may extend this method. * </p> */ public void run() { final IStatus[] errorStatus = new IStatus[1]; try {
[ " WorkspaceModifyOperation op = new WorkspaceModifyOperation() {" ]
1,208
lcc
java
null
028fac90b8ce9bb8e36ca503af93a07b449aafbe6570e486
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans.steps.aggregaterows; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Aggregates rows * * @author Matt * @since 2-jun-2003 */ public class AggregateRows extends BaseStep implements StepInterface { private static Class<?> PKG = AggregateRows.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private AggregateRowsMeta meta; private AggregateRowsData data; public AggregateRows(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private synchronized void AddAggregate(RowMetaInterface rowMeta, Object[] r) throws KettleValueException { for (int i=0;i<data.fieldnrs.length;i++) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fieldnrs[i]); Object valueData = r[data.fieldnrs[i]]; if (!valueMeta.isNull(valueData)) { data.counts[i]++; // only count non-zero values! switch(meta.getAggregateType()[i]) { case AggregateRowsMeta.TYPE_AGGREGATE_SUM: case AggregateRowsMeta.TYPE_AGGREGATE_AVERAGE: { Double number = valueMeta.getNumber(valueData); if (data.values[i]==null) { data.values[i]=number; } else { data.values[i] = new Double( ((Double)data.values[i]).doubleValue() + number.doubleValue() ); } } break; case AggregateRowsMeta.TYPE_AGGREGATE_MIN: { if (data.values[i]==null) { data.values[i]=valueData; } else { if (valueMeta.compare(data.values[i], valueData)<0) data.values[i]=valueData; } } break; case AggregateRowsMeta.TYPE_AGGREGATE_MAX: { if (data.values[i]==null) { data.values[i]=valueData; } else { if (valueMeta.compare(data.values[i], valueData)>0) data.values[i]=valueData; } } break; case AggregateRowsMeta.TYPE_AGGREGATE_NONE: case AggregateRowsMeta.TYPE_AGGREGATE_FIRST: if (data.values[i]==null) { data.values[i]=valueData; } break; case AggregateRowsMeta.TYPE_AGGREGATE_LAST: data.values[i]=valueData; break; } } switch(meta.getAggregateType()[i]) { case AggregateRowsMeta.TYPE_AGGREGATE_FIRST_NULL: // First value, EVEN if it's NULL: if (data.values[i]==null) { data.values[i]=valueData; } break; case AggregateRowsMeta.TYPE_AGGREGATE_LAST_NULL: // Last value, EVEN if it's NULL: data.values[i]=valueData; break; default: break; } } } // End of the road, build a row to output! private synchronized Object[] buildAggregate() { Object[] agg = RowDataUtil.allocateRowData(data.outputRowMeta.size()); for (int i=0;i<data.fieldnrs.length;i++) { switch(meta.getAggregateType()[i]) { case AggregateRowsMeta.TYPE_AGGREGATE_SUM: case AggregateRowsMeta.TYPE_AGGREGATE_MIN: case AggregateRowsMeta.TYPE_AGGREGATE_MAX: case AggregateRowsMeta.TYPE_AGGREGATE_FIRST: case AggregateRowsMeta.TYPE_AGGREGATE_LAST: case AggregateRowsMeta.TYPE_AGGREGATE_NONE: case AggregateRowsMeta.TYPE_AGGREGATE_FIRST_NULL: // First value, EVEN if it's NULL: case AggregateRowsMeta.TYPE_AGGREGATE_LAST_NULL: // Last value, EVEN if it's NULL: agg[i]=data.values[i]; break; case AggregateRowsMeta.TYPE_AGGREGATE_COUNT: agg[i]=new Double(data.counts[i]); break; case AggregateRowsMeta.TYPE_AGGREGATE_AVERAGE: agg[i] = new Double( ((Double)data.values[i]).doubleValue() / data.counts[i] ); break; default: break; } } return agg; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(AggregateRowsMeta)smi; data=(AggregateRowsData)sdi; Object[] r=getRow(); // get row, set busy! if (r==null) // no more input to be expected... { Object[] agg = buildAggregate(); // build a resume putRow(data.outputRowMeta, agg); setOutputDone(); return false; } if (first) { first=false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); for (int i=0;i<meta.getFieldName().length;i++) { data.fieldnrs[i]=getInputRowMeta().indexOfValue(meta.getFieldName()[i]); if (data.fieldnrs[i]<0) { logError(BaseMessages.getString(PKG, "AggregateRows.Log.CouldNotFindField",meta.getFieldName()[i])); //$NON-NLS-1$ //$NON-NLS-2$ setErrors(1); stopAll(); return false; } data.counts[i]=0L; } } AddAggregate(getInputRowMeta(), r); if (checkFeedback(getLinesRead())) if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "AggregateRows.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$ return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(AggregateRowsMeta)smi; data=(AggregateRowsData)sdi;
[ "\t\tif (super.init(smi, sdi))" ]
521
lcc
java
null
6a7e2d3329ea2bdb0c4bdac5aee494e87cdfc588799e3f78
# coding: utf-8 # python from datetime import datetime, time, timedelta # 3rd-party from freezegun import freeze_time import pytest # this app from timetra.diary import utils def test_extract_components(): f = utils.extract_date_time_bounds ## simple since, until assert f('18:55..19:30') == {'since': '18:55', 'until': '19:30'} assert f('00:55..01:30') == {'since': '00:55', 'until': '01:30'} # same, semicolon omitted assert f('0055..0130') == {'since': '0055', 'until': '0130'} # same, leading zeroes omitted assert f('0:55..1:30') == {'since': '0:55', 'until': '1:30'} assert f('55..130') == {'since': '55', 'until': '130'} # missing hour is considered 0 AM, not current one assert f('5..7') == {'since': '5', 'until': '7'} # an ugly but probably valid case assert f(':5..:7') == {'since': ':5', 'until': ':7'} ## defaults # since last until given assert f('..130') == {'until': '130'} # since given until now assert f('55..') == {'since': '55'} # since last until now assert f('..') == {} assert f('') == {} ## relative assert f('12:30..+5') == {'since': '12:30', 'until': '+5'} assert f('12:30..-5') == {'since': '12:30', 'until': '-5'} assert f('+5..12:30') == {'since': '+5', 'until': '12:30'} assert f('-5..12:30') == {'since': '-5', 'until': '12:30'} # both relative assert f('-3..-2') == {'since': '-3', 'until': '-2'} assert f('+5..+8') == {'since': '+5', 'until': '+8'} assert f('-9..+5') == {'since': '-9', 'until': '+5'} assert f('+2..-5') == {'since': '+2', 'until': '-5'} ## ultrashortcuts assert f('1230+5') == {'since': '1230', 'until': '+5'} with pytest.raises(ValueError): f('1230-5') assert f('+5') == {'since': '+5'} assert f('-5') == {'since': '-5'} def test_bounds_normalize_component(): f = utils.string_to_time_or_delta assert f('15:37') == time(15, 37) assert f('05:37') == time(5, 37) assert f('5:37') == time(5, 37) assert f('1537') == time(15, 37) assert f('537') == time(5, 37) assert f('37') == time(0, 37) assert f('7') == time(0, 7) assert f('+5') == timedelta(hours=0, minutes=5) assert f('+50') == timedelta(hours=0, minutes=50) assert f('+250') == timedelta(hours=2, minutes=50) assert f('+1250') == timedelta(hours=12, minutes=50) with pytest.raises(AssertionError): assert f('+70') assert f('-5') == timedelta(hours=0, minutes=-5) assert f('-50') == timedelta(hours=0, minutes=-50) assert f('-250') == timedelta(hours=-2, minutes=-50) assert f('-1250') == timedelta(hours=-12, minutes=-50) with pytest.raises(AssertionError): assert f('-70') assert f(None) == None def test_bounds_normalize_group(): f = utils.normalize_group last = datetime(2014, 1, 31, 22, 55) now = datetime(2014, 2, 1, 21, 30) # f(last, since, until, now) assert f(last, None, None, now) == ( datetime(2014, 1, 31, 22, 55), datetime(2014, 2, 1, 21, 30), ) assert f(last, None, time(20,0), now) == ( datetime(2014, 1, 31, 22, 55), datetime(2014, 2, 1, 20, 0), ) assert f(last, time(12,0), None, now) == ( datetime(2014, 2, 1, 12, 0), datetime(2014, 2, 1, 21, 30), ) assert f(last, time(23,0), time(20,0), now) == ( datetime(2014, 1, 31, 23, 0), datetime(2014, 2, 1, 20, 0), ) assert f(last, timedelta(minutes=5), time(20,0), now) == ( datetime(2014, 1, 31, 23, 0), datetime(2014, 2, 1, 20, 0), ) assert f(last, time(23,0), timedelta(minutes=5), now) == ( datetime(2014, 1, 31, 23, 0), datetime(2014, 1, 31, 23, 5), ) assert f(last, timedelta(minutes=-5), time(20,0), now) == ( datetime(2014, 2, 1, 19, 55), datetime(2014, 2, 1, 20, 0), ) assert f(last, time(23,0), timedelta(minutes=-5), now) == ( datetime(2014, 1, 31, 23, 0), datetime(2014, 2, 1, 21, 25), ) assert f(last, timedelta(minutes=-10), timedelta(minutes=+3), now) == ( datetime(2014, 2, 1, 21, 20), datetime(2014, 2, 1, 21, 23), ) # regressions for "00:00" vs `None`: assert f(last, time(), time(5), now) == ( datetime(2014, 2, 1, 0, 0), datetime(2014, 2, 1, 5, 0), ) assert f(last, timedelta(minutes=-15), time(), now) == ( datetime(2014, 1, 31, 23, 45), datetime(2014, 2, 1, 0, 0), ) @freeze_time('2014-01-31 19:51:37.123456') def test_parse_bounds(): f = utils.parse_date_time_bounds d = datetime now = d.now() last = d(2014,1,30, 22,15,45, 987654) last_rounded_fwd = d(2014,1,30, 22,16) # leading/trailing spaces are ignored assert f(' 18:55..19:30 ', last) == (d(2014,1,31, 18,55), d(2014,1,31, 19,30)) assert f('18:55..19:30', last) == (d(2014,1,31, 18,55), d(2014,1,31, 19,30)) assert f('00:55..01:30', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) # same, semicolon omitted assert f( '0055..0130', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) # same, leading zeroes omitted assert f( '0:55..1:30', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) assert f( '55..130', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) assert f( '..130', last) == (last_rounded_fwd, d(2014,1,31, 1,30)) # missing hour is considered 0 AM, not current one assert f( '5..7', last) == (d(2014,1,31, 0, 5), d(2014,1,31, 0, 7)) # an ugly but probably valid case assert f( ':5..:7', last) == (d(2014,1,31, 0, 5), d(2014,1,31, 0, 7)) ## defaults # since last until given assert f('..130', last) == (last_rounded_fwd, d(2014,1,31, 1,30)) # since given until now assert f('130..', last) == (d(2014,1,31, 1,30), now) # since last until now assert f('..', last) == (last_rounded_fwd, now) assert f('', last) == (last_rounded_fwd, now) ## relative assert f('12:30..+5', last) == (d(2014,1,31, 12,30), d(2014,1,31, 12,35)) assert f('12:30..-5', last) == (d(2014,1,31, 12,30), d(2014,1,31, 19,47)) assert f('+5..12:30', last) == (d(2014,1,30, 22,21), d(2014,1,31, 12,30)) assert f('-5..12:30', last) == (d(2014,1,31, 12,25), d(2014,1,31, 12,30)) assert f('..-5', last) == (last_rounded_fwd, d(2014,1,31, 19,47)) assert f('..+5', last) == (last_rounded_fwd, d(2014,1,30, 22,21)) assert f('+5..', last) == (d(2014,1,30, 22,21), now) assert f('-5..', last) == (d(2014,1,31, 19,47), now) # both relative # # XXX the `-3..-2` case seems counterintuitive. # is "{until-x}..{now-y}" really better than "{now-x}..{now-y}"? # # (?) assert f('-3..-2', last) == (d(2014,1,31, 19,48), d(2014,1,31, 19,49)) assert f('-3..-2', last) == (d(2014,1,31, 19,47), d(2014,1,31, 19,50)) assert f('+5..+8', last) == (d(2014,1,30, 22,21), d(2014,1,30, 22,29)) assert f('-9..+5', last) == (d(2014,1,31, 19,43), d(2014,1,31, 19,48)) assert f('+2..-5', last) == (d(2014,1,30, 22,18), d(2014,1,31, 19,47)) ## ultrashortcuts assert f('1230+5', last) == (d(2014,1,31, 12,30), d(2014,1,31, 12,35)) with pytest.raises(ValueError): f('1230-5', last) # `delta` = `delta..` assert f('+5', last) == (d(2014,1,30, 22,21), now) assert f('-5', last) == (d(2014,1,31, 19,47), now) @freeze_time('2014-01-31 19:30:00') def test_parse_bounds_rounding(): f = utils.parse_date_time_bounds d = datetime until = d(2014,1,31, 12,00) # When `since` is calculated from the previous fact, it is rounded forward # to half a minute. This ensures that: # # a) the precision is lowered to a sane level and some overprecise tail # of one fact's `until` field (seconds and microseconds) is not carried # on and on by a series of consecutive facts. # # b) the facts don't overlap after correction. # assert f('..12:00', last=d(2014,1,30, 22,15, 0, 0)) == \ (d(2014,1,30, 22,15, 0, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15, 1, 0)) == \ (d(2014,1,30, 22,15,30, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15,15, 0)) == \ (d(2014,1,30, 22,15,30, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15,30, 0)) == \ (d(2014,1,30, 22,15,30, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15,31, 0)) == \ (d(2014,1,30, 22,16,00, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15,30, 123456)) == \ (d(2014,1,30, 22,16, 0, 0), until) assert f('..12:00', last=d(2014,1,30, 22,15,59, 0)) == \ (d(2014,1,30, 22,16, 0, 0), until) # same applies to `since` calculated from `now`: we also round forwards last = d(2014,1,31) # does not matter here with freeze_time('2014-01-31 19:30:00'): assert f('-5', last) == (d(2014,1,31, 19,25, 0, 0), d.now()) with freeze_time('2014-01-31 19:30:01'): assert f('-5', last) == (d(2014,1,31, 19,25, 30, 0), d.now()) with freeze_time('2014-01-31 19:30:00.123456'): assert f('-5', last) == (d(2014,1,31, 19,25, 30, 0), d.now()) with freeze_time('2014-01-31 19:30:30.123456'): assert f('-5', last) == (d(2014,1,31, 19,26, 0, 0), d.now()) @pytest.mark.xfail @freeze_time('2014-01-31 19:51:37.123456') def test_parse_bounds_for_a_date_in_the_past(): f = utils.parse_date_time_bounds d = datetime now = d.now() last = d(2014,1,15, 22,15,45, 987654) last_rounded_fwd = d(2014,1,15, 22,16) # leading/trailing spaces are ignored assert f(' 18:55..19:30 ', last) == (d(2014,1,31, 18,55), d(2014,1,31, 19,30)) assert f('18:55..19:30', last) == (d(2014,1,31, 18,55), d(2014,1,31, 19,30)) assert f('00:55..01:30', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) # same, semicolon omitted assert f( '0055..0130', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) # same, leading zeroes omitted assert f( '0:55..1:30', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) assert f( '55..130', last) == (d(2014,1,31, 0,55), d(2014,1,31, 1,30)) assert f( '..130', last) == (last_rounded_fwd, d(2014,1,31, 1,30)) # missing hour is considered 0 AM, not current one assert f( '5..7', last) == (d(2014,1,31, 0, 5), d(2014,1,31, 0, 7)) # an ugly but probably valid case assert f( ':5..:7', last) == (d(2014,1,31, 0, 5), d(2014,1,31, 0, 7)) ## defaults # since last until given assert f('..130', last) == (last_rounded_fwd, d(2014,1,31, 1,30)) # since given until now assert f('130..', last) == (d(2014,1,31, 1,30), now) # since last until now assert f('..', last) == (last_rounded_fwd, now) assert f('', last) == (last_rounded_fwd, now) ## relative assert f('12:30..+5', last) == (d(2014,1,31, 12,30), d(2014,1,31, 12,35)) assert f('12:30..-5', last) == (d(2014,1,31, 12,30), d(2014,1,31, 19,47)) assert f('+5..12:30', last) == (d(2014,1,30, 22,21), d(2014,1,31, 12,30)) assert f('-5..12:30', last) == (d(2014,1,31, 12,25), d(2014,1,31, 12,30)) assert f('..-5', last) == (last_rounded_fwd, d(2014,1,31, 19,47)) assert f('..+5', last) == (last_rounded_fwd, d(2014,1,30, 22,21))
[ " assert f('+5..', last) == (d(2014,1,30, 22,21), now)" ]
1,349
lcc
python
null
6ed48ea127a5e3b151e2448bd64dd53c427087b78346f68e
// This is a MOD of Nerun's Distro SpawnGen (Engine r117) that works with default runuo proximity spawners. using System; using System.Collections.Generic; using System.IO; using Server.Mobiles; using Server.Commands; namespace Server { public class SpawnGenerator { private static int m_Count; private static int m_MapOverride = -1; private static int m_IDOverride = -1; private static double m_MinTimeOverride = -1; private static double m_MaxTimeOverride = -1; private const bool TotalRespawn = false; private const int Team = 0; public static void Initialize() { CommandSystem.Register("SpawnGen", AccessLevel.Administrator, new CommandEventHandler(SpawnGen_OnCommand)); } [Usage("SpawnGen [<filename>]|[unload <id>]|[remove <region>|<rect>]|[save <region>|<rect>][savebyhand][cleanfacet]")] [Description("Complex command, it generate and remove spawners.")] private static void SpawnGen_OnCommand(CommandEventArgs e) { //wrong use if (e.ArgString == null || e.ArgString == "") { e.Mobile.SendMessage("Usage: SpawnGen [<filename>]|[remove <region>|<rect>|<ID>]|[save <region>|<rect>|<ID>]"); } //[spawngen remove and [spawngen remove region else if (e.Arguments[0].ToLower() == "remove" && e.Arguments.Length == 2) { Remove(e.Mobile, e.Arguments[1].ToLower()); } //[spawngen remove x1 y1 x2 y2 else if (e.Arguments[0].ToLower() == "remove" && e.Arguments.Length == 5) { int x1 = Utility.ToInt32(e.Arguments[1]); int y1 = Utility.ToInt32(e.Arguments[2]); int x2 = Utility.ToInt32(e.Arguments[3]); int y2 = Utility.ToInt32(e.Arguments[4]); RemoveByCoord(e.Mobile, x1, y1, x2, y2); } //[spawngen remove else if (e.ArgString.ToLower() == "remove") { Remove(e.Mobile, ""); } //[spawngen save and [spawngen save region else if (e.Arguments[0].ToLower() == "save" && e.Arguments.Length == 2) { Save(e.Mobile, e.Arguments[1].ToLower()); } //[spawngen savebyhand else if (e.Arguments[0].ToLower() == "savebyhand") { SaveByHand(); } //[spawngen cleanfacet else if (e.Arguments[0].ToLower() == "cleanfacet") { CleanFacet(e.Mobile); } ////[spawngen save x1 y1 x2 y2 else if (e.Arguments[0].ToLower() == "save" && e.Arguments.Length == 5) { int x1 = Utility.ToInt32(e.Arguments[1]); int y1 = Utility.ToInt32(e.Arguments[2]); int x2 = Utility.ToInt32(e.Arguments[3]); int y2 = Utility.ToInt32(e.Arguments[4]); SaveByCoord(e.Mobile, x1, y1, x2, y2); } //[spawngen save else if (e.ArgString.ToLower() == "save") { Save(e.Mobile, ""); } else { Parse(e.Mobile, e.ArgString); } } public static void Talk(string alfa) { World.Broadcast(0x35, true, "Spawns are being {0}, please wait.", alfa); } public static string GetRegion(Item item) { Region re = Region.Find(item.Location, item.Map); string regname = re.ToString().ToLower(); return regname; } //[spawngen remove and [spawngen remove region private static void Remove(Mobile from, string region) { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); string prefix = Server.Commands.CommandSystem.Prefix; if (region == null || region == "") { CommandSystem.Handle(from, String.Format("{0}Global remove where IntelliSpawner", prefix)); } else { foreach (Item itemdel in World.Items.Values) { if (itemdel is IntelliSpawner && itemdel.Map == from.Map) { if (GetRegion(itemdel) == region) { itemtodo.Add(itemdel); count += 1; } } } GenericRemove(itemtodo, count, aTime); } } //[spawngen remove x1 y1 x2 y2 private static void RemoveByCoord(Mobile from, int x1, int y1, int x2, int y2) { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); foreach (Item itemremove in World.Items.Values) { if (itemremove is IntelliSpawner && ((itemremove.X >= x1 && itemremove.X <= x2) && (itemremove.Y >= y1 && itemremove.Y <= y2) && itemremove.Map == from.Map)) { itemtodo.Add(itemremove); count += 1; } } GenericRemove(itemtodo, count, aTime); } //[spawngen cleanfacet public static void CleanFacet(Mobile from) { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); foreach (Item itemremove in World.Items.Values) { if (itemremove is IntelliSpawner && itemremove.Map == from.Map && itemremove.Parent == null) { itemtodo.Add(itemremove); count += 1; } } GenericRemove(itemtodo, count, aTime); } private static void GenericRemove(List<Item> colecao, int count, DateTime aTime) { if (colecao.Count == 0) { World.Broadcast(0x35, true, "There are no IntelliSpawners to be removed."); } else { Talk("removed"); foreach (Item item in colecao) { item.Delete(); } DateTime bTime = DateTime.Now; World.Broadcast(0x35, true, "{0} IntelliSpawners have been removed in {1:F1} seconds.", count, (bTime - aTime).TotalSeconds); } } //[spawngen save and [spawngen save region private static void Save(Mobile from, string region) { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); string mapanome = region; if (region == "") mapanome = "Spawns"; foreach (Item itemsave in World.Items.Values) { if (itemsave is IntelliSpawner && (region == null || region == "")) { itemtodo.Add(itemsave); count += 1; } else if (itemsave is IntelliSpawner && itemsave.Map == from.Map) { if (GetRegion(itemsave) == region) { itemtodo.Add(itemsave); count += 1; } } } GenericSave(itemtodo, mapanome, count, aTime); } //[spawngen SaveByHand private static void SaveByHand() { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); string mapanome = "SpawnsByHand"; foreach (Item itemsave in World.Items.Values) { itemtodo.Add(itemsave); count += 1; } GenericSave(itemtodo, mapanome, count, aTime); } //[spawngen save x1 y1 x2 y2 private static void SaveByCoord(Mobile from, int x1, int y1, int x2, int y2) { DateTime aTime = DateTime.Now; int count = 0; List<Item> itemtodo = new List<Item>(); string mapanome = "SpawnsByCoords"; foreach (Item itemsave in World.Items.Values) { if (itemsave is IntelliSpawner && ((itemsave.X >= x1 && itemsave.X <= x2) && (itemsave.Y >= y1 && itemsave.Y <= y2) && itemsave.Map == from.Map)) { itemtodo.Add(itemsave); count += 1; } } GenericSave(itemtodo, mapanome, count, aTime); } private static void GenericSave(List<Item> colecao, string mapa, int count, DateTime startTime) { List<Item> itemssave = new List<Item>(colecao); string mapanome = mapa; if (itemssave.Count == 0) { World.Broadcast(0x35, true, "There are no IntelliSpawners to be saved."); } else { Talk("saved"); if (!Directory.Exists("Data/Nerun's Distro/Spawns")) Directory.CreateDirectory("Data/Nerun's Distro/Spawns"); string escreva = "Data/Nerun's Distro/Spawns/" + mapanome + ".map"; using (StreamWriter op = new StreamWriter(escreva)) { foreach (IntelliSpawner itemsave2 in itemssave) { int mapnumber = 0; switch (itemsave2.Map.ToString()) { case "Felucca": mapnumber = 1; break; case "Trammel": mapnumber = 2; break; case "Ilshenar": mapnumber = 3; break; case "Malas": mapnumber = 4; break; case "Tokuno": mapnumber = 5; break; case "TerMur": mapnumber = 6; break; default: mapnumber = 7; Console.WriteLine("Monster Parser: Warning, unknown map {0}", itemsave2.Map); break; } string timer1a = itemsave2.MinDelay.ToString(); string[] timer1b = timer1a.Split(':'); //Broke the string hh:mm:ss in an array (hh, mm, ss) int timer1c = (Utility.ToInt32(timer1b[0]) * 60) + Utility.ToInt32(timer1b[1]); //multiply hh * 60 to find mm, then add mm string timer1d = timer1c.ToString(); if (Utility.ToInt32(timer1b[0]) == 0 && Utility.ToInt32(timer1b[1]) == 0) //If hh and mm are 0, use seconds, else drop ss timer1d = Utility.ToInt32(timer1b[2]) + "s"; string timer2a = itemsave2.MaxDelay.ToString(); string[] timer2b = timer2a.Split(':'); int timer2c = (Utility.ToInt32(timer2b[0]) * 60) + Utility.ToInt32(timer2b[1]); string timer2d = timer2c.ToString(); if (Utility.ToInt32(timer2b[0]) == 0 && Utility.ToInt32(timer2b[1]) == 0) timer2d = Utility.ToInt32(timer2b[2]) + "s"; string towrite = ""; string towriteA = ""; string towriteB = ""; string towriteC = ""; string towriteD = ""; string towriteE = ""; if (itemsave2.SpawnNames.Count > 0) towrite = itemsave2.SpawnNames[0].ToString(); for (int i = 1; i < itemsave2.SpawnNames.Count; ++i) { towrite = towrite + ":" + itemsave2.SpawnNames[i].ToString(); } op.WriteLine("*|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}|{14}|{15}|{16}|{17}|{18}|{19}|{20}", towrite, towriteA, towriteB, towriteC, towriteD, towriteE, itemsave2.X, itemsave2.Y, itemsave2.Z, mapnumber, timer1d, timer2d, itemsave2.HomeRange, itemsave2.WalkingRange, 1, itemsave2.Count, 0, 0, 0, 0, 0); } } DateTime endTime = DateTime.Now; World.Broadcast(0x35, true, "{0} spawns have been saved. The entire process took {1:F1} seconds.", count, (endTime - startTime).TotalSeconds); } } public static void Parse(Mobile from, string filename) { string monster_path1 = Path.Combine(Core.BaseDirectory, "Data/Nerun's Distro/Spawns"); string monster_path = Path.Combine(monster_path1, filename); m_Count = 0; if (File.Exists(monster_path)) { from.SendMessage("Spawning {0}...", filename); m_MapOverride = -1; m_IDOverride = -1; m_MinTimeOverride = -1; m_MaxTimeOverride = -1; using (StreamReader ip = new StreamReader(monster_path)) { string line; while ((line = ip.ReadLine()) != null) { string[] split = line.Split('|'); string[] splitA = line.Split(' '); if (splitA.Length == 2) { if (splitA[0].ToLower() == "overridemap") m_MapOverride = Utility.ToInt32(splitA[1]); if (splitA[0].ToLower() == "overrideid") m_IDOverride = Utility.ToInt32(splitA[1]); if (splitA[0].ToLower() == "overridemintime") m_MinTimeOverride = Utility.ToDouble(splitA[1]); if (splitA[0].ToLower() == "overridemaxtime") m_MaxTimeOverride = Utility.ToDouble(splitA[1]); } if (split.Length < 19) continue; switch (split[0].ToLower()) { //Comment Line case "##": break; //Place By class case "*": PlaceNPC(split[2].Split(':'), split[3].Split(':'), split[4].Split(':'), split[5].Split(':'), split[6].Split(':'), split[7], split[8], split[9], split[10], split[11], split[12], split[14], split[13], split[15], split[16], split[17], split[18], split[19], split[20], split[21], split[1].Split(':')); break; //Place By Type case "r": PlaceNPC(split[2].Split(':'), split[3].Split(':'), split[4].Split(':'), split[5].Split(':'), split[6].Split(':'), split[7], split[8], split[9], split[10], split[11], split[12], split[14], split[13], split[15], split[16], split[17], split[18], split[19], split[20], split[1], "bloodmoss", "sulfurousash", "spiderssilk", "mandrakeroot", "gravedust", "nightshade", "ginseng", "garlic", "batwing", "pigiron", "noxcrystal", "daemonblood", "blackpearl"); break; } } } m_MapOverride = -1; m_IDOverride = -1; m_MinTimeOverride = -1; m_MaxTimeOverride = -1; from.SendMessage("Done, added {0} spawners", m_Count); } else { from.SendMessage("{0} not found!", monster_path); } } public static void PlaceNPC(string[] fakespawnsA, string[] fakespawnsB, string[] fakespawnsC, string[] fakespawnsD, string[] fakespawnsE, string sx, string sy, string sz, string sm, string smintime, string smaxtime, string swalkingrange, string shomerange, string sspawnid, string snpccount, string sfakecountA, string sfakecountB, string sfakecountC, string sfakecountD, string sfakecountE, params string[] types) { if (types.Length == 0) return; int x = Utility.ToInt32(sx); int y = Utility.ToInt32(sy); int z = Utility.ToInt32(sz); int map = Utility.ToInt32(sm); //MinTime string samintime = smintime; if (smintime.Contains("s") || smintime.Contains("m") || smintime.Contains("h")) samintime = smintime.Remove(smintime.Length - 1); double dmintime = Utility.ToDouble(samintime); if (m_MinTimeOverride != -1) dmintime = m_MinTimeOverride; TimeSpan mintime = TimeSpan.FromMinutes(dmintime); if (smintime.Contains("s")) mintime = TimeSpan.FromSeconds(dmintime); else if (smintime.Contains("m")) mintime = TimeSpan.FromMinutes(dmintime); else if (smintime.Contains("h")) mintime = TimeSpan.FromHours(dmintime); //MaxTime string samaxtime = smaxtime; if (smaxtime.Contains("s") || smaxtime.Contains("m") || smaxtime.Contains("h")) samaxtime = smaxtime.Remove(smaxtime.Length - 1); double dmaxtime = Utility.ToDouble(samaxtime); if (m_MaxTimeOverride != -1) { if (m_MaxTimeOverride < dmintime) dmaxtime = dmintime; else dmaxtime = m_MaxTimeOverride; } TimeSpan maxtime = TimeSpan.FromMinutes(dmaxtime); if (smaxtime.Contains("s")) maxtime = TimeSpan.FromSeconds(dmaxtime); else if (smaxtime.Contains("m")) maxtime = TimeSpan.FromMinutes(dmaxtime);
[ " else if (smaxtime.Contains(\"h\"))" ]
1,478
lcc
csharp
null
616a17b42a836d0cbc6def391f1ad2c62a6951e8da18f14c
""" High-level QEMU test utility functions. This module is meant to reduce code size by performing common test procedures. Generally, code here should look like test code. More specifically: - Functions in this module should raise exceptions if things go wrong - Functions in this module typically use functions and classes from lower-level modules (e.g. utils_misc, qemu_vm, aexpect). - Functions in this module should not be used by lower-level modules. - Functions in this module should be used in the right context. For example, a function should not be used where it may display misleading or inaccurate info or debug messages. :copyright: 2008-2013 Red Hat Inc. """ import os import re import six import time import logging from functools import reduce from avocado.core import exceptions from avocado.utils import path as utils_path from avocado.utils import process from avocado.utils import cpu as cpuutil from virttest import error_context from virttest import utils_misc from virttest import qemu_monitor from virttest.qemu_devices import qdevices from virttest.staging import utils_memory from virttest.compat_52lts import decode_to_text def guest_active(vm): o = vm.monitor.info("status") if isinstance(o, six.string_types): return "status: running" in o else: if "status" in o: return o.get("status") == "running" else: return o.get("running") def get_numa_status(numa_node_info, qemu_pid, debug=True): """ Get the qemu process memory use status and the cpu list in each node. :param numa_node_info: Host numa node information :type numa_node_info: NumaInfo object :param qemu_pid: process id of qemu :type numa_node_info: string :param debug: Print the debug info or not :type debug: bool :return: memory and cpu list in each node :rtype: tuple """ node_list = numa_node_info.online_nodes qemu_memory = [] qemu_cpu = [] cpus = cpuutil.get_pid_cpus(qemu_pid) for node_id in node_list: qemu_memory_status = utils_memory.read_from_numa_maps(qemu_pid, "N%d" % node_id) memory = sum([int(_) for _ in list(qemu_memory_status.values())]) qemu_memory.append(memory) cpu = [_ for _ in cpus if _ in numa_node_info.nodes[node_id].cpus] qemu_cpu.append(cpu) if debug: logging.debug("qemu-kvm process using %s pages and cpu %s in " "node %s" % (memory, " ".join(cpu), node_id)) return (qemu_memory, qemu_cpu) def pin_vm_threads(vm, node): """ Pin VM threads to single cpu of a numa node :param vm: VM object :param node: NumaNode object """ if len(vm.vcpu_threads) + len(vm.vhost_threads) < len(node.cpus): for i in vm.vcpu_threads: logging.info("pin vcpu thread(%s) to cpu(%s)" % (i, node.pin_cpu(i))) for i in vm.vhost_threads: logging.info("pin vhost thread(%s) to cpu(%s)" % (i, node.pin_cpu(i))) elif (len(vm.vcpu_threads) <= len(node.cpus) and len(vm.vhost_threads) <= len(node.cpus)): for i in vm.vcpu_threads: logging.info("pin vcpu thread(%s) to cpu(%s)" % (i, node.pin_cpu(i))) for i in vm.vhost_threads: logging.info("pin vhost thread(%s) to extra cpu(%s)" % (i, node.pin_cpu(i, extra=True))) else: logging.info("Skip pinning, no enough nodes") def _check_driver_verifier(session, driver, timeout=300): """ Check driver verifier status :param session: VM session. :param driver: The driver need to query :param timeout: Timeout in seconds """ logging.info("Check %s driver verifier status" % driver) query_cmd = "verifier /querysettings" output = session.cmd_output(query_cmd, timeout=timeout) return (driver in output, output) @error_context.context_aware def setup_win_driver_verifier(session, driver, vm, timeout=300): """ Enable driver verifier for windows guest. :param driver: The driver which needs enable the verifier. :param vm: VM object. :param timeout: Timeout in seconds. """ verifier_status = _check_driver_verifier(session, driver)[0] if not verifier_status: error_context.context("Enable %s driver verifier" % driver, logging.info) verifier_setup_cmd = "verifier /standard /driver %s.sys" % driver session.cmd(verifier_setup_cmd, timeout=timeout, ignore_all_errors=True) session = vm.reboot(session) verifier_status, output = _check_driver_verifier(session, driver) if not verifier_status: msg = "%s verifier is not enabled, details: %s" % (driver, output) raise exceptions.TestFail(msg) logging.info("%s verifier is enabled already" % driver) return session def clear_win_driver_verifier(driver, vm, timeout=300): """ Clear the driver verifier in windows guest. :param driver: The driver need to clear :param vm: VM object. :param timeout: Timeout in seconds. """ session = vm.wait_for_login(timeout=timeout) try: verifier_status = _check_driver_verifier(session, driver)[1] if verifier_status: logging.info("Clear driver verifier") verifier_clear_cmd = "verifier /reset" session.cmd(verifier_clear_cmd, timeout=timeout, ignore_all_errors=True) session = vm.reboot(session) finally: session.close() @error_context.context_aware def windrv_verify_running(session, test, driver, timeout=300): """ Check if driver is running for windows guest within a period time. :param session: VM session :param test: Kvm test object :param driver: The driver which needs to check. :param timeout: Timeout in seconds. """ def _check_driver_stat(): """ Check if driver is in Running status. """ output = session.cmd_output(driver_check_cmd, timeout=timeout) if "Running" in output: return True return False error_context.context("Check %s driver state." % driver, logging.info) driver_check_cmd = (r'wmic sysdriver where PathName="C:\\Windows\\System32' r'\\drivers\\%s.sys" get State /value') % driver if not utils_misc.wait_for(_check_driver_stat, timeout, 0, 5): test.error("%s driver is not running" % driver) @error_context.context_aware def windrv_check_running_verifier(session, vm, test, driver, timeout=300): """ Check whether the windows driver is running, then enable driver verifier. :param vm: the VM that use the driver. :param test: the KVM test object. :param driver: the driver concerned. :timeout: the timeout to use in this process, in seconds. """ windrv_verify_running(session, test, driver, timeout) return setup_win_driver_verifier(session, driver, vm, timeout) def setup_runlevel(params, session): """ Setup the runlevel in guest. :param params: Dictionary with the test parameters. :param session: VM session. """ cmd = "runlevel" ori_runlevel = "0" expect_runlevel = params.get("expect_runlevel", "3") # Note: All guest services may have not been started when # the guest gets IP addr; the guest runlevel maybe # is "unknown" whose exit status is 1 at that time, # which will cause the cmd execution failed. Need some # time here to wait for the guest services start. if utils_misc.wait_for(lambda: session.cmd_status(cmd) == 0, 15): ori_runlevel = session.cmd(cmd) ori_runlevel = ori_runlevel.split()[-1] if ori_runlevel == expect_runlevel: logging.info("Guest runlevel is already %s as expected" % ori_runlevel) else: session.cmd("init %s" % expect_runlevel) tmp_runlevel = session.cmd(cmd) tmp_runlevel = tmp_runlevel.split()[-1] if tmp_runlevel != expect_runlevel: logging.warn("Changing runlevel from %s to %s failed (%s)!", ori_runlevel, expect_runlevel, tmp_runlevel) class GuestSuspend(object): """ Suspend guest, supports both Linux and Windows. """ SUSPEND_TYPE_MEM = "mem" SUSPEND_TYPE_DISK = "disk" def __init__(self, test, params, vm): if not params or not vm: raise exceptions.TestError("Missing 'params' or 'vm' parameters") self._open_session_list = [] self.test = test self.vm = vm self.params = params self.login_timeout = float(self.params.get("login_timeout", 360)) self.services_up_timeout = float(self.params.get("services_up_timeout", 30)) self.os_type = self.params.get("os_type") def _get_session(self): self.vm.verify_alive() session = self.vm.wait_for_login(timeout=self.login_timeout) return session def _session_cmd_close(self, session, cmd): try: return session.cmd_status_output(cmd) finally: try: session.close() except Exception: pass def _cleanup_open_session(self): try: for s in self._open_session_list: if s: s.close() except Exception: pass @error_context.context_aware def setup_bg_program(self, **args): """ Start up a program as a flag in guest. """ suspend_bg_program_setup_cmd = args.get("suspend_bg_program_setup_cmd") error_context.context( "Run a background program as a flag", logging.info) session = self._get_session() self._open_session_list.append(session) logging.debug("Waiting all services in guest are fully started.") time.sleep(self.services_up_timeout) session.sendline(suspend_bg_program_setup_cmd) @error_context.context_aware def check_bg_program(self, **args): """ Make sure the background program is running as expected """ suspend_bg_program_chk_cmd = args.get("suspend_bg_program_chk_cmd") error_context.context( "Verify background program is running", logging.info) session = self._get_session() s, _ = self._session_cmd_close(session, suspend_bg_program_chk_cmd) if s: raise exceptions.TestFail( "Background program is dead. Suspend failed.") @error_context.context_aware def kill_bg_program(self, **args): error_context.context("Kill background program after resume") suspend_bg_program_kill_cmd = args.get("suspend_bg_program_kill_cmd") try: session = self._get_session() self._session_cmd_close(session, suspend_bg_program_kill_cmd) except Exception as e: logging.warn("Could not stop background program: '%s'", e) pass @error_context.context_aware def _check_guest_suspend_log(self, **args): error_context.context("Check whether guest supports suspend", logging.info) suspend_support_chk_cmd = args.get("suspend_support_chk_cmd") session = self._get_session() s, o = self._session_cmd_close(session, suspend_support_chk_cmd) return s, o def verify_guest_support_suspend(self, **args): s, _ = self._check_guest_suspend_log(**args) if s: raise exceptions.TestError("Guest doesn't support suspend.") @error_context.context_aware def start_suspend(self, **args): suspend_start_cmd = args.get("suspend_start_cmd") error_context.context( "Start suspend [%s]" % (suspend_start_cmd), logging.info) session = self._get_session() self._open_session_list.append(session) # Suspend to disk session.sendline(suspend_start_cmd) @error_context.context_aware def verify_guest_down(self, **args): # Make sure the VM goes down error_context.context("Wait for guest goes down after suspend") suspend_timeout = 240 + int(self.params.get("smp")) * 60 if not utils_misc.wait_for(self.vm.is_dead, suspend_timeout, 2, 2): raise exceptions.TestFail("VM refuses to go down. Suspend failed.") @error_context.context_aware def resume_guest_mem(self, **args): error_context.context("Resume suspended VM from memory") self.vm.monitor.system_wakeup() @error_context.context_aware def resume_guest_disk(self, **args): error_context.context("Resume suspended VM from disk") self.vm.create() @error_context.context_aware def verify_guest_up(self, **args): error_context.context("Verify guest system log", logging.info) suspend_log_chk_cmd = args.get("suspend_log_chk_cmd") session = self._get_session()
[ " s, o = self._session_cmd_close(session, suspend_log_chk_cmd)" ]
1,232
lcc
python
null
659965fc4472dec4f8b056a906be656d08aac541f75950f4
package org.zeromq; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.junit.Ignore; import org.junit.Test; import org.zeromq.ZMQ.Socket; public class PubSubTest { @Test @Ignore public void testRaceConditionIssue322() throws IOException, InterruptedException { final ZMQ.Context context = ZMQ.context(1); final String address = "tcp://localhost:" + Utils.findOpenPort(); final byte[] msg = "abc".getBytes(); final int messagesNumber = 1000; //run publisher Runnable pub = new Runnable() { @Override public void run() { ZMQ.Socket publisher = context.socket(SocketType.PUB); publisher.bind(address); int count = messagesNumber; while (count-- > 0) { publisher.send(msg); System.out.println("Send message " + count); } publisher.close(); } }; //run subscriber Runnable sub = new Runnable() { @Override public void run() { ZMQ.Socket subscriber = context.socket(SocketType.SUB); subscriber.connect(address); subscriber.subscribe(ZMQ.SUBSCRIPTION_ALL); int count = messagesNumber; while (count-- > 0) { subscriber.recv(); System.out.println("Received message " + count); } subscriber.close(); } }; ExecutorService executor = Executors.newFixedThreadPool(2, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); } }); return thread; } }); executor.submit(sub); zmq.ZMQ.sleep(1); executor.submit(pub); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); context.close(); } @Test @Ignore public void testPubConnectSubBindIssue289and342() throws IOException { ZMQ.Context context = ZMQ.context(1); Socket pub = context.socket(SocketType.XPUB); assertThat(pub, notNullValue()); Socket sub = context.socket(SocketType.SUB); assertThat(sub, notNullValue()); boolean rc = sub.subscribe(new byte[0]); assertThat(rc, is(true)); String host = "tcp://localhost:" + Utils.findOpenPort(); rc = sub.bind(host); assertThat(rc, is(true)); rc = pub.connect(host); assertThat(rc, is(true)); zmq.ZMQ.msleep(300); rc = pub.send("test"); assertThat(rc, is(true)); assertThat(sub.recvStr(), is("test")); pub.close(); sub.close(); context.term(); } @Test public void testUnsubscribeIssue554() throws Exception { final int port = Utils.findOpenPort(); final ExecutorService service = Executors.newFixedThreadPool(2); final Callable<Boolean> pub = new Callable<Boolean>() { @Override public Boolean call() { final ZMQ.Context ctx = ZMQ.context(1); assertThat(ctx, notNullValue()); final ZMQ.Socket pubsocket = ctx.socket(SocketType.PUB); assertThat(pubsocket, notNullValue()); boolean rc = pubsocket.bind("tcp://*:" + port); assertThat(rc, is(true)); for (int idx = 1; idx <= 15; ++idx) { rc = pubsocket.sendMore("test/"); assertThat(rc, is(true)); rc = pubsocket.send("data" + idx); assertThat(rc, is(true)); System.out.printf("Send-%d/", idx); ZMQ.msleep(100); } pubsocket.close(); ctx.close(); return true; } }; final Callable<Integer> sub = new Callable<Integer>() { @Override public Integer call() throws Exception { final ZMQ.Context ctx = ZMQ.context(1); assertThat(ctx, notNullValue()); final ZMQ.Socket sub = ctx.socket(SocketType.SUB); assertThat(sub, notNullValue()); boolean rc = sub.setReceiveTimeOut(3000); assertThat(rc, is(true)); rc = sub.subscribe("test/"); assertThat(rc, is(true)); rc = sub.connect("tcp://localhost:" + port); assertThat(rc, is(true)); System.out.println("[SUB]"); int received = receive(sub, 5); assertThat(received > 1, is(true)); // unsubscribe from the topic and verify that we don't receive messages anymore rc = sub.unsubscribe("test/"); assertThat(rc, is(true)); System.out.printf("%n[UNSUB]%n"); received = receive(sub, 10); sub.close(); ctx.close(); return received; } private int receive(ZMQ.Socket socket, int maxSeconds) { int received = 0; long current = System.currentTimeMillis(); long end = current + maxSeconds * 1000; while (current < end) { ZMsg msg = ZMsg.recvMsg(socket); current = System.currentTimeMillis(); if (msg == null) { continue; } ++received; } return received; } }; final Future<Integer> rc = service.submit(sub);
[ " final Future<Boolean> pubf = service.submit(pub);" ]
471
lcc
java
null
4607ba7831731a759293fdd8a639dc5c10d803e93d6bcba2
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.core.body.ft.protocols; import java.io.IOException; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import org.apache.log4j.Logger; import org.objectweb.proactive.Body; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.AbstractBody; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.exceptions.BodyTerminatedException; import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint; import org.objectweb.proactive.core.body.ft.checkpointing.CheckpointInfo; import org.objectweb.proactive.core.body.ft.extension.FTDecorator; import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage; import org.objectweb.proactive.core.body.ft.internalmsg.Heartbeat; import org.objectweb.proactive.core.body.ft.servers.faultdetection.FaultDetector; import org.objectweb.proactive.core.body.ft.servers.location.LocationServer; import org.objectweb.proactive.core.body.ft.servers.recovery.RecoveryProcess; import org.objectweb.proactive.core.body.ft.servers.storage.CheckpointServer; import org.objectweb.proactive.core.body.ft.service.FaultToleranceTechnicalService; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.security.exceptions.CommunicationForbiddenException; import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * Define all hook methods for the management of fault-tolerance. * @author The ProActive Team * @since ProActive 2.2 */ public abstract class FTManager implements java.io.Serializable { private static final long serialVersionUID = 1L; //logger final protected static Logger logger = ProActiveLogger.getLogger(Loggers.FAULT_TOLERANCE); final protected static Logger EXTENDED_FT_LOGGER = ProActiveLogger.getLogger( Loggers.FAULT_TOLERANCE_EXTENSION); /** This value is sent by an active object that is not fault tolerant*/ public static final int NON_FT = -30; /** This is the default value in ms of the checkpoint interval time */ public static final int DEFAULT_TTC_VALUE = 30000; /** Value returned by an object if the recieved message is served as an immediate service (@see xxx) */ public static final int IMMEDIATE_SERVICE = -1; /** Value returned by an object if the received message is orphan */ public static final int ORPHAN_REPLY = -2; /** Time to wait between a send and a resend in ms*/ public static final long TIME_TO_RESEND = 3000; /** Error message when calling uncallable method on a halfbody */ public static final String HALF_BODY_EXCEPTION_MESSAGE = "Cannot perform this call on a FTManager of a HalfBody"; // true is this is a checkpoint private boolean isACheckpoint; // body attached to this manager protected AbstractBody owner; protected UniqueID ownerID; // server adresses protected CheckpointServer storage; protected LocationServer location; protected RecoveryProcess recovery; // additional codebase for checkpoints protected String additionalCodebase; // checkpoint interval (ms) protected int ttc; /** * Return the selector value for a given protocol. * @param protoName the name of the protocol (cic or pml). * @return the selector value for a given protocol. */ public static int getProtoSelector(String protoName) { if (FTManagerFactory.PROTO_CIC.equals(protoName)) { return FTManagerFactory.PROTO_CIC_ID; } else if (FTManagerFactory.PROTO_PML.equals(protoName)) { return FTManagerFactory.PROTO_PML_ID; } return 0; } /** * Initialize the FTManager. This method establishes all needed connections with the servers. * The owner object is registered in the location server (@see xxx). * @param owner The object linked to this FTManager * @return still not used * @throws ProActiveException A problem occurs during the connection with the servers */ public int init(AbstractBody owner) throws ProActiveException { this.owner = owner; this.ownerID = owner.getID(); Node node = NodeFactory.getNode(this.owner.getNodeURL()); try { String ttcValue = node.getProperty(FaultToleranceTechnicalService.TTC); if (ttcValue != null) { this.ttc = Integer.parseInt(ttcValue) * 1000; } else { this.ttc = FTManager.DEFAULT_TTC_VALUE; } String urlGlobal = node.getProperty(FaultToleranceTechnicalService.GLOBAL_SERVER); if (urlGlobal != null) { this.storage = (CheckpointServer) (Naming.lookup(urlGlobal)); this.location = (LocationServer) (Naming.lookup(urlGlobal)); this.recovery = (RecoveryProcess) (Naming.lookup(urlGlobal)); } else { String urlCheckpoint = node.getProperty(FaultToleranceTechnicalService.CKPT_SERVER); String urlRecovery = node.getProperty(FaultToleranceTechnicalService.RECOVERY_SERVER); String urlLocation = node.getProperty(FaultToleranceTechnicalService.LOCATION_SERVER); if ((urlCheckpoint != null) && (urlRecovery != null) && (urlLocation != null)) { this.storage = (CheckpointServer) (Naming.lookup(urlCheckpoint)); this.location = (LocationServer) (Naming.lookup(urlLocation)); this.recovery = (RecoveryProcess) (Naming.lookup(urlRecovery)); } else { throw new ProActiveException("Unable to init FTManager : servers are not correctly set"); } } // the additional codebase is added to normal codebase // ONLY during serialization for checkpoint ! this.additionalCodebase = this.storage.getServerCodebase(); // registration in the recovery process and in the localisation server try { this.recovery.register(ownerID); this.location.updateLocation(ownerID, owner.getRemoteAdapter()); } catch (RemoteException e) { logger.error("**ERROR** Unable to register in location server"); throw new ProActiveException("Unable to register in location server", e); } } catch (MalformedURLException e) { throw new ProActiveException("Unable to init FTManager : FT is disable.", e); } catch (RemoteException e) { throw new ProActiveException("Unable to init FTManager : FT is disable.", e); } catch (NotBoundException e) { throw new ProActiveException("Unable to init FTManager : FT is disable.", e); } return 0; } /** * Unregister this activity from the fault-tolerance mechanism. This method must be called * when an active object ends its activity normally. */ public void termination() throws ProActiveException { try { this.recovery.unregister(this.ownerID); } catch (RemoteException e) { logger.error("**ERROR** Unable to register in location server"); throw new ProActiveException("Unable to unregister in location server", e); } } /** * Return true if the owner is a checkpoint, i.e. during checkpointing, and on recovery * when the owner is deserialized. * @return true if the owner is a checkpoint, i.e. during checkpointing, and on recovery * when the owner is deserialized, false ohterwise */ public boolean isACheckpoint() { return isACheckpoint; } /** * Set the current state of the owner as a checkpoint. Called during checkpoiting. * @param tag true during checkpointing, false otherwise */ public void setCheckpointTag(boolean tag) { this.isACheckpoint = tag; } /** * Common behavior when a communication with another active object failed. * The location server is contacted. * @param suspect the uniqueID of the callee * @param suspectLocation the supposed location of the callee * @param e the exception raised during the communication * @return the actual location of the callee */ public UniversalBody communicationFailed(UniqueID suspect, UniversalBody suspectLocation, Exception e) { try { // send an adapter to suspectLocation: the suspected body could be local UniversalBody newLocation = this.location.searchObject(suspect, suspectLocation .getRemoteAdapter(), this.ownerID); if (newLocation == null) { while (newLocation == null) { try { // suspected is failed or is recovering if (logger.isDebugEnabled()) { logger.debug("[CIC] Waiting for recovery of " + suspect); } Thread.sleep(TIME_TO_RESEND); } catch (InterruptedException e2) { e2.printStackTrace(); } newLocation = this.location.searchObject(suspect, suspectLocation.getRemoteAdapter(), this.ownerID); } return newLocation; } else { System.out.println("FTManager.communicationFailed() : new location is not null "); // newLocation is the new location of suspect return newLocation; } } catch (RemoteException e1) { logger.error("**ERROR** Location server unreachable"); e1.printStackTrace(); return null; } } /** * Fault-tolerant sending: this send notices fault tolerance servers if the destination is * unreachable and resent the message until destination is reachable. * @param r the reply to send * @param destination the destination of the reply * @return the value returned by the sending */ public int sendReply(Reply r, UniversalBody destination) { try { this.owner.getDecorator().onSendReplyBefore(r); int res = r.send(destination); // In case of a recovery, we need to handle the case where the reified object is not decorated // (because the service of this object is not restarted yet) if (this.owner.getDecorator() instanceof FTDecorator) { ((FTDecorator) this.owner.getDecorator()).setOnSendReplyAfterParameters(res, destination); } this.owner.getDecorator().onSendReplyAfter(r); return res; } catch (BodyTerminatedException e) { logger.info("[FAULT] " + this.ownerID + " : FAILURE OF " + destination.getID() + " SUSPECTED ON REPLY SENDING : " + e.getMessage()); UniversalBody newDestination = this.communicationFailed(destination.getID(), destination, e); return this.sendReply(r, newDestination); } catch (IOException e) { logger.info("[FAULT] " + this.ownerID + " : FAILURE OF " + destination.getID() + " SUSPECTED ON REPLY SENDING : " + e.getMessage()); UniversalBody newDestination = this.communicationFailed(destination.getID(), destination, e); return this.sendReply(r, newDestination); } } /** * Fault-tolerant sending: this send notices fault tolerance servers if the destination is * unreachable and resent the message until destination is reachable. * @param r the request to send * @param destination the destination of the request * @return the value returned by the sending * @throws RenegotiateSessionException * @throws CommunicationForbiddenException */ public int sendRequest(Request r, UniversalBody destination) throws RenegotiateSessionException, CommunicationForbiddenException { try { this.owner.getDecorator().onSendRequestBefore(r); int res = r.send(destination); // In case of a recovery, we need to handle the case where the reified object is not decorated // (because the service of this object is not restarted yet)
[ " if (this.owner.getDecorator() instanceof FTDecorator) {" ]
1,423
lcc
java
null
656e6b487418898304f2b9808ba22f80abf877b82fdba872
/* Copyright (C) 2014-2019 de4dot@gmail.com This file is part of dnSpy dnSpy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. dnSpy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using dnlib.DotNet.MD; using dnlib.PE; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace MakeEverythingPublic { public sealed class MakeEverythingPublic : Task { // Increment it if something changes so the files are re-created const string VERSION = "v1"; #pragma warning disable CS8618 // Non-nullable field is uninitialized. [Required] public string IVTString { get; set; } [Required] public string DestinationDirectory { get; set; } [Required] public string AssembliesToMakePublic { get; set; } [Required] public ITaskItem[] ReferencePath { get; set; } [Output] public ITaskItem[] OutputReferencePath { get; private set; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public override bool Execute() { if (string.IsNullOrWhiteSpace(IVTString)) { Log.LogMessageFromText(nameof(IVTString) + " is an empty string", MessageImportance.High); return false; } if (string.IsNullOrWhiteSpace(DestinationDirectory)) { Log.LogMessageFromText(nameof(DestinationDirectory) + " is an empty string", MessageImportance.High); return false; } var assembliesToFix = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var tmp in AssembliesToMakePublic.Split(';')) { var asmName = tmp.Trim(); var asmSimpleName = asmName; int index = asmSimpleName.IndexOf(','); if (index >= 0) asmSimpleName = asmSimpleName.Substring(0, index).Trim(); if (asmSimpleName.Length == 0) continue; assembliesToFix.Add(asmSimpleName); } OutputReferencePath = new ITaskItem[ReferencePath.Length]; byte[]? ivtBlob = null; for (int i = 0; i < ReferencePath.Length; i++) { var file = ReferencePath[i]; OutputReferencePath[i] = file; var filename = file.ItemSpec; var fileExt = Path.GetExtension(filename); var asmSimpleName = Path.GetFileNameWithoutExtension(filename); if (!assembliesToFix.Contains(asmSimpleName)) continue; if (!File.Exists(filename)) { Log.LogMessageFromText($"File does not exist: {filename}", MessageImportance.High); return false; } var patchDir = DestinationDirectory; Directory.CreateDirectory(patchDir); var fileInfo = new FileInfo(filename); long filesize = fileInfo.Length; long writeTime = fileInfo.LastWriteTimeUtc.ToBinary(); var extraInfo = $"_{VERSION} {filesize} {writeTime}_"; var patchedFilename = Path.Combine(patchDir, asmSimpleName + extraInfo + fileExt); if (StringComparer.OrdinalIgnoreCase.Equals(patchedFilename, filename)) continue; if (!File.Exists(patchedFilename)) { if (ivtBlob is null) ivtBlob = CreateIVTBlob(IVTString); var data = File.ReadAllBytes(filename); try { using (var peImage = new PEImage(data, filename, ImageLayout.File, verify: true)) { using (var md = MetadataFactory.CreateMetadata(peImage, verify: true)) { var result = new IVTPatcher(data, md, ivtBlob).Patch(); if (result != IVTPatcherResult.OK) { string errMsg; switch (result) { case IVTPatcherResult.NoCustomAttributes: errMsg = $"Assembly '{asmSimpleName}' has no custom attributes"; break; case IVTPatcherResult.NoIVTs: errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttributes"; break; case IVTPatcherResult.IVTBlobTooSmall: errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttribute blob that is big enough to store '{IVTString}'. Use a shorter assembly name and/or a shorter public key, or skip PublicKey=xxxx... altogether (if it's a C# assembly)"; break; default: Debug.Fail($"Unknown error result: {result}"); errMsg = "Unknown error"; break; } Log.LogMessageFromText(errMsg, MessageImportance.High); return false; } try { File.WriteAllBytes(patchedFilename, data); } catch { try { File.Delete(patchedFilename); } catch { } throw; } } } } catch (Exception ex) when (ex is IOException || ex is BadImageFormatException) { Log.LogMessageFromText($"File '{filename}' is not a .NET file", MessageImportance.High); return false; } var xmlDocFile = Path.ChangeExtension(filename, "xml"); if (File.Exists(xmlDocFile)) { var newXmlDocFile = Path.ChangeExtension(patchedFilename, "xml"); if (File.Exists(newXmlDocFile)) File.Delete(newXmlDocFile); File.Copy(xmlDocFile, newXmlDocFile); } } OutputReferencePath[i] = new TaskItem(patchedFilename); } return true; } static byte[] CreateIVTBlob(string newIVTString) { var caStream = new MemoryStream(); var caWriter = new BinaryWriter(caStream); caWriter.Write((ushort)1); WriteString(caWriter, newIVTString); caWriter.Write((ushort)0); var newIVTBlob = caStream.ToArray(); var compressedSize = GetCompressedUInt32Bytes((uint)newIVTBlob.Length); var blob = new byte[compressedSize + newIVTBlob.Length]; var blobStream = new MemoryStream(blob); var blobWriter = new BinaryWriter(blobStream); WriteCompressedUInt32(blobWriter, (uint)newIVTBlob.Length); blobWriter.Write(newIVTBlob); if (blobWriter.BaseStream.Position != blob.Length) throw new InvalidOperationException(); return blob; } static void WriteString(BinaryWriter writer, string s) { var bytes = Encoding.UTF8.GetBytes(s); WriteCompressedUInt32(writer, (uint)bytes.Length); writer.Write(bytes); } static void WriteCompressedUInt32(BinaryWriter writer, uint value) { if (value <= 0x7F) writer.Write((byte)value); else if (value <= 0x3FFF) { writer.Write((byte)((value >> 8) | 0x80)); writer.Write((byte)value); } else if (value <= 0x1FFFFFFF) { writer.Write((byte)((value >> 24) | 0xC0)); writer.Write((byte)(value >> 16)); writer.Write((byte)(value >> 8)); writer.Write((byte)value); } else throw new ArgumentOutOfRangeException("UInt32 value can't be compressed"); } static uint GetCompressedUInt32Bytes(uint value) {
[ "\t\t\tif (value <= 0x7F)" ]
701
lcc
csharp
null
527be9dcafaca936af7816ffc1b91056d113516e8acf4806
# -*- coding: utf-8 -*- # Copyright (C) 2009-2013 Roman Zimbelmann <hut@lavabit.com> # This configuration file is licensed under the same terms as ranger. # =================================================================== # This file contains ranger's commands. # It's all in python; lines beginning with # are comments. # # Note that additional commands are automatically generated from the methods # of the class ranger.core.actions.Actions. # # You can customize commands in the file ~/.config/ranger/commands.py. # It has the same syntax as this file. In fact, you can just copy this # file there with `ranger --copy-config=commands' and make your modifications. # But make sure you update your configs when you update ranger. # # =================================================================== # Every class defined here which is a subclass of `Command' will be used as a # command in ranger. Several methods are defined to interface with ranger: # execute(): called when the command is executed. # cancel(): called when closing the console. # tab(): called when <TAB> is pressed. # quick(): called after each keypress. # # The return values for tab() can be either: # None: There is no tab completion # A string: Change the console to this string # A list/tuple/generator: cycle through every item in it # # The return value for quick() can be: # False: Nothing happens # True: Execute the command afterwards # # The return value for execute() and cancel() doesn't matter. # # =================================================================== # Commands have certain attributes and methods that facilitate parsing of # the arguments: # # self.line: The whole line that was written in the console. # self.args: A list of all (space-separated) arguments to the command. # self.quantifier: If this command was mapped to the key "X" and # the user pressed 6X, self.quantifier will be 6. # self.arg(n): The n-th argument, or an empty string if it doesn't exist. # self.rest(n): The n-th argument plus everything that followed. For example, # If the command was "search foo bar a b c", rest(2) will be "bar a b c" # self.start(n): The n-th argument and anything before it. For example, # If the command was "search foo bar a b c", rest(2) will be "bar a b c" # # =================================================================== # And this is a little reference for common ranger functions and objects: # # self.fm: A reference to the "fm" object which contains most information # about ranger. # self.fm.notify(string): Print the given string on the screen. # self.fm.notify(string, bad=True): Print the given string in RED. # self.fm.reload_cwd(): Reload the current working directory. # self.fm.thisdir: The current working directory. (A File object.) # self.fm.thisfile: The current file. (A File object too.) # self.fm.thistab.get_selection(): A list of all selected files. # self.fm.execute_console(string): Execute the string as a ranger command. # self.fm.open_console(string): Open the console with the given string # already typed in for you. # self.fm.move(direction): Moves the cursor in the given direction, which # can be something like down=3, up=5, right=1, left=1, to=6, ... # # File objects (for example self.fm.thisfile) have these useful attributes and # methods: # # cf.path: The path to the file. # cf.basename: The base name only. # cf.load_content(): Force a loading of the directories content (which # obviously works with directories only) # cf.is_directory: True/False depending on whether it's a directory. # # For advanced commands it is unavoidable to dive a bit into the source code # of ranger. # =================================================================== from ranger.api.commands import * class alias(Command): """:alias <newcommand> <oldcommand> Copies the oldcommand as newcommand. """ context = 'browser' resolve_macros = False def execute(self): if not self.arg(1) or not self.arg(2): self.fm.notify('Syntax: alias <newcommand> <oldcommand>', bad=True) else: self.fm.commands.alias(self.arg(1), self.rest(2)) class cd(Command): """:cd [-r] <dirname> The cd command changes the directory. The command 'cd -' is equivalent to typing ``. Using the option "-r" will get you to the real path. """ def execute(self): import os.path if self.arg(1) == '-r': self.shift() destination = os.path.realpath(self.rest(1)) if os.path.isfile(destination): destination = os.path.dirname(destination) else: destination = self.rest(1) if not destination: destination = '~' if destination == '-': self.fm.enter_bookmark('`') else: self.fm.cd(destination) def tab(self): import os from os.path import dirname, basename, expanduser, join cwd = self.fm.thisdir.path rel_dest = self.rest(1) bookmarks = [v.path for v in self.fm.bookmarks.dct.values() if rel_dest in v.path ] # expand the tilde into the user directory if rel_dest.startswith('~'): rel_dest = expanduser(rel_dest) # define some shortcuts abs_dest = join(cwd, rel_dest) abs_dirname = dirname(abs_dest) rel_basename = basename(rel_dest) rel_dirname = dirname(rel_dest) try: # are we at the end of a directory? if rel_dest.endswith('/') or rel_dest == '': _, dirnames, _ = next(os.walk(abs_dest)) # are we in the middle of the filename? else: _, dirnames, _ = next(os.walk(abs_dirname)) dirnames = [dn for dn in dirnames \ if dn.startswith(rel_basename)] except (OSError, StopIteration): # os.walk found nothing pass else: dirnames.sort() dirnames = bookmarks + dirnames # no results, return None if len(dirnames) == 0: return # one result. since it must be a directory, append a slash. if len(dirnames) == 1: return self.start(1) + join(rel_dirname, dirnames[0]) + '/' # more than one result. append no slash, so the user can # manually type in the slash to advance into that directory return (self.start(1) + join(rel_dirname, dirname) for dirname in dirnames) class chain(Command): """:chain <command1>; <command2>; ... Calls multiple commands at once, separated by semicolons. """ def execute(self): for command in self.rest(1).split(";"): self.fm.execute_console(command) class shell(Command): escape_macros_for_shell = True def execute(self): if self.arg(1) and self.arg(1)[0] == '-': flags = self.arg(1)[1:] command = self.rest(2) else: flags = '' command = self.rest(1) if not command and 'p' in flags: command = 'cat %f' if command: if '%' in command: command = self.fm.substitute_macros(command, escape=True) self.fm.execute_command(command, flags=flags) def tab(self): from ranger.ext.get_executables import get_executables if self.arg(1) and self.arg(1)[0] == '-': command = self.rest(2) else: command = self.rest(1) start = self.line[0:len(self.line) - len(command)] try: position_of_last_space = command.rindex(" ") except ValueError: return (start + program + ' ' for program \ in get_executables() if program.startswith(command)) if position_of_last_space == len(command) - 1: selection = self.fm.thistab.get_selection() if len(selection) == 1: return self.line + selection[0].shell_escaped_basename + ' ' else: return self.line + '%s ' else: before_word, start_of_word = self.line.rsplit(' ', 1) return (before_word + ' ' + file.shell_escaped_basename \ for file in self.fm.thisdir.files \ if file.shell_escaped_basename.startswith(start_of_word)) class open_with(Command): def execute(self): app, flags, mode = self._get_app_flags_mode(self.rest(1)) self.fm.execute_file( files = [f for f in self.fm.thistab.get_selection()], app = app, flags = flags, mode = mode) def tab(self): return self._tab_through_executables() def _get_app_flags_mode(self, string): """Extracts the application, flags and mode from a string. examples: "mplayer f 1" => ("mplayer", "f", 1) "aunpack 4" => ("aunpack", "", 4) "p" => ("", "p", 0) "" => None """ app = '' flags = '' mode = 0 split = string.split() if len(split) == 0: pass elif len(split) == 1: part = split[0] if self._is_app(part): app = part elif self._is_flags(part): flags = part elif self._is_mode(part): mode = part elif len(split) == 2: part0 = split[0] part1 = split[1] if self._is_app(part0): app = part0 if self._is_flags(part1): flags = part1 elif self._is_mode(part1): mode = part1 elif self._is_flags(part0): flags = part0 if self._is_mode(part1): mode = part1 elif self._is_mode(part0): mode = part0 if self._is_flags(part1): flags = part1 elif len(split) >= 3: part0 = split[0] part1 = split[1] part2 = split[2] if self._is_app(part0): app = part0 if self._is_flags(part1): flags = part1 if self._is_mode(part2): mode = part2 elif self._is_mode(part1): mode = part1 if self._is_flags(part2): flags = part2 elif self._is_flags(part0): flags = part0 if self._is_mode(part1): mode = part1 elif self._is_mode(part0): mode = part0 if self._is_flags(part1): flags = part1 return app, flags, int(mode) def _is_app(self, arg): return not self._is_flags(arg) and not arg.isdigit() def _is_flags(self, arg): from ranger.core.runner import ALLOWED_FLAGS return all(x in ALLOWED_FLAGS for x in arg) def _is_mode(self, arg): return all(x in '0123456789' for x in arg) class set_(Command): """:set <option name>=<python expression> Gives an option a new value. """ name = 'set' # don't override the builtin set class def execute(self): name = self.arg(1) name, value, _ = self.parse_setting_line() self.fm.set_option_from_string(name, value) def tab(self): name, value, name_done = self.parse_setting_line() settings = self.fm.settings if not name: return sorted(self.firstpart + setting for setting in settings) if not value and not name_done: return (self.firstpart + setting for setting in settings \ if setting.startswith(name)) if not value: return self.firstpart + str(settings[name]) if bool in settings.types_of(name): if 'true'.startswith(value.lower()): return self.firstpart + 'True' if 'false'.startswith(value.lower()): return self.firstpart + 'False' class setlocal(set_): """:setlocal path=<python string> <option name>=<python expression> Gives an option a new value. """ PATH_RE = re.compile(r'^\s*path="?(.*?)"?\s*$') def execute(self): import os.path match = self.PATH_RE.match(self.arg(1)) if match: path = os.path.normpath(os.path.expanduser(match.group(1))) self.shift() elif self.fm.thisdir: path = self.fm.thisdir.path else: path = None if path: name = self.arg(1) name, value, _ = self.parse_setting_line() self.fm.set_option_from_string(name, value, localpath=path) class setintag(setlocal): """:setintag <tag or tags> <option name>=<option value> Sets an option for directories that are tagged with a specific tag. """ def execute(self): tags = self.arg(1) self.shift() name, value, _ = self.parse_setting_line() self.fm.set_option_from_string(name, value, tags=tags) class quit(Command): """:quit Closes the current tab. If there is only one tab, quit the program. """ def execute(self): if len(self.fm.tabs) <= 1: self.fm.exit() self.fm.tab_close() class quitall(Command): """:quitall Quits the program immediately. """ def execute(self): self.fm.exit() class quit_bang(quitall): """:quit! Quits the program immediately. """ name = 'quit!' allow_abbrev = False class terminal(Command): """:terminal Spawns an "x-terminal-emulator" starting in the current directory. """ def execute(self): import os from ranger.ext.get_executables import get_executables command = os.environ.get('TERMCMD', os.environ.get('TERM')) if command not in get_executables(): command = 'x-terminal-emulator' if command not in get_executables(): command = 'xterm' self.fm.run(command, flags='f') class delete(Command): """:delete Tries to delete the selection. "Selection" is defined as all the "marked files" (by default, you can mark files with space or v). If there are no marked files, use the "current file" (where the cursor is) When attempting to delete non-empty directories or multiple marked files, it will require a confirmation. """ allow_abbrev = False def execute(self): import os if self.rest(1): self.fm.notify("Error: delete takes no arguments! It deletes " "the selected file(s).", bad=True) return cwd = self.fm.thisdir cf = self.fm.thisfile if not cwd or not cf: self.fm.notify("Error: no file selected for deletion!", bad=True) return confirm = self.fm.settings.confirm_on_delete many_files = (cwd.marked_items or (cf.is_directory and not cf.is_link \ and len(os.listdir(cf.path)) > 0)) if confirm != 'never' and (confirm != 'multiple' or many_files): self.fm.ui.console.ask("Confirm deletion of: %s (y/N)" % ', '.join(f.basename for f in self.fm.thistab.get_selection()), self._question_callback, ('n', 'N', 'y', 'Y')) else: # no need for a confirmation, just delete self.fm.delete() def _question_callback(self, answer): if answer == 'y' or answer == 'Y': self.fm.delete() class mark_tag(Command): """:mark_tag [<tags>] Mark all tags that are tagged with either of the given tags. When leaving out the tag argument, all tagged files are marked. """ do_mark = True def execute(self): cwd = self.fm.thisdir tags = self.rest(1).replace(" ","") if not self.fm.tags: return for fileobj in cwd.files: try: tag = self.fm.tags.tags[fileobj.realpath] except KeyError: continue if not tags or tag in tags: cwd.mark_item(fileobj, val=self.do_mark) self.fm.ui.status.need_redraw = True self.fm.ui.need_redraw = True class console(Command): """:console <command> Open the console with the given command. """ def execute(self): position = None if self.arg(1)[0:2] == '-p': try: position = int(self.arg(1)[2:]) self.shift() except: pass self.fm.open_console(self.rest(1), position=position) class load_copy_buffer(Command): """:load_copy_buffer Load the copy buffer from confdir/copy_buffer """ copy_buffer_filename = 'copy_buffer' def execute(self): from ranger.container.file import File from os.path import exists try: fname = self.fm.confpath(self.copy_buffer_filename) f = open(fname, 'r') except: return self.fm.notify("Cannot open %s" % \ (fname or self.copy_buffer_filename), bad=True) self.fm.copy_buffer = set(File(g) \ for g in f.read().split("\n") if exists(g)) f.close() self.fm.ui.redraw_main_column() class save_copy_buffer(Command): """:save_copy_buffer Save the copy buffer to confdir/copy_buffer """ copy_buffer_filename = 'copy_buffer' def execute(self): fname = None try: fname = self.fm.confpath(self.copy_buffer_filename) f = open(fname, 'w') except: return self.fm.notify("Cannot open %s" % \ (fname or self.copy_buffer_filename), bad=True) f.write("\n".join(f.path for f in self.fm.copy_buffer)) f.close() class unmark_tag(mark_tag): """:unmark_tag [<tags>] Unmark all tags that are tagged with either of the given tags. When leaving out the tag argument, all tagged files are unmarked. """ do_mark = False class mkdir(Command): """:mkdir <dirname> Creates a directory with the name <dirname>. """ def execute(self): from os.path import join, expanduser, lexists from os import mkdir dirname = join(self.fm.thisdir.path, expanduser(self.rest(1))) if not lexists(dirname): mkdir(dirname) else: self.fm.notify("file/directory exists!", bad=True) def tab(self): return self._tab_directory_content() class touch(Command): """:touch <fname> Creates a file with the name <fname>. """ def execute(self): from os.path import join, expanduser, lexists fname = join(self.fm.thisdir.path, expanduser(self.rest(1))) if not lexists(fname): open(fname, 'a').close() else: self.fm.notify("file/directory exists!", bad=True) def tab(self): return self._tab_directory_content() class edit(Command): """:edit <filename> Opens the specified file in vim """ def execute(self): if not self.arg(1): self.fm.edit_file(self.fm.thisfile.path) else: self.fm.edit_file(self.rest(1)) def tab(self): return self._tab_directory_content() class eval_(Command): """:eval [-q] <python code> Evaluates the python code. `fm' is a reference to the FM instance. To display text, use the function `p'. Examples: :eval fm :eval len(fm.directories) :eval p("Hello World!") """ name = 'eval' resolve_macros = False def execute(self): if self.arg(1) == '-q': code = self.rest(2) quiet = True else: code = self.rest(1) quiet = False import ranger global cmd, fm, p, quantifier fm = self.fm cmd = self.fm.execute_console p = fm.notify quantifier = self.quantifier try: try: result = eval(code) except SyntaxError: exec(code) else: if result and not quiet: p(result) except Exception as err: p(err) class rename(Command): """:rename <newname> Changes the name of the currently highlighted file to <newname> """ def execute(self): from ranger.container.file import File from os import access new_name = self.rest(1) if not new_name: return self.fm.notify('Syntax: rename <newname>', bad=True) if new_name == self.fm.thisfile.basename: return if access(new_name, os.F_OK): return self.fm.notify("Can't rename: file already exists!", bad=True) self.fm.rename(self.fm.thisfile, new_name) f = File(new_name) self.fm.thisdir.pointed_obj = f self.fm.thisfile = f def tab(self): return self._tab_directory_content() class chmod(Command): """:chmod <octal number> Sets the permissions of the selection to the octal number. The octal number is between 0 and 777. The digits specify the permissions for the user, the group and others. A 1 permits execution, a 2 permits writing, a 4 permits reading. Add those numbers to combine them. So a 7 permits everything. """ def execute(self): mode = self.rest(1) if not mode: mode = str(self.quantifier) try: mode = int(mode, 8) if mode < 0 or mode > 0o777: raise ValueError except ValueError: self.fm.notify("Need an octal number between 0 and 777!", bad=True) return for file in self.fm.thistab.get_selection(): try: os.chmod(file.path, mode) except Exception as ex: self.fm.notify(ex) try: # reloading directory. maybe its better to reload the selected # files only. self.fm.thisdir.load_content() except: pass class bulkrename(Command): """:bulkrename This command opens a list of selected files in an external editor. After you edit and save the file, it will generate a shell script which does bulk renaming according to the changes you did in the file. This shell script is opened in an editor for you to review. After you close it, it will be executed. """ def execute(self): import sys import tempfile from ranger.container.file import File from ranger.ext.shell_escape import shell_escape as esc py3 = sys.version > "3" # Create and edit the file list filenames = [f.basename for f in self.fm.thistab.get_selection()] listfile = tempfile.NamedTemporaryFile() if py3: listfile.write("\n".join(filenames).encode("utf-8")) else: listfile.write("\n".join(filenames)) listfile.flush() self.fm.execute_file([File(listfile.name)], app='editor') listfile.seek(0) if py3: new_filenames = listfile.read().decode("utf-8").split("\n") else: new_filenames = listfile.read().split("\n") listfile.close() if all(a == b for a, b in zip(filenames, new_filenames)): self.fm.notify("No renaming to be done!") return # Generate and execute script cmdfile = tempfile.NamedTemporaryFile() cmdfile.write(b"# This file will be executed when you close the editor.\n") cmdfile.write(b"# Please double-check everything, clear the file to abort.\n") if py3: cmdfile.write("\n".join("mv -vi -- " + esc(old) + " " + esc(new) \ for old, new in zip(filenames, new_filenames) \ if old != new).encode("utf-8")) else: cmdfile.write("\n".join("mv -vi -- " + esc(old) + " " + esc(new) \ for old, new in zip(filenames, new_filenames) if old != new)) cmdfile.flush() self.fm.execute_file([File(cmdfile.name)], app='editor') self.fm.run(['/bin/sh', cmdfile.name], flags='w') cmdfile.close() class relink(Command): """:relink <newpath> Changes the linked path of the currently highlighted symlink to <newpath> """ def execute(self): from ranger.container.file import File new_path = self.rest(1) cf = self.fm.thisfile if not new_path: return self.fm.notify('Syntax: relink <newpath>', bad=True) if not cf.is_link: return self.fm.notify('%s is not a symlink!' % cf.basename, bad=True) if new_path == os.readlink(cf.path): return try: os.remove(cf.path) os.symlink(new_path, cf.path) except OSError as err: self.fm.notify(err) self.fm.reset() self.fm.thisdir.pointed_obj = cf self.fm.thisfile = cf def tab(self): if not self.rest(1): return self.line+os.readlink(self.fm.thisfile.path) else: return self._tab_directory_content() class help_(Command): """:help Display ranger's manual page. """ name = 'help' def execute(self): if self.quantifier == 1: self.fm.dump_keybindings() elif self.quantifier == 2: self.fm.dump_commands() elif self.quantifier == 3: self.fm.dump_settings() else: self.fm.display_help() class copymap(Command): """:copymap <keys> <newkeys1> [<newkeys2>...] Copies a "browser" keybinding from <keys> to <newkeys> """ context = 'browser' def execute(self): if not self.arg(1) or not self.arg(2): return self.fm.notify("Not enough arguments", bad=True) for arg in self.args[2:]: self.fm.ui.keymaps.copy(self.context, self.arg(1), arg) class copypmap(copymap): """:copypmap <keys> <newkeys1> [<newkeys2>...] Copies a "pager" keybinding from <keys> to <newkeys> """ context = 'pager' class copycmap(copymap): """:copycmap <keys> <newkeys1> [<newkeys2>...] Copies a "console" keybinding from <keys> to <newkeys> """ context = 'console' class copytmap(copymap): """:copycmap <keys> <newkeys1> [<newkeys2>...] Copies a "taskview" keybinding from <keys> to <newkeys> """ context = 'taskview' class unmap(Command): """:unmap <keys> [<keys2>, ...] Remove the given "browser" mappings """ context = 'browser' def execute(self): for arg in self.args[1:]: self.fm.ui.keymaps.unbind(self.context, arg) class cunmap(unmap): """:cunmap <keys> [<keys2>, ...] Remove the given "console" mappings """ context = 'browser' class punmap(unmap): """:punmap <keys> [<keys2>, ...] Remove the given "pager" mappings """ context = 'pager' class tunmap(unmap): """:tunmap <keys> [<keys2>, ...] Remove the given "taskview" mappings """ context = 'taskview' class map_(Command): """:map <keysequence> <command> Maps a command to a keysequence in the "browser" context. Example: map j move down map J move down 10 """ name = 'map' context = 'browser' resolve_macros = False def execute(self): self.fm.ui.keymaps.bind(self.context, self.arg(1), self.rest(2)) class cmap(map_): """:cmap <keysequence> <command> Maps a command to a keysequence in the "console" context. Example: cmap <ESC> console_close cmap <C-x> console_type test """ context = 'console' class tmap(map_): """:tmap <keysequence> <command> Maps a command to a keysequence in the "taskview" context. """ context = 'taskview' class pmap(map_): """:pmap <keysequence> <command> Maps a command to a keysequence in the "pager" context. """ context = 'pager' class scout(Command): """:scout [-FLAGS] <pattern> Swiss army knife command for searching, traveling and filtering files. The command takes various flags as arguments which can be used to influence its behaviour: -a = automatically open a file on unambiguous match -e = open the selected file when pressing enter -f = filter files that match the current search pattern -g = interpret pattern as a glob pattern -i = ignore the letter case of the files -k = keep the console open when changing a directory with the command -l = letter skipping; e.g. allow "rdme" to match the file "readme" -m = mark the matching files after pressing enter -M = unmark the matching files after pressing enter -p = permanent filter: hide non-matching files after pressing enter -s = smart case; like -i unless pattern contains upper case letters -t = apply filter and search pattern as you type -v = inverts the match Multiple flags can be combined. For example, ":scout -gpt" would create a :filter-like command using globbing. """ AUTO_OPEN = 'a' OPEN_ON_ENTER = 'e' FILTER = 'f' SM_GLOB = 'g' IGNORE_CASE = 'i' KEEP_OPEN = 'k' SM_LETTERSKIP = 'l' MARK = 'm' UNMARK = 'M' PERM_FILTER = 'p' SM_REGEX = 'r' SMART_CASE = 's' AS_YOU_TYPE = 't' INVERT = 'v' def __init__(self, *args, **kws): Command.__init__(self, *args, **kws) self._regex = None self.flags, self.pattern = self.parse_flags() def execute(self): thisdir = self.fm.thisdir flags = self.flags pattern = self.pattern regex = self._build_regex() count = self._count(move=True) self.fm.thistab.last_search = regex self.fm.set_search_method(order="search") if self.MARK in flags or self.UNMARK in flags: value = flags.find(self.MARK) > flags.find(self.UNMARK) if self.FILTER in flags: for f in thisdir.files: thisdir.mark_item(f, value) else: for f in thisdir.files: if regex.search(f.basename): thisdir.mark_item(f, value) if self.PERM_FILTER in flags: thisdir.filter = regex if pattern else None # clean up: self.cancel() if self.OPEN_ON_ENTER in flags or \ self.AUTO_OPEN in flags and count == 1: if os.path.exists(pattern): self.fm.cd(pattern) else: self.fm.move(right=1) if self.KEEP_OPEN in flags and thisdir != self.fm.thisdir: # reopen the console: self.fm.open_console(self.line[0:-len(pattern)]) if thisdir != self.fm.thisdir and pattern != "..": self.fm.block_input(0.5) def cancel(self): self.fm.thisdir.temporary_filter = None self.fm.thisdir.refilter() def quick(self): asyoutype = self.AS_YOU_TYPE in self.flags if self.FILTER in self.flags: self.fm.thisdir.temporary_filter = self._build_regex() if self.PERM_FILTER in self.flags and asyoutype: self.fm.thisdir.filter = self._build_regex() if self.FILTER in self.flags or self.PERM_FILTER in self.flags: self.fm.thisdir.refilter() if self._count(move=asyoutype) == 1 and self.AUTO_OPEN in self.flags: return True return False def tab(self): self._count(move=True, offset=1) def _build_regex(self): if self._regex is not None: return self._regex frmat = "%s" flags = self.flags pattern = self.pattern if pattern == ".": return re.compile("") # Handle carets at start and dollar signs at end separately if pattern.startswith('^'): pattern = pattern[1:] frmat = "^" + frmat if pattern.endswith('$'): pattern = pattern[:-1] frmat += "$" # Apply one of the search methods if self.SM_REGEX in flags: regex = pattern elif self.SM_GLOB in flags: regex = re.escape(pattern).replace("\\*", ".*").replace("\\?", ".") elif self.SM_LETTERSKIP in flags: regex = ".*".join(re.escape(c) for c in pattern) else: regex = re.escape(pattern) regex = frmat % regex # Invert regular expression if necessary if self.INVERT in flags: regex = "^(?:(?!%s).)*$" % regex # Compile Regular Expression options = re.LOCALE | re.UNICODE if self.IGNORE_CASE in flags or self.SMART_CASE in flags and \ pattern.islower(): options |= re.IGNORECASE try: self._regex = re.compile(regex, options) except: self._regex = re.compile("") return self._regex def _count(self, move=False, offset=0): count = 0 cwd = self.fm.thisdir pattern = self.pattern if not pattern: return 0 if pattern == '.': return 0 if pattern == '..': return 1 deq = deque(cwd.files) deq.rotate(-cwd.pointer - offset) i = offset regex = self._build_regex() for fsobj in deq: if regex.search(fsobj.basename): count += 1 if move and count == 1: cwd.move(to=(cwd.pointer + i) % len(cwd.files)) self.fm.thisfile = cwd.pointed_obj if count > 1: return count i += 1 return count == 1 class grep(Command): """:grep <string> Looks for a string in all marked files or directories """ def execute(self): if self.rest(1): action = ['grep', '--line-number'] action.extend(['-e', self.rest(1), '-r']) action.extend(f.path for f in self.fm.thistab.get_selection()) self.fm.execute_command(action, flags='p') # Version control commands # -------------------------------- class stage(Command): """ :stage Stage selected files for the corresponding version control system """ def execute(self): from ranger.ext.vcs import VcsError filelist = [f.path for f in self.fm.thistab.get_selection()] self.fm.thisdir.vcs_outdated = True # for f in self.fm.thistab.get_selection(): # f.vcs_outdated = True try: self.fm.thisdir.vcs.add(filelist) except VcsError: self.fm.notify("Could not stage files.") self.fm.reload_cwd() class unstage(Command): """ :unstage Unstage selected files for the corresponding version control system """ def execute(self): from ranger.ext.vcs import VcsError filelist = [f.path for f in self.fm.thistab.get_selection()] self.fm.thisdir.vcs_outdated = True # for f in self.fm.thistab.get_selection(): # f.vcs_outdated = True try: self.fm.thisdir.vcs.reset(filelist) except VcsError: self.fm.notify("Could not unstage files.") self.fm.reload_cwd() class diff(Command): """ :diff Displays a diff of selected files against last last commited version """ def execute(self): from ranger.ext.vcs import VcsError import tempfile L = self.fm.thistab.get_selection() if len(L) == 0: return filelist = [f.path for f in L] vcs = L[0].vcs diff = vcs.get_raw_diff(filelist=filelist) if len(diff.strip()) > 0: tmp = tempfile.NamedTemporaryFile() tmp.write(diff.encode('utf-8')) tmp.flush() pager = os.environ.get('PAGER', ranger.DEFAULT_PAGER) self.fm.run([pager, tmp.name]) else: raise Exception("diff is empty") class log(Command): """ :log Displays the log of the current repo or files """ def execute(self): from ranger.ext.vcs import VcsError import tempfile L = self.fm.thistab.get_selection() if len(L) == 0: return filelist = [f.path for f in L] vcs = L[0].vcs log = vcs.get_raw_log(filelist=filelist) tmp = tempfile.NamedTemporaryFile() tmp.write(log.encode('utf-8')) tmp.flush() pager = os.environ.get('PAGER', ranger.DEFAULT_PAGER) self.fm.run([pager, tmp.name]) # =================================================================== # Custom commands # =================================================================== import os from ranger.core.loader import CommandLoader # Extracts copied archive (yy) --> extracthere class extracthere(Command): def execute(self): """ Extract copied files to current directory """ copied_files = tuple(self.fm.env.copy) if not copied_files: return def refresh(_): cwd = self.fm.env.get_directory(original_path) cwd.load_content() one_file = copied_files[0] cwd = self.fm.env.cwd original_path = cwd.path au_flags = ['-X', cwd.path] au_flags += self.line.split()[1:] au_flags += ['-e'] self.fm.env.copy.clear() self.fm.env.cut = False if len(copied_files) == 1: descr = "extracting: " + os.path.basename(one_file.path) else: descr = "extracting files from: " + os.path.basename(one_file.dirname)
[ " obj = CommandLoader(args=['aunpack'] + au_flags \\" ]
3,874
lcc
python
null
c2347b59144779a0b7a159df894795eedab94a268ecd2b43
// // ActivatorTest.cs - NUnit Test Cases for System.Activator // // Authors: // Nick Drochak <ndrochak@gol.com> // Gert Driesen <drieseng@users.sourceforge.net> // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // using System; using System.Globalization; using System.IO; using System.Reflection; #if !TARGET_JVM && !MONOTOUCH // Reflection.Emit not supported for TARGET_JVM using System.Reflection.Emit; #endif using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Security; using System.Security.Permissions; using NUnit.Framework; // The class in this namespace is used by the main test class namespace MonoTests.System.ActivatorTestInternal { // We need a COM class to test the Activator class [ComVisible (true)] public class COMTest : MarshalByRefObject { private int id; public bool constructorFlag = false; public COMTest () { id = 0; } public COMTest (int id) { this.id = id; } // This property is visible [ComVisible (true)] public int Id { get { return id; } set { id = value; } } } [ComVisible (false)] public class NonCOMTest : COMTest { } } namespace MonoTests.System { using MonoTests.System.ActivatorTestInternal; class CustomUserType : Type { public override Assembly Assembly { get { throw new NotImplementedException (); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException (); } } public override Type BaseType { get { throw new NotImplementedException (); } } public override string FullName { get { throw new NotImplementedException (); } } public override Guid GUID { get { throw new NotImplementedException (); } } protected override TypeAttributes GetAttributeFlagsImpl () { throw new NotImplementedException (); } protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException (); } public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) { throw new NotImplementedException (); } public override Type GetElementType () { throw new NotImplementedException (); } public override EventInfo GetEvent (string name, BindingFlags bindingAttr) { throw new NotImplementedException (); } public override EventInfo[] GetEvents (BindingFlags bindingAttr) { throw new NotImplementedException (); } public override FieldInfo GetField (string name, BindingFlags bindingAttr) { throw new NotImplementedException (); } public override FieldInfo[] GetFields (BindingFlags bindingAttr) { throw new NotImplementedException (); } public override Type GetInterface (string name, bool ignoreCase) { throw new NotImplementedException (); } public override Type[] GetInterfaces () { throw new NotImplementedException (); } public override MemberInfo[] GetMembers (BindingFlags bindingAttr) { throw new NotImplementedException (); } protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException (); } public override MethodInfo[] GetMethods (BindingFlags bindingAttr) { throw new NotImplementedException (); } public override Type GetNestedType (string name, BindingFlags bindingAttr) { throw new NotImplementedException (); } public override Type[] GetNestedTypes (BindingFlags bindingAttr) { throw new NotImplementedException (); } public override PropertyInfo[] GetProperties (BindingFlags bindingAttr) { throw new NotImplementedException (); } protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException (); } protected override bool HasElementTypeImpl () { throw new NotImplementedException (); } public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException (); } protected override bool IsArrayImpl () { throw new NotImplementedException (); } protected override bool IsByRefImpl () { throw new NotImplementedException (); } protected override bool IsCOMObjectImpl () { throw new NotImplementedException (); } protected override bool IsPointerImpl () { throw new NotImplementedException (); } protected override bool IsPrimitiveImpl () { throw new NotImplementedException (); } public override Module Module { get { throw new NotImplementedException (); } } public override string Namespace { get { throw new NotImplementedException (); } } public override Type UnderlyingSystemType { get { return this; } } public override object[] GetCustomAttributes (Type attributeType, bool inherit) { throw new NotImplementedException (); } public override object[] GetCustomAttributes (bool inherit) { throw new NotImplementedException (); } public override bool IsDefined (Type attributeType, bool inherit) { throw new NotImplementedException (); } public override string Name { get { throw new NotImplementedException (); } } } [TestFixture] public class ActivatorTest { private string testLocation = typeof (ActivatorTest).Assembly.Location; [Test] public void CreateInstance_Type() { COMTest objCOMTest = (COMTest) Activator.CreateInstance (typeof (COMTest)); Assert.AreEqual ("MonoTests.System.ActivatorTestInternal.COMTest", (objCOMTest.GetType ()).ToString (), "#A02"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void CreateInstance_TypeNull () { Activator.CreateInstance ((Type)null); } [Test] [ExpectedException (typeof (ArgumentException))] public void CreateInstance_CustomType () { Activator.CreateInstance (new CustomUserType ()); } [Test] public void CreateInstance_StringString () { ObjectHandle objHandle = Activator.CreateInstance (null, "MonoTests.System.ActivatorTestInternal.COMTest"); COMTest objCOMTest = (COMTest)objHandle.Unwrap (); objCOMTest.Id = 2; Assert.AreEqual (2, objCOMTest.Id, "#A03"); } [Test]
[ "\t\t[ExpectedException (typeof (ArgumentNullException))]" ]
740
lcc
csharp
null
4f42b848b4da56a77422629e5f5b34775ae49475d94110cf
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import from __future__ import unicode_literals from elmo.test import TestCase from django.contrib.auth.models import User from life.models import Tree, Forest, Locale from l10nstats.models import Run from shipping.models import (Signoff, Action, Application, AppVersion, AppVersionTreeThrough) from shipping.api import (_actions4appversion, actions4appversions, flags4appversions) from datetime import datetime, timedelta from six.moves import range class ApiActionTest(TestCase): fixtures = ["test_repos.json", "test_pushes.json", "signoffs.json"] def test_count(self): """Test that we have the right amount of Signoffs and Actions""" self.assertEqual(Signoff.objects.count(), 5) self.assertEqual(Action.objects.count(), 8) def test_getflags(self): """Test that the list returns the right flags.""" av = AppVersion.objects.get(code="fx1.0") flags = flags4appversions([av], locales=list(range(1, 5))) self.assertDictEqual(flags, {av: { "pl": ["fx1.0", {Action.PENDING: 2}], "de": ["fx1.0", {Action.ACCEPTED: 3}], "fr": ["fx1.0", {Action.REJECTED: 5}], "da": ["fx1.0", {Action.ACCEPTED: 8, Action.PENDING: 7}] }}) class ApiMigrationTest(TestCase): """Testcases for multiple appversions and signoff fallbacks.""" # fixture sets up empty repos and forest for da, de, fr, pl fixtures = ["test_empty_repos.json"] pre_date = datetime(2010, 5, 15) migration = datetime(2010, 6, 1) post_date = datetime(2010, 6, 15) day = timedelta(days=1) def setUp(self): super(ApiMigrationTest, self).setUp() self.forest = Forest.objects.get(name='l10n') self.tree = Tree.objects.create(code='fx', l10n=self.forest) self.app = Application.objects.create(name="firefox", code="fx") self.old_av = self.app.appversion_set.create(code='fx1.0', version='1.0', accepts_signoffs=False) self.new_av = self.app.appversion_set.create(code='fx1.1', version='1.1', accepts_signoffs=True, fallback=self.old_av) (AppVersionTreeThrough.objects .create(appversion=self.old_av, tree=self.tree, start=None, end=self.migration)) (AppVersionTreeThrough.objects .create(appversion=self.new_av, tree=self.tree, start=self.migration, end=None)) self.csnumber = 1 self.localizer = User.objects.create(username='localizer') self.driver = User.objects.create(username='driver') self.actions = [] def _setup(self, locale, before, after): """Create signoffs before and after migration, in the given state""" repo = self.forest.repositories.get(locale=locale) def _create(self, repo, av, d, state): # helper, create Changeset, Push, Signoff and Actions # for the given date if state is None: return cs = repo.changesets.create(revision='%012d' % self.csnumber) self.csnumber += 1 p = repo.push_set.create(user='jane_doe', push_date=d) p.changesets.set([cs]) p.save() so = (Signoff.objects .create(push=p, appversion=av, author=self.localizer, when=d, locale=repo.locale)) a = so.action_set.create(flag=Action.PENDING, author=self.localizer, when=d) self.actions.append(a) if state != Action.PENDING: a = so.action_set.create(flag=state, author=self.driver, when=d + self.day) self.actions.append(a) _create(self, repo, self.old_av, self.pre_date, before) _create(self, repo, self.new_av, self.post_date, after) Run.objects.create(locale=locale, tree=self.tree).activate() return repo def testEmpty(self): locale = Locale.objects.get(code='da') repo = self._setup(locale, None, None) self.assertEqual(repo.changesets.count(), 1) self.assertTupleEqual( _actions4appversion(self.old_av, {locale.id}, None, 100), ({}, {locale.id})) self.assertTupleEqual( _actions4appversion(self.new_av, {locale.id}, None, 100), ({}, {locale.id})) avs = AppVersion.objects.all() flagdata = flags4appversions(avs) self.assertIn(self.old_av, flagdata) self.assertIn(self.new_av, flagdata) self.assertEqual(len(flagdata), 2) self.assertDictEqual(flagdata[self.new_av], {}) self.assertDictEqual(flagdata[self.old_av], flagdata[self.new_av]) def testOneOld(self): """One locale signed off and accepted on old appversion, nothing new on new, thus falling back to the old one. """ locale = Locale.objects.get(code='da') repo = self._setup(locale, Action.ACCEPTED, None) self.assertEqual(repo.changesets.count(), 2) flaglocs4av, not_found = _actions4appversion(self.old_av, {locale.id}, None, 100) self.assertEqual(not_found, set()) self.assertListEqual(list(flaglocs4av.keys()), [locale.id]) flag, action_id = list(flaglocs4av[locale.id].items())[0] self.assertEqual(flag, Action.ACCEPTED) self.assertEqual( Signoff.objects.get(action=action_id).locale_id, locale.id) self.assertTupleEqual( _actions4appversion(self.new_av, {locale.id}, None, 100), ({}, {locale.id})) avs = AppVersion.objects.all() flagdata = flags4appversions(avs) self.assertIn(self.old_av, flagdata) self.assertIn(self.new_av, flagdata) self.assertEqual(len(flagdata), 2) self.assertDictEqual( flagdata[self.new_av], {'da': ['fx1.0', {Action.ACCEPTED: self.actions[1].id}] }) self.assertDictEqual(flagdata[self.old_av], flagdata[self.new_av]) def testOneOldOneNewByActionDate(self): """One locale signed off and accepted on old appversion, nothing new on new, thus falling back to the old one. """ locale = Locale.objects.get(code='da') repo = self._setup(locale, Action.ACCEPTED, Action.ACCEPTED) self.assertEqual(repo.changesets.count(), 3) flaglocs4av, __ = _actions4appversion( self.old_av, {locale.id}, None, 100, ) actions = flaglocs4av[locale.id] action = Action.objects.get(pk=list(actions.values())[0]) self.assertEqual(action.flag, Action.ACCEPTED) flaglocs4av, __ = _actions4appversion( self.old_av, {locale.id}, None, 100, up_until=self.pre_date ) actions = flaglocs4av[locale.id] action = Action.objects.get(pk=list(actions.values())[0]) self.assertEqual(action.flag, Action.PENDING) flaglocs4av, __ = _actions4appversion( self.old_av, {locale.id}, None, 100, up_until=self.post_date ) actions = flaglocs4av[locale.id] action = Action.objects.get(pk=list(actions.values())[0]) self.assertEqual(action.flag, Action.ACCEPTED) def testOneNew(self): """One accepted signoff on the new appversion, none on the old. Old appversion comes back empty. """ locale = Locale.objects.get(code='da') repo = self._setup(locale, None, Action.ACCEPTED) self.assertEqual(repo.changesets.count(), 2) self.assertTupleEqual( _actions4appversion(self.old_av, {locale.id}, None, 100), ({}, {locale.id})) a4av, not_found = _actions4appversion(self.new_av, {locale.id}, None, 100) self.assertEqual(not_found, set()) self.assertListEqual(list(a4av.keys()), [locale.id]) flag, action_id = list(a4av[locale.id].items())[0] self.assertEqual(flag, Action.ACCEPTED) self.assertEqual( Signoff.objects.get(action=action_id).locale_id, locale.id) avs = AppVersion.objects.all() flagdata = flags4appversions(avs) self.assertIn(self.old_av, flagdata) self.assertIn(self.new_av, flagdata) self.assertEqual(len(flagdata), 2) self.assertDictEqual( flagdata[self.new_av], {'da': ['fx1.1', {Action.ACCEPTED: self.actions[1].id}]}) self.assertDictEqual(flagdata[self.old_av], {}) def testOneOldAndNew(self): locale = Locale.objects.get(code='da') repo = self._setup(locale, Action.ACCEPTED, Action.ACCEPTED) self.assertEqual(repo.changesets.count(), 3) avs = AppVersion.objects.all() flagdata = flags4appversions(avs) self.assertIn(self.old_av, flagdata) self.assertIn(self.new_av, flagdata) self.assertEqual(len(flagdata), 2) self.assertDictEqual( flagdata[self.new_av], {'da': ['fx1.1', {Action.ACCEPTED: self.actions[3].id}] }) self.assertDictEqual( flagdata[self.old_av], {'da': ['fx1.0', {Action.ACCEPTED: self.actions[1].id}] }) def testOneOldAndOtherNew(self): da = Locale.objects.get(code='da')
[ " de = Locale.objects.get(code='de')" ]
668
lcc
python
null
af99b5be338dcd6ea99c715d5b5b5bdb923174f4a608472b
# -*- coding: utf-8 -*- import threading import logging import time import select import socket import ssl import struct from errors import * from constants import * import users import channels import blobs import commands import messages import callbacks import tools import soundoutput import mumble_pb2 from pycelt import SUPPORTED_BITSTREAMS class Mumble(threading.Thread): """ Mumble client library main object. basically a thread """ def __init__(self, host=None, port=None, user=None, password=None, client_certif=None, reconnect=False, debug=False): """ host=mumble server hostname or address port=mumble server port user=user to use for the connection password=password for the connection client_certif=client certificate to authenticate the connection (NOT IMPLEMENTED) reconnect=if True, try to reconnect if disconnected debug=if True, send debugging messages (lot of...) to the stdout """ #TODO: client certificate authentication #TODO: exit both threads properly #TODO: use UDP audio threading.Thread.__init__(self) self.Log = logging.getLogger("PyMumble") # logging object for errors and debugging if debug: self.Log.setLevel(logging.DEBUG) else: self.Log.setLevel(logging.ERROR) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s') ch.setFormatter(formatter) self.Log.addHandler(ch) self.parent_thread = threading.current_thread() # main thread of the calling application self.mumble_thread = None # thread of the mumble client library self.host = host self.port = port self.user = user self.password = password self.client_certif = client_certif self.reconnect = reconnect self.receive_sound = False # set to True to treat incoming audio, otherwise it is simply ignored self.loop_rate = PYMUMBLE_LOOP_RATE self.application = PYMUMBLE_VERSION_STRING self.callbacks = callbacks.CallBacks() #callbacks management self.ready_lock = threading.Lock() # released when the connection is fully established with the server self.ready_lock.acquire() def init_connection(self): """Initialize variables that are local to a connection, (needed if the client automatically reconnect)""" self.ready_lock.acquire(False) # reacquire the ready-lock in case of reconnection self.connected = PYMUMBLE_CONN_STATE_NOT_CONNECTED self.control_socket = None self.media_socket = None # Not implemented - for UDP media self.bandwidth = PYMUMBLE_BANDWIDTH # reset the outgoing bandwidth to it's default before connectiong self.server_max_bandwidth = None self.udp_active = False self.users = users.Users(self, self.callbacks) # contain the server's connected users informations self.channels = channels.Channels(self, self.callbacks) # contain the server's channels informations self.blobs = blobs.Blobs(self) # manage the blob objects self.sound_output = soundoutput.SoundOutput(self, PYMUMBLE_AUDIO_PER_PACKET, self.bandwidth) # manage the outgoing sounds self.commands = commands.Commands() # manage commands sent between the main and the mumble threads self.receive_buffer = "" # initialize the control connection input buffer def run(self): """Connect to the server and start the loop in its thread. Retry if requested""" self.mumble_thread = threading.current_thread() # loop if auto-reconnect is requested while True: self.init_connection() # reset the connection-specific object members self.connect() self.loop() if not self.reconnect or not self.parent_thread.is_alive(): break time.sleep(PYMUMBLE_CONNECTION_RETRY_INTERVAL) def connect(self): """Connect to the server""" # Connect the SSL tunnel self.Log.debug("connecting to %s on port %i.", self.host, self.port) std_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.control_socket = ssl.wrap_socket(std_sock, certfile=self.client_certif, ssl_version=ssl.PROTOCOL_TLSv1) self.control_socket.connect((self.host, self.port)) self.control_socket.setblocking(0) # Perform the Mumble authentication version = mumble_pb2.Version() version.version = (PYMUMBLE_PROTOCOL_VERSION[0] << 16) + (PYMUMBLE_PROTOCOL_VERSION[1] << 8) + PYMUMBLE_PROTOCOL_VERSION[2] version.release = self.application version.os = PYMUMBLE_OS_STRING version.os_version = PYMUMBLE_OS_VERSION_STRING self.Log.debug("sending: version: %s", version) self.send_message(PYMUMBLE_MSG_TYPES_VERSION, version) authenticate = mumble_pb2.Authenticate() authenticate.username = self.user authenticate.password = self.password authenticate.celt_versions.extend(SUPPORTED_BITSTREAMS.keys()) # authenticate.celt_versions.extend([-2147483637]) # for debugging - only celt 0.7 authenticate.opus = True self.Log.debug("sending: authenticate: %s", authenticate) self.send_message(PYMUMBLE_MSG_TYPES_AUTHENTICATE, authenticate) self.connected = PYMUMBLE_CONN_STATE_AUTHENTICATING def loop(self): """ Main loop waiting for a message from the server for maximum self.loop_rate time take care of sending the ping take care of sending the queued commands to the server check on every iteration for outgoing sound check for disconnection """ self.Log.debug("entering loop") last_ping = time.time() # keep track of the last ping time # loop as long as the connection and the parent thread are alive while self.connected != PYMUMBLE_CONN_STATE_NOT_CONNECTED and self.parent_thread.is_alive(): if last_ping + PYMUMBLE_PING_DELAY <= time.time(): # when it is time, send the ping self.ping() last_ping = time.time() if self.connected == PYMUMBLE_CONN_STATE_CONNECTED: while self.commands.is_cmd(): self.treat_command(self.commands.pop_cmd()) # send the commands coming from the application to the server self.sound_output.send_audio() # send outgoing audio if available (rlist, wlist, xlist) = select.select([self.control_socket], [], [self.control_socket], self.loop_rate) # wait for a socket activity if self.control_socket in rlist: # something to be read on the control socket self.read_control_messages() elif self.control_socket in xlist: # socket was closed self.control_socket.close() self.connected = PYMUMBLE_CONN_STATE_NOT_CONNECTED def ping(self): """Send the keepalive through available channels""" #TODO: Ping counters ping = mumble_pb2.Ping() ping.timestamp=int(time.time()) self.Log.debug("sending: ping: %s", ping) self.send_message(PYMUMBLE_MSG_TYPES_PING, ping) def send_message(self, type, message): """Send a control message to the server""" packet=struct.pack("!HL", type, message.ByteSize()) + message.SerializeToString() while len(packet)>0: self.Log.debug("sending message") sent=self.control_socket.send(packet) if sent < 0: raise socket.error("Server socket error") packet=packet[sent:] def read_control_messages(self): """Read control messages coming from the server""" # from tools import toHex # for debugging buffer = self.control_socket.recv(PYMUMBLE_READ_BUFFER_SIZE) self.receive_buffer += buffer while len(self.receive_buffer) >= 6: # header is present (type + length) self.Log.debug("read control connection") header = self.receive_buffer[0:6] (type, size) = struct.unpack("!HL", header) # decode header if len(self.receive_buffer) < size+6: # if not length data, read further break # self.Log.debug("message received : " + toHex(self.receive_buffer[0:size+6])) # for debugging message = self.receive_buffer[6:size+6] # get the control message self.receive_buffer = self.receive_buffer[size+6:] # remove from the buffer the read part self.dispatch_control_message(type, message) def dispatch_control_message(self, type, message): """Dispatch control messages based on their type""" self.Log.debug("dispatch control message") if type == PYMUMBLE_MSG_TYPES_UDPTUNNEL: # audio encapsulated in control message self.sound_received(message) elif type == PYMUMBLE_MSG_TYPES_VERSION: mess = mumble_pb2.Version() mess.ParseFromString(message) self.Log.debug("message: Version : %s", mess) elif type == PYMUMBLE_MSG_TYPES_AUTHENTICATE: mess = mumble_pb2.Authenticate() mess.ParseFromString(message) self.Log.debug("message: Authenticate : %s", mess) elif type == PYMUMBLE_MSG_TYPES_PING: mess = mumble_pb2.Ping() mess.ParseFromString(message) self.Log.debug("message: Ping : %s", mess) elif type == PYMUMBLE_MSG_TYPES_REJECT: mess = mumble_pb2.Reject() mess.ParseFromString(message) self.Log.debug("message: reject : %s", mess) self.ready_lock.release() raise ConnectionRejectedError(mess.reason) elif type == PYMUMBLE_MSG_TYPES_SERVERSYNC: # this message finish the connection process mess = mumble_pb2.ServerSync() mess.ParseFromString(message) self.Log.debug("message: serversync : %s", mess) self.users.set_myself(mess.session) self.server_max_bandwidth = mess.max_bandwidth self.set_bandwidth(mess.max_bandwidth) if self.connected == PYMUMBLE_CONN_STATE_AUTHENTICATING: self.connected = PYMUMBLE_CONN_STATE_CONNECTED self.callbacks(PYMUMBLE_CLBK_CONNECTED) self.ready_lock.release() # release the ready-lock elif type == PYMUMBLE_MSG_TYPES_CHANNELREMOVE: mess = mumble_pb2.ChannelRemove() mess.ParseFromString(message) self.Log.debug("message: ChannelRemove : %s", mess) self.channels.remove(mess.channel_id) elif type == PYMUMBLE_MSG_TYPES_CHANNELSTATE: mess = mumble_pb2.ChannelState() mess.ParseFromString(message) self.Log.debug("message: channelstate : %s", mess) self.channels.update(mess) elif type == PYMUMBLE_MSG_TYPES_USERREMOVE: mess = mumble_pb2.UserRemove() mess.ParseFromString(message) self.Log.debug("message: UserRemove : %s", mess) self.users.remove(mess) elif type == PYMUMBLE_MSG_TYPES_USERSTATE: mess = mumble_pb2.UserState() mess.ParseFromString(message) self.Log.debug("message: userstate : %s", mess) self.users.update(mess) elif type == PYMUMBLE_MSG_TYPES_BANLIST: mess = mumble_pb2.BanList() mess.ParseFromString(message) self.Log.debug("message: BanList : %s", mess) elif type == PYMUMBLE_MSG_TYPES_TEXTMESSAGE: mess = mumble_pb2.TextMessage() mess.ParseFromString(message) self.Log.debug("message: TextMessage : %s", mess) self.callbacks(PYMUMBLE_CLBK_TEXTMESSAGERECEIVED, mess.message) elif type == PYMUMBLE_MSG_TYPES_PERMISSIONDENIED: mess = mumble_pb2.PermissionDenied() mess.ParseFromString(message) self.Log.debug("message: PermissionDenied : %s", mess) elif type == PYMUMBLE_MSG_TYPES_ACL: mess = mumble_pb2.ACL() mess.ParseFromString(message) self.Log.debug("message: ACL : %s", mess) elif type == PYMUMBLE_MSG_TYPES_QUERYUSERS: mess = mumble_pb2.QueryUsers() mess.ParseFromString(message) self.Log.debug("message: QueryUsers : %s", mess) elif type == PYMUMBLE_MSG_TYPES_CRYPTSETUP: mess = mumble_pb2.CryptSetup() mess.ParseFromString(message) self.Log.debug("message: CryptSetup : %s", mess) elif type == PYMUMBLE_MSG_TYPES_CONTEXTACTIONADD: mess = mumble_pb2.ContextActionAdd() mess.ParseFromString(message) self.Log.debug("message: ContextActionAdd : %s", mess) elif type == PYMUMBLE_MSG_TYPES_CONTEXTACTION: mess = mumble_pb2.ContextActionAdd() mess.ParseFromString(message) self.Log.debug("message: ContextActionAdd : %s", mess) elif type == PYMUMBLE_MSG_TYPES_USERLIST: mess = mumble_pb2.UserList() mess.ParseFromString(message) self.Log.debug("message: UserList : %s", mess) elif type == PYMUMBLE_MSG_TYPES_VOICETARGET: mess = mumble_pb2.VoiceTarget() mess.ParseFromString(message) self.Log.debug("message: VoiceTarget : %s", mess) elif type == PYMUMBLE_MSG_TYPES_PERMISSIONQUERY: mess = mumble_pb2.PermissionQuery() mess.ParseFromString(message) self.Log.debug("message: PermissionQuery : %s", mess) elif type == PYMUMBLE_MSG_TYPES_CODECVERSION: mess = mumble_pb2.CodecVersion() mess.ParseFromString(message) self.Log.debug("message: CodecVersion : %s", mess) self.sound_output.set_default_codec(mess) elif type == PYMUMBLE_MSG_TYPES_USERSTATS: mess = mumble_pb2.UserStats() mess.ParseFromString(message) self.Log.debug("message: UserStats : %s", mess) elif type == PYMUMBLE_MSG_TYPES_REQUESTBLOB: mess = mumble_pb2.RequestBlob() mess.ParseFromString(message) self.Log.debug("message: RequestBlob : %s", mess) elif type == PYMUMBLE_MSG_TYPES_SERVERCONFIG: mess = mumble_pb2.ServerConfig() mess.ParseFromString(message) self.Log.debug("message: ServerConfig : %s", mess) def set_bandwidth(self, bandwidth): """set the total allowed outgoing bandwidth""" if self.server_max_bandwidth is not None and bandwidth > self.server_max_bandwidth: self.bandwidth = self.server_max_bandwidth else: self.bandwidth = bandwidth self.sound_output.set_bandwidth(self.bandwidth) # communicate the update to the outgoing audio manager def sound_received(self, message): """Manage a received sound message""" # from tools import toHex # for debugging pos = 0 # self.Log.debug("sound packet : " + toHex(message)) # for debugging (header, ) = struct.unpack("!B", message[pos]) # extract the header type = ( header & 0b11100000 ) >> 5 target = header & 0b00011111 pos += 1 if type == PYMUMBLE_AUDIO_TYPE_PING: return session = tools.VarInt() # decode session id pos += session.decode(message[pos:pos+10]) sequence = tools.VarInt() # decode sequence number pos += sequence.decode(message[pos:pos+10]) self.Log.debug("audio packet received from %i, sequence %i, type:%i, target:%i, lenght:%i", session.value, sequence.value, type, target, len(message)) terminator = False # set to true if it's the last 10 ms audio frame for the packet (used with CELT codec) while ( pos < len(message)) and not terminator: # get the audio frames one by one if type == PYMUMBLE_AUDIO_TYPE_OPUS: size = tools.VarInt() # OPUS use varint for the frame length pos += size.decode(message[pos:pos+10]) size = size.value if not (size & 0x2000): # terminator is 0x2000 in the resulting int. terminator = True # should actually always be 0 as OPUS can use variable length audio frames size = size & 0x1fff # isolate the size from the terminator else: (header, ) = struct.unpack("!B", message[pos]) # CELT length and terminator is encoded in a 1 byte int if not (header & 0b10000000): terminator = True size = header & 0b01111111 pos += 1 self.Log.debug("Audio frame : time:%f, last:%s, size:%i, type:%i, target:%i, pos:%i",time.time(), str(terminator), size, type, target, pos-1) if size > 0 and self.receive_sound: # if audio must be treated try: newsound = self.users[session.value].sound.add(message[pos:pos+size], sequence.value, type, target) # add the sound to the user's sound queue self.callbacks(PYMUMBLE_CLBK_SOUNDRECEIVED, self.users[session.value], newsound) self.Log.debug("Audio frame : time:%f last:%s, size:%i, uncompressed:%i, type:%i, target:%i",time.time(), str(terminator), size, newsound.size, type, target) except CodecNotSupportedError as msg: print msg except KeyError: # sound received after user removed pass sequence.value += int(round(newsound.duration / 1000 * 10)) # add 1 sequence per 10ms of audio # if len(message) - pos < size: # raise InvalidFormatError("Invalid audio frame size") pos += size # go further in the packet, after the audio frame #TODO: get position info def set_application_string(self, string): """Set the application name, that can be viewed by other clients on the server""" self.application = string def set_loop_rate(self, rate): """set the current main loop rate (pause per iteration)""" self.loop_rate = rate def get_loop_rate(self): """get the current main loop rate (pause per iteration)""" return(self.loop_rate) def set_receive_sound(self, value): """Enable or disable the management of incoming sounds""" if value: self.receive_sound = True else: self.receive_sound = False def is_ready(self): """Wait for the connection to be fully completed. To be used in the main thread""" self.ready_lock.acquire() self.ready_lock.release() def execute_command(self, cmd, blocking=True): """Create a command to be sent to the server. To be userd in the main thread""" self.is_ready() lock = self.commands.new_cmd(cmd) if blocking and self.mumble_thread is not threading.current_thread(): lock.acquire() lock.release() return lock #TODO: manage a timeout for blocking commands. Currently, no command actually waits for the server to execute # The result of these commands should actually be checked against incoming server updates def treat_command(self, cmd): """Send the awaiting commands to the server. Used in the pymumble thread.""" if cmd.cmd == PYMUMBLE_CMD_MOVE: userstate = mumble_pb2.UserState() userstate.session = cmd.parameters["session"] userstate.channel_id = cmd.parameters["channel_id"] self.Log.debug("Moving to channel") self.send_message(PYMUMBLE_MSG_TYPES_USERSTATE, userstate) cmd.response = True self.commands.answer(cmd) elif cmd.cmd == PYMUMBLE_CMD_MODUSERSTATE: userstate = mumble_pb2.UserState() userstate.session = cmd.parameters["session"] if "mute" in cmd.parameters: userstate.mute = cmd.parameters["mute"] if "self_mute" in cmd.parameters: userstate.self_mute = cmd.parameters["self_mute"] if "deaf" in cmd.parameters: userstate.deaf = cmd.parameters["deaf"] if "self_deaf" in cmd.parameters: userstate.self_deaf = cmd.parameters["self_deaf"] if "suppress" in cmd.parameters: userstate.suppress = cmd.parameters["suppress"] if "recording" in cmd.parameters: userstate.recording = cmd.parameters["recording"] if "comment" in cmd.parameters: userstate.comment = cmd.parameters["comment"] if "texture" in cmd.parameters:
[ " userstate.texture = cmd.parameters[\"texture\"]" ]
1,807
lcc
python
null
835d60f6bb369f4f9e5e17b7af239e5a16e37bb40847519c
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package com.aionemu.gameserver.model.team2.group; import com.aionemu.commons.callbacks.metadata.GlobalCallback; import com.aionemu.gameserver.configs.main.GroupConfig; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.team2.TeamType; import com.aionemu.gameserver.model.team2.common.events.PlayerLeavedEvent.LeaveReson; import com.aionemu.gameserver.model.team2.common.events.ShowBrandEvent; import com.aionemu.gameserver.model.team2.common.events.TeamKinahDistributionEvent; import com.aionemu.gameserver.model.team2.common.legacy.GroupEvent; import com.aionemu.gameserver.model.team2.common.legacy.LootGroupRules; import com.aionemu.gameserver.model.team2.group.callback.AddPlayerToGroupCallback; import com.aionemu.gameserver.model.team2.group.callback.PlayerGroupCreateCallback; import com.aionemu.gameserver.model.team2.group.callback.PlayerGroupDisbandCallback; import com.aionemu.gameserver.model.team2.group.events.*; import com.aionemu.gameserver.network.aion.serverpackets.SM_QUESTION_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.restrictions.RestrictionsManager; import com.aionemu.gameserver.services.AutoGroupService; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.utils.ThreadPoolManager; import com.aionemu.gameserver.utils.TimeUtil; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import javolution.util.FastMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * @author ATracer */ public class PlayerGroupService { private static final Logger log = LoggerFactory.getLogger(PlayerGroupService.class); private static final Map<Integer, PlayerGroup> groups = new ConcurrentHashMap<Integer, PlayerGroup>(); private static final AtomicBoolean offlineCheckStarted = new AtomicBoolean(); private static FastMap<Integer, PlayerGroup> groupMembers; public static final void inviteToGroup(final Player inviter, final Player invited) { if (canInvite(inviter, invited)) { PlayerGroupInvite invite = new PlayerGroupInvite(inviter, invited); if (invited.getResponseRequester().putRequest(SM_QUESTION_WINDOW.STR_PARTY_DO_YOU_ACCEPT_INVITATION, invite)) { PacketSendUtility.sendPacket(invited, new SM_QUESTION_WINDOW(SM_QUESTION_WINDOW.STR_PARTY_DO_YOU_ACCEPT_INVITATION, 0, 0, inviter.getName())); } } } public static final boolean canInvite(Player inviter, Player invited) { if (inviter.isInInstance()) { if (AutoGroupService.getInstance().isAutoInstance(inviter.getInstanceId())) { PacketSendUtility.sendPacket(inviter, SM_SYSTEM_MESSAGE.STR_MSG_INSTANCE_CANT_INVITE_PARTY_COMMAND); return false; } } if (invited.isInInstance()) { if (AutoGroupService.getInstance().isAutoInstance(invited.getInstanceId())) { PacketSendUtility.sendPacket(inviter, SM_SYSTEM_MESSAGE.STR_MSG_INSTANCE_CANT_INVITE_PARTY_COMMAND); return false; } } return RestrictionsManager.canInviteToGroup(inviter, invited); } @GlobalCallback(PlayerGroupCreateCallback.class) public static final PlayerGroup createGroup(Player leader, Player invited, TeamType type) { PlayerGroup newGroup = new PlayerGroup(new PlayerGroupMember(leader), type); groups.put(newGroup.getTeamId(), newGroup); addPlayer(newGroup, leader); addPlayer(newGroup, invited); if (offlineCheckStarted.compareAndSet(false, true)) { initializeOfflineCheck(); } return newGroup; } private static void initializeOfflineCheck() { ThreadPoolManager.getInstance().scheduleAtFixedRate(new OfflinePlayerChecker(), 1000, 30 * 1000); } @GlobalCallback(AddPlayerToGroupCallback.class) public static final void addPlayerToGroup(PlayerGroup group, Player invited) { group.addMember(new PlayerGroupMember(invited)); } /** * Change group's loot rules and notify team members */ public static final void changeGroupRules(PlayerGroup group, LootGroupRules lootRules) { group.onEvent(new ChangeGroupLootRulesEvent(group, lootRules)); } /** * Player entered world - search for non expired group */ public static final void onPlayerLogin(Player player) { for (PlayerGroup group : groups.values()) { PlayerGroupMember member = group.getMember(player.getObjectId()); if (member != null) { group.onEvent(new PlayerConnectedEvent(group, player)); } } } /** * Player leaved world - set last online on member */ public static final void onPlayerLogout(Player player) { PlayerGroup group = player.getPlayerGroup2(); if (group != null) { PlayerGroupMember member = group.getMember(player.getObjectId()); member.updateLastOnlineTime(); group.onEvent(new PlayerDisconnectedEvent(group, player)); } } /** * Update group members to some event of player */ public static final void updateGroup(Player player, GroupEvent groupEvent) { PlayerGroup group = player.getPlayerGroup2(); if (group != null) { group.onEvent(new PlayerGroupUpdateEvent(group, player, groupEvent)); } } /** * Add player to group */ public static final void addPlayer(PlayerGroup group, Player player) { Preconditions.checkNotNull(group, "Group should not be null"); group.onEvent(new PlayerEnteredEvent(group, player)); } /** * Remove player from group (normal leave, or kick offline player) */ public static final void removePlayer(Player player) { PlayerGroup group = player.getPlayerGroup2(); if (group != null) { group.onEvent(new PlayerGroupLeavedEvent(group, player)); } } /** * Remove player from group (ban) */ public static final void banPlayer(Player bannedPlayer, Player banGiver) { Preconditions.checkNotNull(bannedPlayer, "Banned player should not be null"); Preconditions.checkNotNull(banGiver, "Bangiver player should not be null"); PlayerGroup group = banGiver.getPlayerGroup2(); if (group != null) { if (group.hasMember(bannedPlayer.getObjectId())) { group.onEvent(new PlayerGroupLeavedEvent(group, bannedPlayer, LeaveReson.BAN, banGiver.getName())); } else { log.warn("TEAM2: banning player not in group {}", group.onlineMembers()); } } } /** * Disband group by removing all players one by one */ @GlobalCallback(PlayerGroupDisbandCallback.class) public static void disband(PlayerGroup group) { Preconditions.checkState(group.onlineMembers() <= 1, "Can't disband group with more than one online member"); groups.remove(group.getTeamId()); group.onEvent(new GroupDisbandEvent(group)); } /** * Share specific amount of kinah between group members */ public static void distributeKinah(Player player, long kinah) { PlayerGroup group = player.getPlayerGroup2(); if (group != null) { group.onEvent(new TeamKinahDistributionEvent<PlayerGroup>(group, player, kinah)); } } /** * Show specific mark on top of player */ public static void showBrand(Player player, int targetObjId, int brandId) { PlayerGroup group = player.getPlayerGroup2(); if (group != null) { group.onEvent(new ShowBrandEvent<PlayerGroup>(group, targetObjId, brandId)); } } public static void changeLeader(Player player) {
[ " PlayerGroup group = player.getPlayerGroup2();" ]
799
lcc
java
null
67a6dc96ef742343a5472232bc814279dccd54c1055439e8
# -*- coding: utf-8 -*- from io import BytesIO as StringIO from amoco.config import conf from amoco.logger import Log logger = Log(__name__) logger.debug("loading module") import re try: from pygments.token import Token from pygments.style import Style from pygments.lexer import RegexLexer from pygments.formatters import * except ImportError: logger.info("pygments package not found, no renderer defined") has_pygments = False # metaclass definition, with a syntax compatible with python2 and python3 class TokenType(type): def __getattr__(cls, key): return key Token_base = TokenType("Token_base", (), {}) class Token(Token_base): pass class NullFormatter(object): def __init__(self, **options): self.options = options def format(self, tokensource, outfile): for t, v in tokensource: outfile.write(v.encode("latin1")) Formats = { "Null": NullFormatter(), } else: logger.info("pygments package imported") has_pygments = True class DarkStyle(Style): default_style = "" styles = { # Token.Literal: '#fff', Token.Address: "#fb0", Token.Constant: "#f30", # Token.Prefix: '#fff', Token.Mnemonic: "bold", Token.Register: "#33f", Token.Memory: "#3ff", Token.Comment: "#8f8", Token.Name: "underline", Token.Tainted: "bold #f00", Token.Column: "#bbb", Token.Hide: "#222", } class LightStyle(Style): default_style = "" styles = { Token.Literal: "#000", Token.Address: "#b58900", Token.Constant: "#dc322f", Token.Prefix: "#000", Token.Mnemonic: "bold", Token.Register: "#268bd2", Token.Memory: "#859900", Token.Comment: "#93a1a1", Token.Name: "underline", Token.Tainted: "bold #f00", Token.Column: "#222", Token.Hide: "#bbb", } DefaultStyle = DarkStyle Formats = { "Null": NullFormatter(encoding="utf-8"), "Terminal": TerminalFormatter(style=DefaultStyle, encoding="utf-8"), "Terminal256": Terminal256Formatter(style=DefaultStyle, encoding="utf-8"), "TerminalDark": Terminal256Formatter(style=DarkStyle, encoding="utf-8"), "TerminalLight": Terminal256Formatter(style=LightStyle, encoding="utf-8"), "Html": HtmlFormatter(style=LightStyle, encoding="utf-8"), } def highlight(toks, formatter=None, outfile=None): formatter = formatter or Formats.get(conf.UI.formatter) if isinstance(formatter, str): formatter = Formats[formatter] outfile = outfile or StringIO() formatter.format(toks, outfile) return outfile.getvalue().decode("utf-8") def TokenListJoin(j, lst): if isinstance(j, str): j = (Token.Literal, j) res = lst[0:1] for x in lst[1:]: res.append(j) res.append(x) return res class vltable(object): """ variable length table: """ def __init__(self, rows=None, formatter=None, outfile=None): if rows is None: rows = [] self.rows = rows self.rowparams = { "colsize": {}, "hidden_c": set(), "squash_c": True, "formatter": formatter, "outfile": outfile, } self.maxlength = float("inf") self.hidden_r = set() self.hidden_c = self.rowparams["hidden_c"] self.squash_r = True self.colsize = self.rowparams["colsize"] self.update() self.header = "" self.footer = "" def update(self, *rr): for c in range(self.ncols): cz = self.colsize.get(c, 0) if len(rr) > 0 else 0 self.colsize[c] = max(cz, self.getcolsize(c, rr, squash=False)) def getcolsize(self, c, rr=None, squash=True): cz = 0 if not rr: rr = range(self.nrows) for i in rr: if self.rowparams["squash_c"] and (i in self.hidden_r): if squash: continue cz = max(cz, self.rows[i].colsize(c)) return cz @property def width(self): sep = self.rowparams.get("sep", "") cs = self.ncols * len(sep) return sum(self.colsize.values(), cs) def setcolsize(self, c, value): self.colsize[c] = value def addrow(self, toks): self.rows.append(tokenrow(toks)) self.update(-1) return self def hiderow(self, n): self.hidden_r.add(n) def showrow(self, n): self.hidden_r.remove(n) def hidecolumn(self, n): self.hidden_c.add(n) def showcolumn(self, n): self.hidden_c.remove(n) def showall(self): self.hidden_r = set() self.rowparams["hidden_c"] = set() self.hidden_c = self.rowparams["hidden_c"] return self def grep(self, regex, col=None, invert=False): L = set() R = range(self.nrows) for i in R: if i in self.hidden_r: continue C = self.rows[i].rawcols(col) for c, s in enumerate(C): if c in self.hidden_c: continue if re.search(regex, s): L.add(i) break if not invert: L = set(R) - L for n in L: self.hiderow(n) return self @property def nrows(self): return len(self.rows) @property def ncols(self): if self.nrows > 0: return max((r.ncols for r in self.rows)) else: return 0 def __str__(self): s = [] formatter = self.rowparams["formatter"] outfile = self.rowparams["outfile"] for i in range(self.nrows): if i in self.hidden_r: if not self.squash_r: s.append( highlight( [ ( Token.Hide, self.rows[i].show(raw=True, **self.rowparams), ) ], formatter, outfile, ) ) else: s.append(self.rows[i].show(**self.rowparams)) if len(s) > self.maxlength: s = s[: self.maxlength - 1] s.append(highlight([(Token.Literal, "...")], formatter, outfile)) if self.header: s.insert(0, self.header) if self.footer: s.append(self.footer) return "\n".join(s) class tokenrow(object): def __init__(self, toks=None): if toks is None: toks = [] self.toks = [(t, "%s" % s) for (t, s) in toks] self.maxwidth = float("inf") self.align = "<" self.fill = " " self.separator = "" self.cols = self.cut() def cut(self): C = [] c = [] for t in self.toks: c.append(t) if t[0] == Token.Column: C.append(c) c = [] C.append(c) return C def colsize(self, c): if c >= len(self.cols): return 0 return sum((len(t[1]) for t in self.cols[c] if t[0] != Token.Column)) @property def ncols(self): return len(self.cols) def rawcols(self, j=None): r = [] cols = self.cols if j is not None: cols = self.cols[j : j + 1] for c in cols: r.append("".join([t[1] for t in c])) return r def show(self, raw=False, **params): formatter = params.get("formatter", None) outfile = params.get("outfile", None) align = params.get("align", self.align) fill = params.get("fill", self.fill) sep = params.get("sep", self.separator) width = params.get("maxwidth", self.maxwidth) colsz = params.get("colsize") hidden_c = params.get("hidden_c", set()) squash_c = params.get("squash_c", True) head = params.get("head", "") tail = params.get("tail", "") if raw: formatter = "Null" outfile = None
[ " r = [head]" ]
734
lcc
python
null
d8447e7d54fe3091a9199e7ab96ea24e60a7f9976caf7d82
from __future__ import print_function, division, absolute_import # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # try: import unittest2 as unittest except ImportError: import unittest #from gi.repository import Gtk from datetime import datetime, timedelta from rhsm.certificate import GMT from subscription_manager.ga import Gtk as ga_Gtk from subscription_manager.gui.storage import MappedTreeStore from subscription_manager.gui.widgets import MachineTypeColumn, QuantitySelectionColumn, \ SubDetailsWidget, ContractSubDetailsWidget, \ DatePicker, HasSortableWidget from dateutil.tz import tzlocal from nose.plugins.attrib import attr @attr('gui') class TestSubDetailsWidget(unittest.TestCase): widget = SubDetailsWidget sku_text = "Some SKU" expected_sub_text = "All Available Subscription Text" def show(self, details): details.show(name="Some Product", contract="123123", start=datetime.now(GMT()), end=datetime.now(GMT()) + timedelta(days=365), highlight="some filter", support_level="Standard", support_type="L1", sku=self.sku_text) def test_show(self): details = self.widget(None) self.show(details) def test_clear(self): details = self.widget(None) self.show(details) details.clear() def test_a11y(self): details = self.widget(None) self.show(details) sub_text = details.subscription_text.get_accessible().get_name() self.assertEqual(self.expected_sub_text, sub_text) @attr('gui') class TestContractSubDetailsWidget(TestSubDetailsWidget): widget = ContractSubDetailsWidget expected_sub_text = "Subscription Text" def test_get_expired_bg(self): details = self.widget(None) self.show(details) yesterday = datetime.now(GMT()) - timedelta(days=1) bg_color = details._get_date_bg(yesterday, True) self.assertEqual(details.expired_color, bg_color) def test_get_warning_bg(self): details = self.widget(None) self.show(details) tomorrow = datetime.now(GMT()) + timedelta(days=1) bg_color = details._get_date_bg(tomorrow, True) self.assertEqual(details.warning_color, bg_color) def test_get_details(self): details = self.widget(None) reasons = ['reason 1', 'reason 2'] details.show("Some Product", reasons=reasons, start=datetime.now(GMT()), end=datetime.now(GMT()) + timedelta(days=365)) buff = details.details_view.get_buffer() result_list = buff.get_text(buff.get_bounds()[0], buff.get_bounds()[1], include_hidden_chars=False).split("\n") self.assertEqual(reasons, result_list) def testVirtOnly(self): details = self.widget(None) self.show(details) d = datetime(2011, 4, 16, tzinfo=tzlocal()) start_date = datetime(d.year, d.month, d.day, tzinfo=tzlocal()) end_date = datetime(d.year + 1, d.month, d.day, tzinfo=tzlocal()) details.show('noname', contract='c', start=start_date, end=end_date, account='a', management='m', support_level='s_l', support_type='s_t', virt_only='v_o') s_iter = details.virt_only_text.get_buffer().get_start_iter() e_iter = details.virt_only_text.get_buffer().get_end_iter() self.assertEqual(details.virt_only_text.get_buffer().get_text(s_iter, e_iter, False), 'v_o') @attr('gui') class TestDatePicker(unittest.TestCase): def test_date_picker_date(self): d = datetime(2033, 12, 29, tzinfo=tzlocal()) self._assert_is_isoformat(d) def test_date_validate_2000_12_1(self): d = datetime(2000, 12, 1, tzinfo=tzlocal()) self._assert_is_isoformat(d) def test_date_validate_2000_1_22(self): d = datetime(2000, 1, 12, tzinfo=tzlocal()) self._assert_is_isoformat(d) def test_date_validate_1_1_2000(self): d = datetime(2000, 1, 1, tzinfo=tzlocal()) self._assert_is_isoformat(d) # why? because some locales fail to parse in dates with # double digt months def test_date_validate_12_29_2020(self): #with Capture(silent=True): d = datetime(2020, 12, 29, tzinfo=tzlocal()) self._assert_is_isoformat(d) def _assert_is_isoformat(self, d): date_picker = DatePicker(d) valid = date_picker.date_entry_validate() self.assertTrue(valid) self.assertEqual(date_picker._date_entry.get_text(), d.date().isoformat()) class BaseColumnTest(unittest.TestCase): def _assert_column_value(self, column_class, model_bool_val, expected_text): model = ga_Gtk.ListStore(bool) model.append([model_bool_val]) column = column_class(0) column._render_cell(None, column.renderer, model, model.get_iter_first()) self.assertEqual(expected_text, column.renderer.get_property("text")) @attr('gui') class TestHasSortableWidget(unittest.TestCase): def _run_cases(self, cases, expected): for index, case in enumerate(cases): result = HasSortableWidget.compare_text(*case) self.assertEqual(result, expected[index]) def test_compare_text_ints(self): # Two string representations of ints str1 = '1' str2 = '2' cases = [ (str1, str2), # x < y should return -1 (str2, str1), # x > y should return 1 (str1, str1) # x == y should return 0 ] expected = [ -1, 1, 0 ] self._run_cases(cases, expected) def test_compare_text_unlimited(self): # Test unlimited comparison unlimited = 'Unlimited' str1 = '1' cases = [ (unlimited, str1), # Unlimited, 1 should return 1 (str1, unlimited), # 1, Unlimited should return -1 (unlimited, unlimited) # Unlimited, Unlimited should return 0 ] expected = [ 1, -1, 0 ] self._run_cases(cases, expected) def test_compare_alphabetic_text(self): cases = [ ('a', 'b'), ('b', 'a'), ('a', 'a') ] def _cmp(x1, x2): if x1 < x2: return -1 elif x1 == x2: return 0 else: return 1 expected = [_cmp(*case) for case in cases] self._run_cases(cases, expected) @attr('gui') class TestMachineTypeColumn(BaseColumnTest): def test_render_virtual_when_virt_only(self): self._assert_column_value(MachineTypeColumn, True, MachineTypeColumn.VIRTUAL_MACHINE) def test_render_physical_when_not_virt_only(self): self._assert_column_value(MachineTypeColumn, False, MachineTypeColumn.PHYSICAL_MACHINE) @attr('gui') class TestQuantitySelectionColumnTests(unittest.TestCase): def test__update_cell_based_on_data_clears_cell_when_row_has_children(self): column, tree_model, tree_iter = self._setup_column(1, False) tree_model.add_map(tree_iter, self._create_store_map(1, False, 15, 2)) column.quantity_renderer.set_property("text", "22") column._update_cell_based_on_data(None, column.quantity_renderer, tree_model, tree_iter) self.assertEqual("", column.quantity_renderer.get_property("text")) def test_update_cell_based_on_data_does_not_clear_cell_when_row_has_no_children(self):
[ " column, tree_model, tree_iter = self._setup_column(1, False)" ]
630
lcc
python
null
01927bf90663c8e45781b1b5ddce62bfaf81ca7f023ef08b
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.tag; import javax.servlet.jsp.tagext.Tag; import lucee.commons.color.ColorCaster; import lucee.commons.lang.StringUtil; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.exp.TagNotSupported; import lucee.runtime.ext.tag.TagImpl; import lucee.runtime.type.util.ListUtil; /** * Used with cfgrid in a cfform, you use cfgridcolumn to specify column data in a cfgrid control. * Font and alignment attributes used in cfgridcolumn override any global font or alignment settings * defined in cfgrid. * * * **/ public final class GridColumn extends TagImpl { private GridColumnBean column = new GridColumnBean(); public GridColumn() throws TagNotSupported { throw new TagNotSupported("GridColumn"); } private String valuesdelimiter = ","; private String valuesdisplay; private String values; @Override public void release() { column = new GridColumnBean(); valuesdelimiter = ","; valuesdisplay = null; values = null; } /** * @param mask the mask to set */ public void setMask(String mask) { column.setMask(mask); } /** * set the value display Yes or No. Use to hide columns. Default is Yes to display the column. * * @param display value to set **/ public void setDisplay(boolean display) { column.setDisplay(display); } /** * set the value width The width of the column, in pixels. Default is the width of the column head * text. * * @param width value to set **/ public void setWidth(double width) { column.setWidth((int) width); } /** * set the value headerfontsize Font size to use for the column header, in pixels. Default is as * specified by the orresponding attribute of cfgrid. * * @param headerfontsize value to set **/ public void setHeaderfontsize(double headerfontsize) { column.setHeaderFontSize((int) headerfontsize); } /** * set the value hrefkey The name of a query column when the grid uses a query. The column specified * becomes the Key regardless of the select mode for the grid. * * @param hrefkey value to set **/ public void setHrefkey(String hrefkey) { column.setHrefKey(hrefkey); } /** * set the value target The name of the frame in which to open the link specified in href. * * @param target value to set **/ public void setTarget(String target) { column.setTarget(target); } /** * set the value values Formats cells in the column as drop down list boxes. lets end users select * an item in a drop down list. Use the values attribute to specify the items you want to appear in * the drop down list. * * @param values value to set **/ public void setValues(String values) { this.values = values; } /** * set the value headerfont Font to use for the column header. Default is as specified by the * corresponding attribute of cfgrid. * * @param headerfont value to set **/ public void setHeaderfont(String headerfont) { column.setHeaderFont(headerfont); } /** * set the value font Font name to use for data in the column. Defaults is the font specified by * cfgrid. * * @param font value to set **/ public void setFont(String font) { column.setFont(font); } /** * set the value italic Yes or No. Yes displays all grid control text in italic. Default is as * specified by the corresponding attribute of cfgrid. * * @param italic value to set **/ public void setItalic(boolean italic) { column.setItalic(italic); } /** * set the value bgcolor Color value for the background of the grid column, or an expression you can * use to manipulate grid column background color. Valid color entries are: black, magenta, cyan, * orange, darkgray, pink, gray, white (default), lightgray, yellow. * * @param bgcolor value to set * @throws ExpressionException **/ public void setBgcolor(String bgcolor) throws ExpressionException { column.setBgColor(ColorCaster.toColor(bgcolor)); } /** * set the value valuesdisplay Used to map elements specified in the values attribute to a string of * your choice to display in the drop down list. Enter comma separated strings and/or numeric * range(s). * * @param valuesdisplay value to set **/ public void setValuesdisplay(String valuesdisplay) { this.valuesdisplay = valuesdisplay; } /** * set the value headeritalic Yes or No. Yes displays column header text in italic. Default is as * specified by the corresponding attribute of cfgrid. * * @param headeritalic value to set **/ public void setHeaderitalic(boolean headeritalic) { column.setHeaderItalic(headeritalic); } /** * set the value name A name for the grid column element. If the grid uses a query, the column name * must specify the name of a query column. * * @param name value to set **/ public void setName(String name) { column.setName(name); } /** * set the value href URL to associate with the grid item. You can specify a URL that is relative to * the current page * * @param href value to set **/ public void setHref(String href) { column.setHref(href); } /** * set the value type * * @param type value to set **/ public void setType(String type) { column.setType(type); } /** * set the value valuesdelimiter Character to use as a delimiter in the values and valuesDisplay * attributes. Default is "," (comma). * * @param valuesdelimiter value to set **/ public void setValuesdelimiter(String valuesdelimiter) { this.valuesdelimiter = valuesdelimiter; } /** * set the value numberformat The format for displaying numeric data in the grid. For information * about mask characters, see "numberFormat mask characters". * * @param numberformat value to set **/ public void setNumberformat(String numberformat) { column.setNumberFormat(numberformat); } /** * set the value header Text for the column header. The value of header is used only when the cfgrid * colHeaders attribute is Yes (or omitted, since it defaults to Yes). * * @param header value to set **/ public void setHeader(String header) { column.setHeader(header); } /** * set the value textcolor Color value for grid element text in the grid column, or an expression * you can use to manipulate text color in grid column elements. Valid color entries are: black * (default), magenta, cyan, orange, arkgray, pink, gray, white, lightgray, yellow * * @param textcolor value to set * @throws ExpressionException **/ public void setTextcolor(String textcolor) throws ExpressionException { column.setTextColor(ColorCaster.toColor(textcolor)); } /** * set the value select Yes or No. Yes lets end users select a column in a grid control. When No, * the column cannot be edited, even if the cfgrid insert or delete attributes are enabled. The * value of the select attribute is ignored if the cfgrid selectMode attribute is set to Row or * Browse. * * @param select value to set **/ public void setSelect(boolean select) { column.setSelect(select); } /** * set the value headeralign Alignment for the column header text. Default is as specified by * cfgrid. * * @param headeralign value to set **/ public void setHeaderalign(String headeralign) { column.setHeaderAlign(headeralign); } /** * set the value dataalign Alignment for column data. Entries are: left, center, or right. Default * is as specified by cfgrid. * * @param dataalign value to set **/ public void setDataalign(String dataalign) { column.setDataAlign(dataalign); } /** * set the value bold Yes or No. Yes displays all grid control text in boldface. Default is as * specified by the corresponding attribute of cfgrid. * * @param bold value to set **/ public void setBold(boolean bold) { column.setBold(bold); } /** * set the value headerbold Yes or No. Yes displays header text in boldface. Default is as specified * by the corresponding attribute of cfgrid. * * @param headerbold value to set **/ public void setHeaderbold(boolean headerbold) { column.setHeaderBold(headerbold); } /** * set the value colheadertextcolor Color value for the grid control column header text. Entries * are: black (default), magenta, cyan, orange, darkgray, pink, gray, white, lightgray, yellow. * * @param headertextcolor value to set * @throws ExpressionException **/ public void setHeadertextcolor(String headertextcolor) throws ExpressionException { column.setHeaderTextColor(ColorCaster.toColor(headertextcolor)); } /** * set the value fontsize Font size for text in the column. Default is the font specified by cfgrid. * * @param fontsize value to set **/ public void setFontsize(double fontsize) { column.setFontSize((int) fontsize); } @Override public int doStartTag() throws PageException { if (!StringUtil.isEmpty(values)) column.setValues(ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(values, valuesdelimiter))); if (!StringUtil.isEmpty(valuesdisplay)) column.setValuesDisplay(ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(valuesdisplay, valuesdelimiter))); // provide to parent Tag parent = this; do { parent = parent.getParent();
[ "\t if (parent instanceof Grid) {" ]
1,452
lcc
java
null
a9f806dacfe9f5d8c7b09f082dcb1b2d02bd3ec0647bbbed
/* * "NorseWorld: Ragnarok", a roguelike game for PCs. * Copyright (C) 2002-2008, 2014 by Serg V. Zhdanovskih. * * This file is part of "NorseWorld: Ragnarok". * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Xml; using BSLib; using NWR.Game; using NWR.Game.Types; using ZRLib.Core; namespace NWR.Database { public sealed class CreatureEntry : VolatileEntry { public sealed class InventoryEntry { public string ItemSign; public int CountMin; public int CountMax; public ItemState State; public int Bonus; } public RaceID Race; public string Gfx; public string Sfx; public CreatureFlags Flags; public short MinHP; public short MaxHP; public short AC; public short ToHit; public sbyte Speed; public sbyte Attacks; public short Constitution; public short Strength; public ushort Dexterity; public short MinDB; public short MaxDB; public byte Survey; public string[] Lands; public sbyte Level; public Alignment Alignment; public CreatureSex Sex; public float Weight; public bool Extinctable; public int FleshEffect; public short FleshSatiety; public AttributeList Abilities; public AttributeList Skills; public InventoryEntry[] Inventory; public char Symbol; public byte Hear; public byte Smell; public byte Perception; // deprecated??? public DialogEntry Dialog; public byte FramesCount; public byte FramesLoaded; public int ImageIndex; public int GrayImageIndex; public bool Respawn { get { return Flags.Contains(CreatureFlags.esRespawn); } } public bool CorpsesPersist { get { return Flags.Contains(CreatureFlags.esCorpsesPersist); } } public bool WithoutCorpse { get { return Flags.Contains(CreatureFlags.esWithoutCorpse); } } public bool Remains { get { return Flags.Contains(CreatureFlags.esRemains); } } public CreatureEntry(object owner) : base(owner) { Lands = new string[0]; Inventory = new InventoryEntry[0]; Abilities = new AttributeList(); Skills = new AttributeList(); Dialog = new DialogEntry(); } protected override void Dispose(bool disposing) { if (disposing) { Abilities.Dispose(); Skills.Dispose(); Dialog.Dispose(); Inventory = null; Lands = null; } base.Dispose(disposing); } public override void LoadXML(XmlNode element, FileVersion version) { try { base.LoadXML(element, version); Race = (RaceID)Enum.Parse(typeof(RaceID), ReadElement(element, "Race")); Gfx = ReadElement(element, "gfx"); Sfx = ReadElement(element, "sfx"); string signs = ReadElement(element, "Signs"); Flags = new CreatureFlags(signs); if (!signs.Equals(Flags.Signature)) { throw new Exception("CreatureSigns not equals " + Convert.ToString(GUID)); } MinHP = Convert.ToInt16(ReadElement(element, "minHP")); MaxHP = Convert.ToInt16(ReadElement(element, "maxHP")); AC = Convert.ToInt16(ReadElement(element, "AC")); Speed = Convert.ToSByte(ReadElement(element, "Speed")); ToHit = Convert.ToInt16(ReadElement(element, "ToHit")); Attacks = Convert.ToSByte(ReadElement(element, "Attacks")); Constitution = Convert.ToInt16(ReadElement(element, "Constitution")); Strength = Convert.ToInt16(ReadElement(element, "Strength")); MinDB = Convert.ToInt16(ReadElement(element, "minDB")); MaxDB = Convert.ToInt16(ReadElement(element, "maxDB")); Survey = Convert.ToByte(ReadElement(element, "Survey")); Level = Convert.ToSByte(ReadElement(element, "Level")); Alignment = (Alignment)Enum.Parse(typeof(Alignment), ReadElement(element, "Alignment")); Weight = (float)ConvertHelper.ParseFloat(ReadElement(element, "Weight"), 0.0f, true); Sex = StaticData.GetSexBySign(ReadElement(element, "Sex")); FleshEffect = Convert.ToInt32(ReadElement(element, "FleshEffect")); FleshSatiety = Convert.ToInt16(ReadElement(element, "FleshSatiety")); string sym = ReadElement(element, "Symbol"); Symbol = (string.IsNullOrEmpty(sym) ? '?' : sym[0]); Extinctable = Convert.ToBoolean(ReadElement(element, "Extinctable")); Dexterity = Convert.ToUInt16(ReadElement(element, "Dexterity")); Hear = Convert.ToByte(ReadElement(element, "Hear")); Smell = Convert.ToByte(ReadElement(element, "Smell")); FramesCount = Convert.ToByte(ReadElement(element, "FramesCount")); XmlNodeList nl = element.SelectSingleNode("Lands").ChildNodes; Lands = new string[nl.Count]; for (int i = 0; i < nl.Count; i++) { XmlNode n = nl[i]; Lands[i] = n.Attributes["ID"].InnerText; } nl = element.SelectSingleNode("Abilities").ChildNodes; for (int i = 0; i < nl.Count; i++) { XmlNode n = nl[i]; AbilityID ab = (AbilityID)Enum.Parse(typeof(AbilityID), n.Attributes["ID"].InnerText); int val = Convert.ToInt32(n.Attributes["Value"].InnerText); Abilities.Add((int)ab, val); } nl = element.SelectSingleNode("Skills").ChildNodes; for (int i = 0; i < nl.Count; i++) { XmlNode n = nl[i]; SkillID sk = (SkillID)Enum.Parse(typeof(SkillID), n.Attributes["ID"].InnerText); int val = Convert.ToInt32(n.Attributes["Value"].InnerText); Skills.Add((int)sk, val); } nl = element.SelectSingleNode("Inventory").ChildNodes; Inventory = new InventoryEntry[nl.Count]; for (int i = 0; i < nl.Count; i++) { XmlNode n = nl[i]; InventoryEntry invEntry = new InventoryEntry(); Inventory[i] = invEntry; invEntry.ItemSign = n.Attributes["ID"].InnerText; invEntry.CountMin = Convert.ToInt32(n.Attributes["CountMin"].InnerText); invEntry.CountMax = Convert.ToInt32(n.Attributes["CountMax"].InnerText); XmlAttribute stat = n.Attributes["Status"]; if (stat != null) ParseStatus(invEntry, stat.InnerText); }
[ " XmlNodeList dnl = element.SelectNodes(\"Dialog\");" ]
667
lcc
csharp
null
60f43ea884b0dda7f3dd9e6fee352e3b1f7715b7cbef50df
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Engines.PartySystem; using Server.Mobiles; using Server.Network; using Server.Regions; namespace Server.Items { public enum PeerlessList { None, DreadHorn, Exodus, MelisandeTrammel, MelisandeFelucca, Travesty, InterredGrizzle, ParoxysmusTrammel, ParoxysmusFelucca, ShimmeringEffusionTrammel, ShimmeringEffusionFelucca, Dummy } public class AltarPeerless : Container { public static bool IsPeerlessBoss( Mobile m ) { return m is DreadHorn || m is LadyMelisande || m is Travesty || m is ChiefParoxysmus || m is ShimmeringEffusion || m is MonstrousInterredGrizzle; } public override int DefaultMaxWeight { get { return 0; } } public override bool IsDecoContainer { get { return false; } } private PeerlessRegion m_Region; private bool m_actived = false; private BaseActivation[] m_key = new BaseActivation[3]; private Mobile m_Boss; private PeerlessList m_Peerless = 0; private Timer m_ResetTimer; private Timer m_PeerlessTimer; private Timer m_ClearTimer; private Mobile m_Owner; public PeerlessRegion Region { get { return m_Region; } } public Mobile Boss { get { return m_Boss; } } public bool actived { get { return m_actived; } set { m_actived = value; } } public BaseActivation[] key { get { return m_key; } set { m_key = value; } } [CommandProperty( AccessLevel.GameMaster )] public PeerlessList Peerless { get { return m_Peerless; } set { m_Peerless = value; if ( m_Peerless == PeerlessList.ParoxysmusTrammel || m_Peerless == PeerlessList.ParoxysmusFelucca ) { this.Name = "Cauldron"; this.Hue = 1125; this.ItemID = 0x207A; } else if ( m_Peerless == PeerlessList.MelisandeTrammel || m_Peerless == PeerlessList.MelisandeFelucca ) { this.Name = "Basket"; this.Hue = 0; this.ItemID = 0x207B; } else if ( m_Peerless == PeerlessList.DreadHorn ) { this.Name = "Statue Of The Faie"; this.Hue = 0; this.ItemID = 0x207C; } else if ( m_Peerless == PeerlessList.Travesty || m_Peerless == PeerlessList.InterredGrizzle ) { this.Name = "Keyed Table"; this.Hue = 0; this.ItemID = 0x207E; } else if ( m_Peerless == PeerlessList.ShimmeringEffusionTrammel || m_Peerless == PeerlessList.ShimmeringEffusionFelucca ) { this.Name = "Pillar"; this.Hue = 1153; this.ItemID = 8317; } else if (m_Peerless == PeerlessList.Exodus) { this.Name = "Exodus Summoning Tome"; this.Hue = 2360; this.ItemID = 0x2259; } else { this.Name = null; this.Hue = 0; this.ItemID = 0x9AB; } if ( m_Peerless != PeerlessList.None ) UpdateRegion(); } } public Timer PeerlessT { get { return m_PeerlessTimer; } set { m_PeerlessTimer = value; } } public Timer clearT { get { return m_ClearTimer; } set { m_ClearTimer = value; } } public Mobile Owner { get { return m_Owner; } set { m_Owner = value; } } private readonly Type[] m_Keys = new Type[6]; [Constructable] public AltarPeerless() : base( 0x9AB ) { Movable = false; DropSound = 0x48; } public AltarPeerless( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( (int) m_Peerless ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); m_Peerless = (PeerlessList) reader.ReadInt(); if ( m_Peerless != PeerlessList.None ) { UpdateRegion(); m_Region.Register(); } } public override bool DisplayWeight { get { return false; } } public override bool OnDragDrop( Mobile from, Item dropped ) { if ( !base.OnDragDrop( from, dropped ) || m_Peerless == PeerlessList.None ) { return false; } if ( PeerlessEntry.IsPeerlessKey( m_Peerless, dropped ) ) { if ( m_Owner != from && m_actived ) { if ( Boss != null && Boss.CheckAlive() ) from.SendLocalizedMessage( 1075213 ); // The master of this realm has already been summoned and is engaged in combat. Your opportunity will come after he has squashed the current batch of intruders! else from.SendLocalizedMessage( 1072683, m_Owner.Name ); // ~1_NAME~ has already activated the Prism, please wait... return false; } for ( int i = 0; i < m_Keys.Length; i++ ) { if ( m_Keys[i] == dropped.GetType() ) { from.SendLocalizedMessage( 1072682 ); // This is not the proper key. return false; } else if ( m_Keys[i] == null ) { m_Keys[i] = dropped.GetType(); if ( i == 0 ) { m_actived = true; m_Owner = from; from.SendLocalizedMessage( 1074575 ); // You have activated this object! m_ResetTimer = new ResetTimer( this ); m_ResetTimer.Start(); } if ( PeerlessEntry.GetAltarKeys( m_Peerless ) == ( i + 1 ) ) { m_ResetTimer.Stop(); from.SendLocalizedMessage( 1072678 ); // You have awakened the master of this realm. You need to hurry to defeat it in time! GiveKeys( from ); Mobile boss = Activator.CreateInstance( PeerlessEntry.GetBoss( m_Peerless ) ) as Mobile; m_Boss = boss; boss.MoveToWorld( PeerlessEntry.GetSpawnPoint( m_Peerless ), PeerlessEntry.GetMap( m_Peerless ) ); boss.OnBeforeSpawn( boss.Location, boss.Map ); PeerlessT = new PeerlessTimer( this ); PeerlessT.Start(); } dropped.Delete(); return true; } } from.SendLocalizedMessage( 1072682 ); // This is not the proper key. return false; } else { from.SendLocalizedMessage( 1072682 ); // This is not the proper key. return false; } } public void UpdateRegion() { if ( m_Region != null ) m_Region.Unregister(); string regionName; Map regionMap; List<Rectangle2D> regionBounds = new List<Rectangle2D>(); switch ( m_Peerless ) { default: case PeerlessList.DreadHorn: { regionName = "DreadHorn"; regionMap = Map.Ilshenar; regionBounds.Add( new Rectangle2D( 2126, 1237, 22, 22 ) ); regionBounds.Add( new Rectangle2D( 2148, 1238, 4, 21 ) ); regionBounds.Add( new Rectangle2D( 2152, 1246, 6, 13 ) ); regionBounds.Add( new Rectangle2D( 2130, 1259, 27, 4 ) ); regionBounds.Add( new Rectangle2D( 2135, 1263, 21, 6 ) ); regionBounds.Add( new Rectangle2D( 2137, 1269, 18, 5 ) ); regionBounds.Add( new Rectangle2D( 2157, 1253, 4, 8 ) ); break; } case PeerlessList.MelisandeFelucca: { regionName = "MelisandeFelucca"; regionMap = Map.Felucca; regionBounds.Add( new Rectangle2D( 6456, 922, 86, 44 ) ); break; } case PeerlessList.MelisandeTrammel: { regionName = "MelisandeTrammel"; regionMap = Map.Trammel; regionBounds.Add( new Rectangle2D( 6456, 922, 86, 44 ) ); break; } case PeerlessList.Travesty: { regionName = "Travesty"; regionMap = Map.Malas; regionBounds.Add( new Rectangle2D( new Point2D( 64, 1933 ), new Point2D( 117, 1978 ) ) ); break; } case PeerlessList.ParoxysmusTrammel: { regionName = "ParoxysmusTrammel"; regionMap = Map.Trammel; regionBounds.Add( new Rectangle2D( new Point2D( 6486, 335 ), new Point2D( 6552, 398 ) ) ); break; } case PeerlessList.ParoxysmusFelucca: { regionName = "ParoxysmusFelucca"; regionMap = Map.Felucca; regionBounds.Add( new Rectangle2D( new Point2D( 6486, 335 ), new Point2D( 6552, 398 ) ) ); break; } case PeerlessList.InterredGrizzle: { regionName = "InterredGrizzle"; regionMap = Map.Malas; regionBounds.Add( new Rectangle2D( new Point2D( 148, 1721 ), new Point2D( 198, 1765 ) ) ); break; } case PeerlessList.ShimmeringEffusionTrammel: { regionName = "ShimmeringEffusionTrammel"; regionMap = Map.Trammel; regionBounds.Add( new Rectangle2D( new Point2D( 6499, 111 ), new Point2D( 6545, 145 ) ) ); break; } case PeerlessList.ShimmeringEffusionFelucca: { regionName = "ShimmeringEffusionFelucca"; regionMap = Map.Trammel; regionBounds.Add( new Rectangle2D( new Point2D( 6499, 111 ), new Point2D( 6545, 145 ) ) ); break; } } m_Region = new PeerlessRegion( regionName, regionMap, this, regionBounds.ToArray() ); } public void Clear() { for ( int i = 0; i < m_Keys.Length; i++ ) m_Keys[i] = null; actived = false; } public void GiveKeys( Mobile from ) { if ( m_Peerless != PeerlessList.None ) { for ( int i = 0; i < m_key.Length; i++ ) { if ( m_Peerless == PeerlessList.DreadHorn ) m_key[i] = new DreadHornActivation(); else if (m_Peerless == PeerlessList.Exodus)
[ " m_key[i] = new ExodusTomeAltar();" ]
1,143
lcc
csharp
null
e8fcbecdd8f66e30320eeb4325e3c774f6123213490f17da
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.careuk.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to CAREUK.ChangeOfService business object (ID: 1096100021). */ public class ChangeOfServiceVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<ChangeOfServiceVo> { private static final long serialVersionUID = 1L; private ArrayList<ChangeOfServiceVo> col = new ArrayList<ChangeOfServiceVo>(); public String getBoClassName() { return "ims.careuk.domain.objects.ChangeOfService"; } public boolean add(ChangeOfServiceVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, ChangeOfServiceVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(ChangeOfServiceVo instance) { return col.indexOf(instance); } public ChangeOfServiceVo get(int index) { return this.col.get(index); } public boolean set(int index, ChangeOfServiceVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(ChangeOfServiceVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(ChangeOfServiceVo instance) { return indexOf(instance) >= 0; } public Object clone() { ChangeOfServiceVoCollection clone = new ChangeOfServiceVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((ChangeOfServiceVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public ChangeOfServiceVoCollection sort() { return sort(SortOrder.ASCENDING); } public ChangeOfServiceVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public ChangeOfServiceVoCollection sort(SortOrder order) { return sort(new ChangeOfServiceVoComparator(order)); } public ChangeOfServiceVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new ChangeOfServiceVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public ChangeOfServiceVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.careuk.vo.ChangeOfServiceRefVoCollection toRefVoCollection() { ims.careuk.vo.ChangeOfServiceRefVoCollection result = new ims.careuk.vo.ChangeOfServiceRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public ChangeOfServiceVo[] toArray() { ChangeOfServiceVo[] arr = new ChangeOfServiceVo[col.size()]; col.toArray(arr); return arr; } public Iterator<ChangeOfServiceVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class ChangeOfServiceVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public ChangeOfServiceVoComparator() { this(SortOrder.ASCENDING); } public ChangeOfServiceVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public ChangeOfServiceVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { ChangeOfServiceVo voObj1 = (ChangeOfServiceVo)obj1; ChangeOfServiceVo voObj2 = (ChangeOfServiceVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.careuk.vo.beans.ChangeOfServiceVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.careuk.vo.beans.ChangeOfServiceVoBean[] getBeanCollectionArray() { ims.careuk.vo.beans.ChangeOfServiceVoBean[] result = new ims.careuk.vo.beans.ChangeOfServiceVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { ChangeOfServiceVo vo = ((ChangeOfServiceVo)col.get(i)); result[i] = (ims.careuk.vo.beans.ChangeOfServiceVoBean)vo.getBean(); } return result; } public static ChangeOfServiceVoCollection buildFromBeanCollection(java.util.Collection beans) { ChangeOfServiceVoCollection coll = new ChangeOfServiceVoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.careuk.vo.beans.ChangeOfServiceVoBean)iter.next()).buildVo()); } return coll; } public static ChangeOfServiceVoCollection buildFromBeanCollection(ims.careuk.vo.beans.ChangeOfServiceVoBean[] beans) { ChangeOfServiceVoCollection coll = new ChangeOfServiceVoCollection();
[ "\t\tif(beans == null)" ]
755
lcc
java
null
131b0d4e1060ac70718be3c8613b7334215e78efea7deb46
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.paradise.itext.qrcode; /** * See ISO 18004:2006 Annex D * * @author Sean Owen * @since 5.0.2 */ public final class Version { /** * See ISO 18004:2006 Annex D. * Element i represents the raw version bits that specify version i + 7 */ private static final int[] VERSION_DECODE_INFO = { 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69 }; private static final Version[] VERSIONS = buildVersions(); private final int versionNumber; private final int[] alignmentPatternCenters; private final ECBlocks[] ecBlocks; private final int totalCodewords; private Version(int versionNumber, int[] alignmentPatternCenters, ECBlocks ecBlocks1, ECBlocks ecBlocks2, ECBlocks ecBlocks3, ECBlocks ecBlocks4) { this.versionNumber = versionNumber; this.alignmentPatternCenters = alignmentPatternCenters; this.ecBlocks = new ECBlocks[]{ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4}; int total = 0; int ecCodewords = ecBlocks1.getECCodewordsPerBlock(); ECB[] ecbArray = ecBlocks1.getECBlocks(); for (int i = 0; i < ecbArray.length; i++) { ECB ecBlock = ecbArray[i]; total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); } this.totalCodewords = total; } public int getVersionNumber() { return versionNumber; } public int[] getAlignmentPatternCenters() { return alignmentPatternCenters; } public int getTotalCodewords() { return totalCodewords; } public int getDimensionForVersion() { return 17 + 4 * versionNumber; } public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) { return ecBlocks[ecLevel.ordinal()]; } /** * <p>Deduces version information purely from QR Code dimensions.</p> * * @param dimension dimension in modules * @return {@link Version} for a QR Code of that dimension * @throws FormatException if dimension is not 1 mod 4 */ public static Version getProvisionalVersionForDimension(int dimension) { if (dimension % 4 != 1) { throw new IllegalArgumentException(); } try { return getVersionForNumber((dimension - 17) >> 2); } catch (IllegalArgumentException iae) { throw iae; } } public static Version getVersionForNumber(int versionNumber) { if (versionNumber < 1 || versionNumber > 40) { throw new IllegalArgumentException(); } return VERSIONS[versionNumber - 1]; } static Version decodeVersionInformation(int versionBits) { int bestDifference = Integer.MAX_VALUE; int bestVersion = 0; for (int i = 0; i < VERSION_DECODE_INFO.length; i++) { int targetVersion = VERSION_DECODE_INFO[i]; // Do the version info bits match exactly? done. if (targetVersion == versionBits) { return getVersionForNumber(i + 7); } // Otherwise see if this is the closest to a real version info bit string // we have seen so far int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); if (bitsDifference < bestDifference) { bestVersion = i + 7; bestDifference = bitsDifference; } } // We can tolerate up to 3 bits of error since no two version info codewords will // differ in less than 4 bits. if (bestDifference <= 3) { return getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail return null; } /** * See ISO 18004:2006 Annex E */ BitMatrix buildFunctionPattern() { int dimension = getDimensionForVersion(); BitMatrix bitMatrix = new BitMatrix(dimension); // Top left finder pattern + separator + format bitMatrix.setRegion(0, 0, 9, 9); // Top right finder pattern + separator + format bitMatrix.setRegion(dimension - 8, 0, 8, 9); // Bottom left finder pattern + separator + format bitMatrix.setRegion(0, dimension - 8, 9, 8); // Alignment patterns int max = alignmentPatternCenters.length; for (int x = 0; x < max; x++) { int i = alignmentPatternCenters[x] - 2; for (int y = 0; y < max; y++) { if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { // No alignment patterns near the three finder paterns continue; } bitMatrix.setRegion(alignmentPatternCenters[y] - 2, i, 5, 5); } } // Vertical timing pattern bitMatrix.setRegion(6, 9, 1, dimension - 17); // Horizontal timing pattern bitMatrix.setRegion(9, 6, dimension - 17, 1); if (versionNumber > 6) { // Version info, top right bitMatrix.setRegion(dimension - 11, 0, 3, 6); // Version info, bottom left bitMatrix.setRegion(0, dimension - 11, 6, 3); } return bitMatrix; } /** * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will * use blocks of differing sizes within one version, so, this encapsulates the parameters for * each set of blocks. It also holds the number of error-correction codewords per block since it * will be the same across all blocks within one version.</p> */ public static final class ECBlocks { private final int ecCodewordsPerBlock; private final ECB[] ecBlocks; ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks) { this.ecCodewordsPerBlock = ecCodewordsPerBlock; this.ecBlocks = new ECB[]{ecBlocks}; } ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks1, ECB ecBlocks2) { this.ecCodewordsPerBlock = ecCodewordsPerBlock; this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; } public int getECCodewordsPerBlock() { return ecCodewordsPerBlock; } public int getNumBlocks() { int total = 0; for (int i = 0; i < ecBlocks.length; i++) { total += ecBlocks[i].getCount(); } return total; } public int getTotalECCodewords() { return ecCodewordsPerBlock * getNumBlocks(); } public ECB[] getECBlocks() { return ecBlocks; } } /** * <p>Encapsualtes the parameters for one error-correction block in one symbol version. * This includes the number of data codewords, and the number of times a block with these * parameters is used consecutively in the QR code version's format.</p> */ public static final class ECB { private final int count; private final int dataCodewords; ECB(int count, int dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; } public int getCount() { return count; } public int getDataCodewords() { return dataCodewords; } } public String toString() { return String.valueOf(versionNumber); } /** * See ISO 18004:2006 6.5.1 Table 9 */ private static Version[] buildVersions() { return new Version[]{
[ " new Version(1, new int[]{}," ]
994
lcc
java
null
5a5af80308308375d1df176501cc0cb6e044e09d4787ab3a
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Text; #if KeePassUAP using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; #else using System.Security.Cryptography; #endif using KeePassLib.Cryptography.Cipher; using KeePassLib.Cryptography.Hash; using KeePassLib.Cryptography.KeyDerivation; using KeePassLib.Keys; using KeePassLib.Native; using KeePassLib.Resources; using KeePassLib.Security; using KeePassLib.Utility; #if (KeePassUAP && KeePassLibSD) #error KeePassUAP and KeePassLibSD are mutually exclusive. #endif namespace KeePassLib.Cryptography { /// <summary> /// Class containing self-test methods. /// </summary> public static class SelfTest { /// <summary> /// Perform a self-test. /// </summary> public static void Perform() { Random r = CryptoRandom.NewWeakRandom(); TestFipsComplianceProblems(); // Must be the first test TestRijndael(); TestSalsa20(r); TestChaCha20(r); TestBlake2b(r); TestArgon2(); TestHmac(); TestKeyTransform(r); TestNativeKeyTransform(r); TestHmacOtp(); TestProtectedObjects(r); TestMemUtil(r); TestStrUtil(); TestUrlUtil(); Debug.Assert((int)PwIcon.World == 1); Debug.Assert((int)PwIcon.Warning == 2); Debug.Assert((int)PwIcon.BlackBerry == 68); #if KeePassUAP SelfTestEx.Perform(); #endif } internal static void TestFipsComplianceProblems() { #if !KeePassUAP try { using(RijndaelManaged r = new RijndaelManaged()) { } } catch(Exception exAes) { throw new SecurityException("AES/Rijndael: " + exAes.Message); } #endif try { using(SHA256Managed h = new SHA256Managed()) { } } catch(Exception exSha256) { throw new SecurityException("SHA-256: " + exSha256.Message); } } private static void TestRijndael() { // Test vector (official ECB test vector #356) byte[] pbIV = new byte[16]; byte[] pbTestKey = new byte[32]; byte[] pbTestData = new byte[16]; byte[] pbReferenceCT = new byte[16] { 0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22, 0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7 }; int i; for(i = 0; i < 16; ++i) pbIV[i] = 0; for(i = 0; i < 32; ++i) pbTestKey[i] = 0; for(i = 0; i < 16; ++i) pbTestData[i] = 0; pbTestData[0] = 0x04; #if KeePassUAP AesEngine r = new AesEngine(); r.Init(true, new KeyParameter(pbTestKey)); if(r.GetBlockSize() != pbTestData.Length) throw new SecurityException("AES (BC)"); r.ProcessBlock(pbTestData, 0, pbTestData, 0); #else RijndaelManaged r = new RijndaelManaged(); if(r.BlockSize != 128) // AES block size { Debug.Assert(false); r.BlockSize = 128; } r.IV = pbIV; r.KeySize = 256; r.Key = pbTestKey; r.Mode = CipherMode.ECB; ICryptoTransform iCrypt = r.CreateEncryptor(); iCrypt.TransformBlock(pbTestData, 0, 16, pbTestData, 0); #endif if(!MemUtil.ArraysEqual(pbTestData, pbReferenceCT)) throw new SecurityException("AES"); } private static void TestSalsa20(Random r) { #if DEBUG // Test values from official set 6, vector 3 byte[] pbKey = new byte[32] { 0x0F, 0x62, 0xB5, 0x08, 0x5B, 0xAE, 0x01, 0x54, 0xA7, 0xFA, 0x4D, 0xA0, 0xF3, 0x46, 0x99, 0xEC, 0x3F, 0x92, 0xE5, 0x38, 0x8B, 0xDE, 0x31, 0x84, 0xD7, 0x2A, 0x7D, 0xD0, 0x23, 0x76, 0xC9, 0x1C }; byte[] pbIV = new byte[8] { 0x28, 0x8F, 0xF6, 0x5D, 0xC4, 0x2B, 0x92, 0xF9 }; byte[] pbExpected = new byte[16] { 0x5E, 0x5E, 0x71, 0xF9, 0x01, 0x99, 0x34, 0x03, 0x04, 0xAB, 0xB2, 0x2A, 0x37, 0xB6, 0x62, 0x5B }; byte[] pb = new byte[16]; Salsa20Cipher c = new Salsa20Cipher(pbKey, pbIV); c.Encrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpected)) throw new SecurityException("Salsa20-1"); // Extended test byte[] pbExpected2 = new byte[16] { 0xAB, 0xF3, 0x9A, 0x21, 0x0E, 0xEE, 0x89, 0x59, 0x8B, 0x71, 0x33, 0x37, 0x70, 0x56, 0xC2, 0xFE }; byte[] pbExpected3 = new byte[16] { 0x1B, 0xA8, 0x9D, 0xBD, 0x3F, 0x98, 0x83, 0x97, 0x28, 0xF5, 0x67, 0x91, 0xD5, 0xB7, 0xCE, 0x23 }; int nPos = Salsa20ToPos(c, r, pb.Length, 65536); Array.Clear(pb, 0, pb.Length); c.Encrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpected2)) throw new SecurityException("Salsa20-2"); nPos = Salsa20ToPos(c, r, nPos + pb.Length, 131008); Array.Clear(pb, 0, pb.Length); c.Encrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpected3)) throw new SecurityException("Salsa20-3"); Dictionary<string, bool> d = new Dictionary<string, bool>(); const int nRounds = 100; for(int i = 0; i < nRounds; ++i) { byte[] z = new byte[32]; c = new Salsa20Cipher(z, MemUtil.Int64ToBytes(i)); c.Encrypt(z, 0, z.Length); d[MemUtil.ByteArrayToHexString(z)] = true; } if(d.Count != nRounds) throw new SecurityException("Salsa20-4"); #endif } #if DEBUG private static int Salsa20ToPos(Salsa20Cipher c, Random r, int nPos, int nTargetPos) { byte[] pb = new byte[512]; while(nPos < nTargetPos) { int x = r.Next(1, 513); int nGen = Math.Min(nTargetPos - nPos, x); c.Encrypt(pb, 0, nGen); nPos += nGen; } return nTargetPos; } #endif private static void TestChaCha20(Random r) { // ====================================================== // Test vector from RFC 7539, section 2.3.2 byte[] pbKey = new byte[32]; for(int i = 0; i < 32; ++i) pbKey[i] = (byte)i; byte[] pbIV = new byte[12]; pbIV[3] = 0x09; pbIV[7] = 0x4A; byte[] pbExpc = new byte[64] { 0x10, 0xF1, 0xE7, 0xE4, 0xD1, 0x3B, 0x59, 0x15, 0x50, 0x0F, 0xDD, 0x1F, 0xA3, 0x20, 0x71, 0xC4, 0xC7, 0xD1, 0xF4, 0xC7, 0x33, 0xC0, 0x68, 0x03, 0x04, 0x22, 0xAA, 0x9A, 0xC3, 0xD4, 0x6C, 0x4E, 0xD2, 0x82, 0x64, 0x46, 0x07, 0x9F, 0xAA, 0x09, 0x14, 0xC2, 0xD7, 0x05, 0xD9, 0x8B, 0x02, 0xA2, 0xB5, 0x12, 0x9C, 0xD1, 0xDE, 0x16, 0x4E, 0xB9, 0xCB, 0xD0, 0x83, 0xE8, 0xA2, 0x50, 0x3C, 0x4E }; byte[] pb = new byte[64]; using(ChaCha20Cipher c = new ChaCha20Cipher(pbKey, pbIV)) { c.Seek(64, SeekOrigin.Begin); // Skip first block c.Encrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpc)) throw new SecurityException("ChaCha20-1"); } #if DEBUG // ====================================================== // Test vector from RFC 7539, section 2.4.2 pbIV[3] = 0; pb = StrUtil.Utf8.GetBytes("Ladies and Gentlemen of the clas" + @"s of '99: If I could offer you only one tip for " + @"the future, sunscreen would be it."); pbExpc = new byte[] { 0x6E, 0x2E, 0x35, 0x9A, 0x25, 0x68, 0xF9, 0x80, 0x41, 0xBA, 0x07, 0x28, 0xDD, 0x0D, 0x69, 0x81, 0xE9, 0x7E, 0x7A, 0xEC, 0x1D, 0x43, 0x60, 0xC2, 0x0A, 0x27, 0xAF, 0xCC, 0xFD, 0x9F, 0xAE, 0x0B, 0xF9, 0x1B, 0x65, 0xC5, 0x52, 0x47, 0x33, 0xAB, 0x8F, 0x59, 0x3D, 0xAB, 0xCD, 0x62, 0xB3, 0x57, 0x16, 0x39, 0xD6, 0x24, 0xE6, 0x51, 0x52, 0xAB, 0x8F, 0x53, 0x0C, 0x35, 0x9F, 0x08, 0x61, 0xD8, 0x07, 0xCA, 0x0D, 0xBF, 0x50, 0x0D, 0x6A, 0x61, 0x56, 0xA3, 0x8E, 0x08, 0x8A, 0x22, 0xB6, 0x5E, 0x52, 0xBC, 0x51, 0x4D, 0x16, 0xCC, 0xF8, 0x06, 0x81, 0x8C, 0xE9, 0x1A, 0xB7, 0x79, 0x37, 0x36, 0x5A, 0xF9, 0x0B, 0xBF, 0x74, 0xA3, 0x5B, 0xE6, 0xB4, 0x0B, 0x8E, 0xED, 0xF2, 0x78, 0x5E, 0x42, 0x87, 0x4D }; byte[] pb64 = new byte[64]; using(ChaCha20Cipher c = new ChaCha20Cipher(pbKey, pbIV)) { c.Encrypt(pb64, 0, pb64.Length); // Skip first block c.Encrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpc)) throw new SecurityException("ChaCha20-2"); } // ====================================================== // Test vector from RFC 7539, appendix A.2 #2 Array.Clear(pbKey, 0, pbKey.Length); pbKey[31] = 1; Array.Clear(pbIV, 0, pbIV.Length); pbIV[11] = 2; pb = StrUtil.Utf8.GetBytes("Any submission to the IETF inten" + "ded by the Contributor for publication as all or" + " part of an IETF Internet-Draft or RFC and any s" + "tatement made within the context of an IETF acti" + "vity is considered an \"IETF Contribution\". Such " + "statements include oral statements in IETF sessi" + "ons, as well as written and electronic communica" + "tions made at any time or place, which are addressed to"); pbExpc = MemUtil.HexStringToByteArray( "A3FBF07DF3FA2FDE4F376CA23E82737041605D9F4F4F57BD8CFF2C1D4B7955EC" + "2A97948BD3722915C8F3D337F7D370050E9E96D647B7C39F56E031CA5EB6250D" + "4042E02785ECECFA4B4BB5E8EAD0440E20B6E8DB09D881A7C6132F420E527950" + "42BDFA7773D8A9051447B3291CE1411C680465552AA6C405B7764D5E87BEA85A" + "D00F8449ED8F72D0D662AB052691CA66424BC86D2DF80EA41F43ABF937D3259D" + "C4B2D0DFB48A6C9139DDD7F76966E928E635553BA76C5C879D7B35D49EB2E62B" + "0871CDAC638939E25E8A1E0EF9D5280FA8CA328B351C3C765989CBCF3DAA8B6C" + "CC3AAF9F3979C92B3720FC88DC95ED84A1BE059C6499B9FDA236E7E818B04B0B" + "C39C1E876B193BFE5569753F88128CC08AAA9B63D1A16F80EF2554D7189C411F" + "5869CA52C5B83FA36FF216B9C1D30062BEBCFD2DC5BCE0911934FDA79A86F6E6" + "98CED759C3FF9B6477338F3DA4F9CD8514EA9982CCAFB341B2384DD902F3D1AB" + "7AC61DD29C6F21BA5B862F3730E37CFDC4FD806C22F221"); using(MemoryStream msEnc = new MemoryStream()) { using(ChaCha20Stream c = new ChaCha20Stream(msEnc, true, pbKey, pbIV)) { r.NextBytes(pb64); c.Write(pb64, 0, pb64.Length); // Skip first block int p = 0; while(p < pb.Length) { int cb = r.Next(1, pb.Length - p + 1); c.Write(pb, p, cb); p += cb; } Debug.Assert(p == pb.Length); } byte[] pbEnc0 = msEnc.ToArray(); byte[] pbEnc = MemUtil.Mid(pbEnc0, 64, pbEnc0.Length - 64); if(!MemUtil.ArraysEqual(pbEnc, pbExpc)) throw new SecurityException("ChaCha20-3"); using(MemoryStream msCT = new MemoryStream(pbEnc0, false)) { using(ChaCha20Stream cDec = new ChaCha20Stream(msCT, false, pbKey, pbIV)) { byte[] pbPT = MemUtil.Read(cDec, pbEnc0.Length); if(cDec.ReadByte() >= 0) throw new SecurityException("ChaCha20-4"); if(!MemUtil.ArraysEqual(MemUtil.Mid(pbPT, 0, 64), pb64)) throw new SecurityException("ChaCha20-5"); if(!MemUtil.ArraysEqual(MemUtil.Mid(pbPT, 64, pbEnc.Length), pb)) throw new SecurityException("ChaCha20-6"); } } } // ====================================================== // Test vector TC8 from RFC draft by J. Strombergson: // https://tools.ietf.org/html/draft-strombergson-chacha-test-vectors-01 pbKey = new byte[32] { 0xC4, 0x6E, 0xC1, 0xB1, 0x8C, 0xE8, 0xA8, 0x78, 0x72, 0x5A, 0x37, 0xE7, 0x80, 0xDF, 0xB7, 0x35, 0x1F, 0x68, 0xED, 0x2E, 0x19, 0x4C, 0x79, 0xFB, 0xC6, 0xAE, 0xBE, 0xE1, 0xA6, 0x67, 0x97, 0x5D }; // The first 4 bytes are set to zero and a large counter // is used; this makes the RFC 7539 version of ChaCha20 // compatible with the original specification by // D. J. Bernstein. pbIV = new byte[12] { 0x00, 0x00, 0x00, 0x00, 0x1A, 0xDA, 0x31, 0xD5, 0xCF, 0x68, 0x82, 0x21 }; pb = new byte[128]; pbExpc = new byte[128] { 0xF6, 0x3A, 0x89, 0xB7, 0x5C, 0x22, 0x71, 0xF9, 0x36, 0x88, 0x16, 0x54, 0x2B, 0xA5, 0x2F, 0x06, 0xED, 0x49, 0x24, 0x17, 0x92, 0x30, 0x2B, 0x00, 0xB5, 0xE8, 0xF8, 0x0A, 0xE9, 0xA4, 0x73, 0xAF, 0xC2, 0x5B, 0x21, 0x8F, 0x51, 0x9A, 0xF0, 0xFD, 0xD4, 0x06, 0x36, 0x2E, 0x8D, 0x69, 0xDE, 0x7F, 0x54, 0xC6, 0x04, 0xA6, 0xE0, 0x0F, 0x35, 0x3F, 0x11, 0x0F, 0x77, 0x1B, 0xDC, 0xA8, 0xAB, 0x92, 0xE5, 0xFB, 0xC3, 0x4E, 0x60, 0xA1, 0xD9, 0xA9, 0xDB, 0x17, 0x34, 0x5B, 0x0A, 0x40, 0x27, 0x36, 0x85, 0x3B, 0xF9, 0x10, 0xB0, 0x60, 0xBD, 0xF1, 0xF8, 0x97, 0xB6, 0x29, 0x0F, 0x01, 0xD1, 0x38, 0xAE, 0x2C, 0x4C, 0x90, 0x22, 0x5B, 0xA9, 0xEA, 0x14, 0xD5, 0x18, 0xF5, 0x59, 0x29, 0xDE, 0xA0, 0x98, 0xCA, 0x7A, 0x6C, 0xCF, 0xE6, 0x12, 0x27, 0x05, 0x3C, 0x84, 0xE4, 0x9A, 0x4A, 0x33, 0x32 }; using(ChaCha20Cipher c = new ChaCha20Cipher(pbKey, pbIV, true)) { c.Decrypt(pb, 0, pb.Length); if(!MemUtil.ArraysEqual(pb, pbExpc)) throw new SecurityException("ChaCha20-7"); } #endif } private static void TestBlake2b(Random r) { #if DEBUG Blake2b h = new Blake2b(); // ====================================================== // From https://tools.ietf.org/html/rfc7693 byte[] pbData = StrUtil.Utf8.GetBytes("abc"); byte[] pbExpc = new byte[64] { 0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D, 0x6A, 0x27, 0x97, 0xB6, 0x9F, 0x12, 0xF6, 0xE9, 0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A, 0xC4, 0xB7, 0x4B, 0x12, 0xBB, 0x6F, 0xDB, 0xFF, 0xA2, 0xD1, 0x7D, 0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D, 0xC2, 0x52, 0xD5, 0xDE, 0x45, 0x33, 0xCC, 0x95, 0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92, 0x5A, 0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23 }; byte[] pbC = h.ComputeHash(pbData); if(!MemUtil.ArraysEqual(pbC, pbExpc)) throw new SecurityException("Blake2b-1"); // ====================================================== // Computed using the official b2sum tool pbExpc = new byte[64] { 0x78, 0x6A, 0x02, 0xF7, 0x42, 0x01, 0x59, 0x03, 0xC6, 0xC6, 0xFD, 0x85, 0x25, 0x52, 0xD2, 0x72, 0x91, 0x2F, 0x47, 0x40, 0xE1, 0x58, 0x47, 0x61, 0x8A, 0x86, 0xE2, 0x17, 0xF7, 0x1F, 0x54, 0x19, 0xD2, 0x5E, 0x10, 0x31, 0xAF, 0xEE, 0x58, 0x53, 0x13, 0x89, 0x64, 0x44, 0x93, 0x4E, 0xB0, 0x4B, 0x90, 0x3A, 0x68, 0x5B, 0x14, 0x48, 0xB7, 0x55, 0xD5, 0x6F, 0x70, 0x1A, 0xFE, 0x9B, 0xE2, 0xCE }; pbC = h.ComputeHash(MemUtil.EmptyByteArray); if(!MemUtil.ArraysEqual(pbC, pbExpc)) throw new SecurityException("Blake2b-2"); // ====================================================== // Computed using the official b2sum tool string strS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:,;_-\r\n"; StringBuilder sb = new StringBuilder(); for(int i = 0; i < 1000; ++i) sb.Append(strS); pbData = StrUtil.Utf8.GetBytes(sb.ToString()); pbExpc = new byte[64] { 0x59, 0x69, 0x8D, 0x3B, 0x83, 0xF4, 0x02, 0x4E, 0xD8, 0x99, 0x26, 0x0E, 0xF4, 0xE5, 0x9F, 0x20, 0xDC, 0x31, 0xEE, 0x5B, 0x45, 0xEA, 0xBB, 0xFC, 0x1C, 0x0A, 0x8E, 0xED, 0xAA, 0x7A, 0xFF, 0x50, 0x82, 0xA5, 0x8F, 0xBC, 0x4A, 0x46, 0xFC, 0xC5, 0xEF, 0x44, 0x4E, 0x89, 0x80, 0x7D, 0x3F, 0x1C, 0xC1, 0x94, 0x45, 0xBB, 0xC0, 0x2C, 0x95, 0xAA, 0x3F, 0x08, 0x8A, 0x93, 0xF8, 0x75, 0x91, 0xB0 }; int p = 0; while(p < pbData.Length) { int cb = r.Next(1, pbData.Length - p + 1); h.TransformBlock(pbData, p, cb, pbData, p); p += cb; } Debug.Assert(p == pbData.Length); h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0); if(!MemUtil.ArraysEqual(h.Hash, pbExpc)) throw new SecurityException("Blake2b-3"); h.Clear(); #endif } private static void TestArgon2() { #if DEBUG Argon2Kdf kdf = new Argon2Kdf(); // ====================================================== // From the official Argon2 1.3 reference code package // (test vector for Argon2d 1.3); also on // https://tools.ietf.org/html/draft-irtf-cfrg-argon2-00 KdfParameters p = kdf.GetDefaultParameters(); kdf.Randomize(p); Debug.Assert(p.GetUInt32(Argon2Kdf.ParamVersion, 0) == 0x13U); byte[] pbMsg = new byte[32]; for(int i = 0; i < pbMsg.Length; ++i) pbMsg[i] = 1; p.SetUInt64(Argon2Kdf.ParamMemory, 32 * 1024); p.SetUInt64(Argon2Kdf.ParamIterations, 3); p.SetUInt32(Argon2Kdf.ParamParallelism, 4); byte[] pbSalt = new byte[16]; for(int i = 0; i < pbSalt.Length; ++i) pbSalt[i] = 2; p.SetByteArray(Argon2Kdf.ParamSalt, pbSalt); byte[] pbKey = new byte[8]; for(int i = 0; i < pbKey.Length; ++i) pbKey[i] = 3; p.SetByteArray(Argon2Kdf.ParamSecretKey, pbKey); byte[] pbAssoc = new byte[12]; for(int i = 0; i < pbAssoc.Length; ++i) pbAssoc[i] = 4; p.SetByteArray(Argon2Kdf.ParamAssocData, pbAssoc); byte[] pbExpc = new byte[32] { 0x51, 0x2B, 0x39, 0x1B, 0x6F, 0x11, 0x62, 0x97, 0x53, 0x71, 0xD3, 0x09, 0x19, 0x73, 0x42, 0x94, 0xF8, 0x68, 0xE3, 0xBE, 0x39, 0x84, 0xF3, 0xC1, 0xA1, 0x3A, 0x4D, 0xB9, 0xFA, 0xBE, 0x4A, 0xCB };
[ "\t\t\tbyte[] pb = kdf.Transform(pbMsg, p);" ]
2,072
lcc
csharp
null
cad0e73b70c6604397a4ffceeee2f4696001601af1e061b6
/** * This class was created by <Vazkii>. It's distributed as * part of the Botania Mod. Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php * * File Created @ [Mar 13, 2014, 5:32:24 PM (GMT)] */ package vazkii.botania.api.mana; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import vazkii.botania.api.BotaniaAPI; public final class ManaItemHandler { /** * Requests mana from items in a given player's inventory. * @param manaToGet How much mana is to be requested, if less mana exists than this amount, * the amount of mana existent will be returned instead, if you want exact values use requestManaExact. * @param remove If true, the mana will be removed from the target item. Set to false to just check. * @return The amount of mana received from the request. */ public static int requestMana(ItemStack stack, EntityPlayer player, int manaToGet, boolean remove) { if(stack == null) return 0; IInventory mainInv = player.inventory; IInventory baublesInv = BotaniaAPI.internalHandler.getBaublesInventory(player); int invSize = mainInv.getSizeInventory(); int size = invSize; if(baublesInv != null) size += baublesInv.getSizeInventory(); for(int i = 0; i < size; i++) { boolean useBaubles = i >= invSize; IInventory inv = useBaubles ? baublesInv : mainInv; int slot = i - (useBaubles ? invSize : 0); ItemStack stackInSlot = inv.getStackInSlot(slot); if(stackInSlot == stack) continue; if(stackInSlot != null && stackInSlot.getItem() instanceof IManaItem) { IManaItem manaItem = (IManaItem) stackInSlot.getItem(); if(manaItem.canExportManaToItem(stackInSlot, stack) && manaItem.getMana(stackInSlot) > 0) { if(stack.getItem() instanceof IManaItem && !((IManaItem) stack.getItem()).canReceiveManaFromItem(stack, stackInSlot)) continue; int mana = Math.min(manaToGet, manaItem.getMana(stackInSlot)); if(remove) manaItem.addMana(stackInSlot, -mana); if(useBaubles) BotaniaAPI.internalHandler.sendBaubleUpdatePacket(player, slot); return mana; } } } return 0; } /** * Requests an exact amount of mana from items in a given player's inventory. * @param manaToGet How much mana is to be requested, if less mana exists than this amount, * false will be returned instead, and nothing will happen. * @param remove If true, the mana will be removed from the target item. Set to false to just check. * @return If the request was succesful. */ public static boolean requestManaExact(ItemStack stack, EntityPlayer player, int manaToGet, boolean remove) { if(stack == null) return false; IInventory mainInv = player.inventory; IInventory baublesInv = BotaniaAPI.internalHandler.getBaublesInventory(player); int invSize = mainInv.getSizeInventory(); int size = invSize; if(baublesInv != null) size += baublesInv.getSizeInventory(); for(int i = 0; i < size; i++) { boolean useBaubles = i >= invSize; IInventory inv = useBaubles ? baublesInv : mainInv; int slot = i - (useBaubles ? invSize : 0); ItemStack stackInSlot = inv.getStackInSlot(slot); if(stackInSlot == stack) continue; if(stackInSlot != null && stackInSlot.getItem() instanceof IManaItem) { IManaItem manaItemSlot = (IManaItem) stackInSlot.getItem(); if(manaItemSlot.canExportManaToItem(stackInSlot, stack) && manaItemSlot.getMana(stackInSlot) > manaToGet) { if(stack.getItem() instanceof IManaItem && !((IManaItem) stack.getItem()).canReceiveManaFromItem(stack, stackInSlot)) continue; if(remove) manaItemSlot.addMana(stackInSlot, -manaToGet); if(useBaubles) BotaniaAPI.internalHandler.sendBaubleUpdatePacket(player, slot); return true; } } } return false; } /** * Dispatches mana to items in a given player's inventory. Note that this method * does not automatically remove mana from the item which is exporting. * @param manaToSend How much mana is to be sent. * @param remove If true, the mana will be added from the target item. Set to false to just check. * @return The amount of mana actually sent. */ public static int dispatchMana(ItemStack stack, EntityPlayer player, int manaToSend, boolean add) { if(stack == null) return 0; IInventory mainInv = player.inventory; IInventory baublesInv = BotaniaAPI.internalHandler.getBaublesInventory(player); int invSize = mainInv.getSizeInventory(); int size = invSize; if(baublesInv != null) size += baublesInv.getSizeInventory(); for(int i = 0; i < size; i++) { boolean useBaubles = i >= invSize; IInventory inv = useBaubles ? baublesInv : mainInv; int slot = i - (useBaubles ? invSize : 0); ItemStack stackInSlot = inv.getStackInSlot(slot); if(stackInSlot == stack) continue; if(stackInSlot != null && stackInSlot.getItem() instanceof IManaItem) { IManaItem manaItemSlot = (IManaItem) stackInSlot.getItem(); if(manaItemSlot.canReceiveManaFromItem(stackInSlot, stack)) { if(stack.getItem() instanceof IManaItem && !((IManaItem) stack.getItem()).canExportManaToItem(stack, stackInSlot)) continue; int received = 0; if(manaItemSlot.getMana(stackInSlot) + manaToSend <= manaItemSlot.getMaxMana(stackInSlot)) received = manaToSend; else received = manaToSend - (manaItemSlot.getMana(stackInSlot) + manaToSend - manaItemSlot.getMaxMana(stackInSlot)); if(add) manaItemSlot.addMana(stackInSlot, manaToSend); if(useBaubles) BotaniaAPI.internalHandler.sendBaubleUpdatePacket(player, slot); return received; } } } return 0; } /** * Dispatches an exact amount of mana to items in a given player's inventory. Note that this method * does not automatically remove mana from the item which is exporting. * @param manaToSend How much mana is to be sent. * @param remove If true, the mana will be added from the target item. Set to false to just check. * @return If an item received the mana sent. */ public static boolean dispatchManaExact(ItemStack stack, EntityPlayer player, int manaToSend, boolean add) { if(stack == null) return false; IInventory mainInv = player.inventory; IInventory baublesInv = BotaniaAPI.internalHandler.getBaublesInventory(player); int invSize = mainInv.getSizeInventory(); int size = invSize; if(baublesInv != null) size += baublesInv.getSizeInventory(); for(int i = 0; i < size; i++) { boolean useBaubles = i >= invSize; IInventory inv = useBaubles ? baublesInv : mainInv; int slot = i - (useBaubles ? invSize : 0); ItemStack stackInSlot = inv.getStackInSlot(slot); if(stackInSlot == stack) continue; if(stackInSlot != null && stackInSlot.getItem() instanceof IManaItem) { IManaItem manaItemSlot = (IManaItem) stackInSlot.getItem(); if(manaItemSlot.getMana(stackInSlot) + manaToSend <= manaItemSlot.getMaxMana(stackInSlot) && manaItemSlot.canReceiveManaFromItem(stackInSlot, stack)) { if(stack.getItem() instanceof IManaItem && !((IManaItem) stack.getItem()).canExportManaToItem(stack, stackInSlot)) continue; if(add) manaItemSlot.addMana(stackInSlot, manaToSend); if(useBaubles) BotaniaAPI.internalHandler.sendBaubleUpdatePacket(player, slot); return true; } } } return false; } /** * Requests mana from items in a given player's inventory. This version also * checks for IManaDiscountArmor items equipped to lower the cost. * @param manaToGet How much mana is to be requested, if less mana exists than this amount, * the amount of mana existent will be returned instead, if you want exact values use requestManaExact. * @param remove If true, the mana will be removed from the target item. Set to false to just check. * @return The amount of mana received from the request. */ public static int requestManaForTool(ItemStack stack, EntityPlayer player, int manaToGet, boolean remove) { float multiplier = Math.max(0F, 1F - getFullDiscountForTools(player)); int cost = (int) (manaToGet * multiplier); return (int) (requestMana(stack, player, cost, remove) / multiplier); } /** * Requests an exact amount of mana from items in a given player's inventory. This version also * checks for IManaDiscountArmor items equipped to lower the cost. * @param manaToGet How much mana is to be requested, if less mana exists than this amount, * false will be returned instead, and nothing will happen. * @param remove If true, the mana will be removed from the target item. Set to false to just check. * @return If the request was succesful. */ public static boolean requestManaExactForTool(ItemStack stack, EntityPlayer player, int manaToGet, boolean remove) { float multiplier = Math.max(0F, 1F - getFullDiscountForTools(player)); int cost = (int) (manaToGet * multiplier);
[ "\t\treturn requestManaExact(stack, player, cost, remove);" ]
1,100
lcc
java
null
b94c4100fcacf82ca0b3cf350411e8a6361c3aedbbb68172
# Copy this file to app_server/settings.py and adjust to your specification (it should work fine out of the box) # Django settings for django_agfk project. import os import sys SETTINGS_PATH = os.path.realpath(os.path.dirname(__file__)) CLIENT_SERVER_PATH = SETTINGS_PATH AGFK_PATH = os.path.realpath(os.path.join(SETTINGS_PATH, '../')) sys.path.append(AGFK_PATH) import config ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.DJANGO_DB_FILE, # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(CLIENT_SERVER_PATH, 'static/media') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( ('css',os.path.join(CLIENT_SERVER_PATH, 'static/css')), ('images',os.path.join(CLIENT_SERVER_PATH, 'static/images')), ('fonts',os.path.join(CLIENT_SERVER_PATH, 'static/fonts')), ('javascript',os.path.join(CLIENT_SERVER_PATH, 'static/javascript')), ('lib',os.path.join(CLIENT_SERVER_PATH, 'static/lib')) ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder' # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader' ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'wsgi.application' TEMPLATE_DIRS = ( os.path.join(CLIENT_SERVER_PATH,'static/html/'), os.path.join(CLIENT_SERVER_PATH,'static/html/underscore-templates/'), os.path.join(CLIENT_SERVER_PATH,'static/html/content-editing/') ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'apps.graph', 'apps.user_management', 'apps.roadmaps', 'apps.browser_tests', 'haystack', 'captcha', 'compressor', 'lazysignup', 'reversion', 'tastypie' ) # apps settings CAPTCHA_NOISE_FUNCTIONS = () CAPTCHA_LETTER_ROTATION = (-10,10) CAPTCHA_FONT_SIZE = 24 CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge' HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(config.APP_SERVER_SEARCH_INDEX_PATH, 'whoosh_index'), }, } # TODO we may want to eventually switch to queued processing # https://github.com/toastdriven/queued_search HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_DEFAULT_OPERATOR = 'AND' SESSION_SAVE_EVERY_REQUEST = True # context processors TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'lazysignup.backends.LazySignupBackend', ) # default URL to redirect to after login LOGIN_REDIRECT_URL = '/user' INTERNAL_IPS = ("127.0.0.1",) APP_SERVER = 'http://' + str(config.FRONTEND_SERVER_IP) + ":" + str(config.FRONTEND_SERVER_PORT) from settings_local import *
[ "if DEBUG and len(sys.argv) > 1:" ]
684
lcc
python
null
d7f7bd8bf110178d86ce3ea9bb27e6f1f794f60c3fe3a478
// // LED_Queue.cs // // Author: // Shane Synan <digitalcircuit36939@gmail.com> // // Copyright (c) 2015 - 2016 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; // Animation management using Actinic.Animations; // Rendering using Actinic.Rendering; namespace Actinic { public class LED_Queue { /// <summary> /// Modifiable list of LEDs representing the desired output state /// </summary> public Layer Lights; /// <summary> /// Gets a list of LEDs representing the last state processed by the output system, useful for fades /// </summary> /// <value>Read-only list of LEDs</value> public Layer LightsLastProcessed { get; private set; } /// <summary> /// Gets the number of lights /// </summary> /// <value>Number of lights</value> public int LightCount { get { return Lights.PixelCount; } } /// <summary> /// Gets a value indicating whether the selected animation is active. /// </summary> /// <value><c>true</c> if an animation is active; otherwise, <c>false</c>.</value> public bool AnimationActive { get { return (SelectedAnimation != null); } } /// <summary> /// If <c>true</c>, force an update for the next frame request in the output system loop /// </summary> public bool AnimationForceFrameRequest = false; /// <summary> /// The currently selected animation. /// </summary> public AbstractAnimation SelectedAnimation = null; /// <summary> /// How long the output queue has been idle. /// </summary> public int QueueIdleTime = 0; /// <summary> /// Gets a value indicating whether the output queue is empty. /// </summary> /// <value><c>true</c> if queue is empty; otherwise, <c>false</c>.</value> public bool QueueEmpty { get { return (OutputQueue.Count <= 0); } } /// <summary> /// Gets the number of frames currently in the output queue. /// </summary> /// <value>Number representing frames waiting in output queue.</value> public int QueueCount { get { return OutputQueue.Count; } } /// <summary> /// Gets a value indicating whether this <see cref="Actinic.LED_Queue"/> has any effect on ouput, i.e. LEDs /// are not all black with no brightness. /// </summary> /// <value><c>true</c> if lights have no effect; otherwise, <c>false</c>.</value> public bool LightsHaveNoEffect { get { if (AnimationActive == true || QueueEmpty == false) return false; // Check if the lights -don't- have an effect. return !Lights.HasEffect; } } // FIXME: Revisit queue-wide blend-mode after LED Queue update private Color.BlendMode blending_mode = Color.BlendMode.Combine; /// <summary> /// When merged down, this defines how the layer should be handled, default of Combine. /// </summary> /// <value>The blending mode.</value> public Color.BlendMode BlendMode { get { return blending_mode; } set { blending_mode = value; } } private Queue<Layer> OutputQueue = new Queue<Layer> (); public LED_Queue (int LED_Light_Count) { InitializeFromBlanks (LED_Light_Count, false); } public LED_Queue (int LED_Light_Count, bool ClearAllLEDs) { InitializeFromBlanks (LED_Light_Count, ClearAllLEDs); } private void InitializeFromBlanks ( int LED_Light_Count, bool ClearAllLEDs) { byte brightness = (ClearAllLEDs ? (byte)0 : Color.MAX); Color fillColor = new Color (0, 0, 0, brightness); // Fill the layer with the given color Lights = new Layer (LED_Light_Count, Color.BlendMode.Combine, fillColor); // Copy to the processed list. When first initializing, skip // locking. LightsLastProcessed = Lights.Clone (); } public LED_Queue (Layer PreviouslyShownFrame) { Lights = PreviouslyShownFrame.Clone (); // Copy to the processed list. When first initializing, skip // locking. LightsLastProcessed = Lights.Clone (); } /// <summary> /// Marks the current queue as processed, copying it to LightsLastProcessed /// </summary> public void MarkAsProcessed () { lock (Lights) { lock (LightsLastProcessed) { // Clone the layer over to avoid any reference links LightsLastProcessed = Lights.Clone (); } } } /// <summary> /// Grabs the first frame from the queue if entries are queued, otherwise returns null /// </summary> /// <returns>If multiple frames are queued, returns a Layer, otherwise null</returns> public Layer PopFromQueue () { lock (OutputQueue) { if (OutputQueue.Count > 0) { Layer result = OutputQueue.Dequeue (); // Update the layer blending mode to the queue default // FIXME: Revisit blend-mode coercion after LED Queue update result.Blending = BlendMode; return result; } else { return null; } } } /// <summary> /// Adds the current state of the Lights frame to the end of the output queue /// </summary> public void PushToQueue () { PushToQueue (false); } /// <summary> /// Adds a frame to the end of the output queue /// </summary> /// <param name="NextFrame">A Layer representing the desired frame.</param> public void PushToQueue (Layer NextFrame) { if (NextFrame.PixelCount != LightCount) throw new ArgumentOutOfRangeException ("NextFrame", string.Format ( "NextFrame must contain same number of LEDs (has {0}," +
[ "\t\t\t\t\t\t\" expected {1})\", NextFrame.PixelCount, LightCount" ]
821
lcc
csharp
null
4673929404a475d693820dddae925a0b49797eeb5da4c706
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * http://www.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.nabucco.testautomation.result.facade.datatype.manual; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.nabucco.framework.base.facade.datatype.Datatype; import org.nabucco.framework.base.facade.datatype.collection.NabuccoCollectionState; import org.nabucco.framework.base.facade.datatype.collection.NabuccoList; import org.nabucco.framework.base.facade.datatype.collection.NabuccoListImpl; import org.nabucco.framework.base.facade.datatype.log.LogTrace; import org.nabucco.framework.base.facade.datatype.property.NabuccoProperty; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyContainer; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyDescriptor; import org.nabucco.framework.base.facade.datatype.property.PropertyAssociationType; import org.nabucco.framework.base.facade.datatype.property.PropertyCache; import org.nabucco.framework.base.facade.datatype.property.PropertyDescriptorSupport; import org.nabucco.testautomation.result.facade.datatype.TestResult; import org.nabucco.testautomation.result.facade.datatype.manual.ManualState; import org.nabucco.testautomation.result.facade.datatype.trace.ActionTrace; import org.nabucco.testautomation.result.facade.datatype.trace.FileTrace; import org.nabucco.testautomation.result.facade.datatype.trace.MessageTrace; import org.nabucco.testautomation.result.facade.datatype.trace.ScreenshotTrace; import org.nabucco.testautomation.settings.facade.datatype.engine.ContextSnapshot; /** * ManualTestResult<p/>The result of a manual test step<p/> * * @author Steffen Schmidt, PRODYNA AG, 2010-11-30 */ public class ManualTestResult extends TestResult implements Datatype { private static final long serialVersionUID = 1L; private static final ManualState STATE_DEFAULT = ManualState.INITIALIZED; private static final String[] PROPERTY_CONSTRAINTS = { "m1,1;", "l0,10000;u0,n;m0,1;", "l0,10000;u0,n;m0,1;", "m0,n;", "m0,n;", "m0,n;", "m0,n;", "m0,1;", "m0,1;" }; public static final String STATE = "state"; public static final String USERMESSAGE = "userMessage"; public static final String USERERRORMESSAGE = "userErrorMessage"; public static final String ACTIONTRACELIST = "actionTraceList"; public static final String SCREENSHOTS = "screenshots"; public static final String FILES = "files"; public static final String MESSAGES = "messages"; public static final String CONTEXTSNAPSHOT = "contextSnapshot"; public static final String PROPERTYLIST = "propertyList"; private ManualState state; private LogTrace userMessage; private LogTrace userErrorMessage; private NabuccoList<ActionTrace> actionTraceList; private NabuccoList<ScreenshotTrace> screenshots; private NabuccoList<FileTrace> files; private NabuccoList<MessageTrace> messages; private ContextSnapshot contextSnapshot; private ContextSnapshot propertyList; /** Constructs a new ManualTestResult instance. */ public ManualTestResult() { super(); this.initDefaults(); } /** InitDefaults. */ private void initDefaults() { state = STATE_DEFAULT; } /** * CloneObject. * * @param clone the ManualTestResult. */ protected void cloneObject(ManualTestResult clone) { super.cloneObject(clone); clone.setState(this.getState()); if ((this.getUserMessage() != null)) { clone.setUserMessage(this.getUserMessage().cloneObject()); } if ((this.getUserErrorMessage() != null)) { clone.setUserErrorMessage(this.getUserErrorMessage().cloneObject()); } if ((this.actionTraceList != null)) { clone.actionTraceList = this.actionTraceList.cloneCollection(); } if ((this.screenshots != null)) { clone.screenshots = this.screenshots.cloneCollection(); } if ((this.files != null)) { clone.files = this.files.cloneCollection(); } if ((this.messages != null)) { clone.messages = this.messages.cloneCollection(); } if ((this.getContextSnapshot() != null)) { clone.setContextSnapshot(this.getContextSnapshot().cloneObject()); } if ((this.getPropertyList() != null)) { clone.setPropertyList(this.getPropertyList().cloneObject()); } } /** * Getter for the ActionTraceListJPA. * * @return the List<ActionTrace>. */ List<ActionTrace> getActionTraceListJPA() { if ((this.actionTraceList == null)) { this.actionTraceList = new NabuccoListImpl<ActionTrace>(NabuccoCollectionState.EAGER); } return ((NabuccoListImpl<ActionTrace>) this.actionTraceList).getDelegate(); } /** * Setter for the ActionTraceListJPA. * * @param actionTraceList the List<ActionTrace>. */ void setActionTraceListJPA(List<ActionTrace> actionTraceList) { if ((this.actionTraceList == null)) { this.actionTraceList = new NabuccoListImpl<ActionTrace>(NabuccoCollectionState.EAGER); } ((NabuccoListImpl<ActionTrace>) this.actionTraceList).setDelegate(actionTraceList); } /** * CreatePropertyContainer. * * @return the NabuccoPropertyContainer. */ protected static NabuccoPropertyContainer createPropertyContainer() { Map<String, NabuccoPropertyDescriptor> propertyMap = new HashMap<String, NabuccoPropertyDescriptor>(); propertyMap.putAll(PropertyCache.getInstance().retrieve(TestResult.class).getPropertyMap()); propertyMap.put(STATE, PropertyDescriptorSupport.createEnumeration(STATE, ManualState.class, 19, PROPERTY_CONSTRAINTS[0], false)); propertyMap.put(USERMESSAGE, PropertyDescriptorSupport.createBasetype(USERMESSAGE, LogTrace.class, 20, PROPERTY_CONSTRAINTS[1], false)); propertyMap.put(USERERRORMESSAGE, PropertyDescriptorSupport.createBasetype(USERERRORMESSAGE, LogTrace.class, 21, PROPERTY_CONSTRAINTS[2], false)); propertyMap.put(ACTIONTRACELIST, PropertyDescriptorSupport.createCollection(ACTIONTRACELIST, ActionTrace.class, 22, PROPERTY_CONSTRAINTS[3], false, PropertyAssociationType.COMPOSITION)); propertyMap.put(SCREENSHOTS, PropertyDescriptorSupport.createCollection(SCREENSHOTS, ScreenshotTrace.class, 23, PROPERTY_CONSTRAINTS[4], false, PropertyAssociationType.COMPOSITION)); propertyMap.put(FILES, PropertyDescriptorSupport.createCollection(FILES, FileTrace.class, 24, PROPERTY_CONSTRAINTS[5], false, PropertyAssociationType.COMPOSITION)); propertyMap.put(MESSAGES, PropertyDescriptorSupport.createCollection(MESSAGES, MessageTrace.class, 25, PROPERTY_CONSTRAINTS[6], false, PropertyAssociationType.COMPOSITION)); propertyMap.put(CONTEXTSNAPSHOT, PropertyDescriptorSupport.createDatatype(CONTEXTSNAPSHOT, ContextSnapshot.class, 26, PROPERTY_CONSTRAINTS[7], false, PropertyAssociationType.COMPONENT)); propertyMap.put(PROPERTYLIST, PropertyDescriptorSupport.createDatatype(PROPERTYLIST, ContextSnapshot.class, 27, PROPERTY_CONSTRAINTS[8], false, PropertyAssociationType.COMPONENT)); return new NabuccoPropertyContainer(propertyMap); } @Override public void init() { this.initDefaults(); } @Override public Set<NabuccoProperty> getProperties() { Set<NabuccoProperty> properties = super.getProperties(); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(STATE), this.getState(), null)); properties .add(super.createProperty(ManualTestResult.getPropertyDescriptor(USERMESSAGE), this.userMessage, null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(USERERRORMESSAGE), this.userErrorMessage, null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(ACTIONTRACELIST), this.actionTraceList, null)); properties .add(super.createProperty(ManualTestResult.getPropertyDescriptor(SCREENSHOTS), this.screenshots, null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(FILES), this.files, null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(MESSAGES), this.messages, null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(CONTEXTSNAPSHOT), this.getContextSnapshot(), null)); properties.add(super.createProperty(ManualTestResult.getPropertyDescriptor(PROPERTYLIST), this.getPropertyList(), null)); return properties; } @Override @SuppressWarnings("unchecked") public boolean setProperty(NabuccoProperty property) { if (super.setProperty(property)) { return true; } if ((property.getName().equals(STATE) && (property.getType() == ManualState.class))) { this.setState(((ManualState) property.getInstance())); return true; } else if ((property.getName().equals(USERMESSAGE) && (property.getType() == LogTrace.class))) { this.setUserMessage(((LogTrace) property.getInstance())); return true; } else if ((property.getName().equals(USERERRORMESSAGE) && (property.getType() == LogTrace.class))) { this.setUserErrorMessage(((LogTrace) property.getInstance())); return true; } else if ((property.getName().equals(ACTIONTRACELIST) && (property.getType() == ActionTrace.class))) { this.actionTraceList = ((NabuccoList<ActionTrace>) property.getInstance()); return true; } else if ((property.getName().equals(SCREENSHOTS) && (property.getType() == ScreenshotTrace.class))) { this.screenshots = ((NabuccoList<ScreenshotTrace>) property.getInstance()); return true; } else if ((property.getName().equals(FILES) && (property.getType() == FileTrace.class))) { this.files = ((NabuccoList<FileTrace>) property.getInstance()); return true; } else if ((property.getName().equals(MESSAGES) && (property.getType() == MessageTrace.class))) { this.messages = ((NabuccoList<MessageTrace>) property.getInstance()); return true; } else if ((property.getName().equals(CONTEXTSNAPSHOT) && (property.getType() == ContextSnapshot.class))) { this.setContextSnapshot(((ContextSnapshot) property.getInstance())); return true; } else if ((property.getName().equals(PROPERTYLIST) && (property.getType() == ContextSnapshot.class))) { this.setPropertyList(((ContextSnapshot) property.getInstance())); return true; } return false; } @Override public boolean equals(Object obj) { if ((this == obj)) { return true; } if ((obj == null)) { return false; } if ((this.getClass() != obj.getClass())) { return false; } if ((!super.equals(obj))) { return false; } final ManualTestResult other = ((ManualTestResult) obj); if ((this.state == null)) { if ((other.state != null)) return false; } else if ((!this.state.equals(other.state))) return false; if ((this.userMessage == null)) { if ((other.userMessage != null)) return false; } else if ((!this.userMessage.equals(other.userMessage))) return false;
[ " if ((this.userErrorMessage == null)) {" ]
813
lcc
java
null
9de1c2d790d0cfc4b8f31402e8be6b0d06aa0e2623207f6a
/* * Copyright (C) 2012 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import static com.android.internal.telephony.RILConstants.*; import android.content.Context; import android.os.AsyncResult; import android.os.Message; import android.os.Parcel; import android.os.SystemProperties; import android.util.Log; import com.android.internal.telephony.RILConstants; import java.util.Collections; import android.telephony.PhoneNumberUtils; import java.util.ArrayList; /** * Custom RIL to handle unique behavior of D2 radio * * {@hide} */ public class SamsungBCMRIL extends RIL implements CommandsInterface { public SamsungBCMRIL(Context context, int networkMode, int cdmaSubscription) { super(context, networkMode, cdmaSubscription); mQANElements = 5; } public void dial(String address, int clirMode, UUSInfo uusInfo, Message result) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_DIAL, result); rr.mp.writeString(address); rr.mp.writeInt(clirMode); rr.mp.writeInt(0); // UUS information is absent: Samsung BCM compat if (uusInfo == null) { rr.mp.writeInt(0); // UUS information is absent } else { rr.mp.writeInt(1); // UUS information is present rr.mp.writeInt(uusInfo.getType()); rr.mp.writeInt(uusInfo.getDcs()); rr.mp.writeByteArray(uusInfo.getUserData()); } if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } protected void processSolicited (Parcel p) { int serial, error; boolean found = false; serial = p.readInt(); error = p.readInt(); RILRequest rr; rr = findAndRemoveRequestFromList(serial); if (rr == null) { Log.w(LOG_TAG, "Unexpected solicited response! sn: " + serial + " error: " + error); return; } Object ret = null; if (error == 0 || p.dataAvail() > 0) { // either command succeeds or command fails but with data payload try {switch (rr.mRequest) { /* cat libs/telephony/ril_commands.h \ | egrep "^ *{RIL_" \ | sed -re 's/\{([^,]+),[^,]+,([^}]+).+/case \1: ret = \2(p); break;/' */ case RIL_REQUEST_GET_SIM_STATUS: ret = responseIccCardStatus(p); break; case RIL_REQUEST_ENTER_SIM_PIN: ret = responseInts(p); break; case RIL_REQUEST_ENTER_SIM_PUK: ret = responseInts(p); break; case RIL_REQUEST_ENTER_SIM_PIN2: ret = responseInts(p); break; case RIL_REQUEST_ENTER_SIM_PUK2: ret = responseInts(p); break; case RIL_REQUEST_CHANGE_SIM_PIN: ret = responseInts(p); break; case RIL_REQUEST_CHANGE_SIM_PIN2: ret = responseInts(p); break; case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: ret = responseInts(p); break; case RIL_REQUEST_GET_CURRENT_CALLS: ret = responseCallList(p); break; case RIL_REQUEST_DIAL: ret = responseVoid(p); break; case RIL_REQUEST_GET_IMSI: ret = responseString(p); break; case RIL_REQUEST_HANGUP: ret = responseVoid(p); break; case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: ret = responseVoid(p); break; case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: { if (mTestingEmergencyCall.getAndSet(false)) { if (mEmergencyCallbackModeRegistrant != null) { riljLog("testing emergency call, notify ECM Registrants"); mEmergencyCallbackModeRegistrant.notifyRegistrant(); } } ret = responseVoid(p); break; } case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: ret = responseVoid(p); break; case RIL_REQUEST_CONFERENCE: ret = responseVoid(p); break; case RIL_REQUEST_UDUB: ret = responseVoid(p); break; case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: ret = responseInts(p); break; case RIL_REQUEST_SIGNAL_STRENGTH: ret = responseSignalStrength(p); break; case RIL_REQUEST_VOICE_REGISTRATION_STATE: ret = responseStrings(p); break; case RIL_REQUEST_DATA_REGISTRATION_STATE: ret = responseStrings(p); break; case RIL_REQUEST_OPERATOR: ret = responseStrings(p); break; case RIL_REQUEST_RADIO_POWER: ret = responseVoid(p); break; case RIL_REQUEST_DTMF: ret = responseVoid(p); break; case RIL_REQUEST_SEND_SMS: ret = responseSMS(p); break; case RIL_REQUEST_SEND_SMS_EXPECT_MORE: ret = responseSMS(p); break; case RIL_REQUEST_SETUP_DATA_CALL: ret = responseSetupDataCall(p); break; case RIL_REQUEST_SIM_IO: ret = responseICC_IO(p); break; case RIL_REQUEST_SEND_USSD: ret = responseVoid(p); break; case RIL_REQUEST_CANCEL_USSD: ret = responseVoid(p); break; case RIL_REQUEST_GET_CLIR: ret = responseInts(p); break; case RIL_REQUEST_SET_CLIR: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: ret = responseCallForward(p); break; case RIL_REQUEST_SET_CALL_FORWARD: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_CALL_WAITING: ret = responseInts(p); break; case RIL_REQUEST_SET_CALL_WAITING: ret = responseVoid(p); break; case RIL_REQUEST_SMS_ACKNOWLEDGE: ret = responseVoid(p); break; case RIL_REQUEST_GET_IMEI: ret = responseString(p); break; case RIL_REQUEST_GET_IMEISV: ret = responseString(p); break; case RIL_REQUEST_ANSWER: ret = responseVoid(p); break; case RIL_REQUEST_DEACTIVATE_DATA_CALL: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_FACILITY_LOCK: ret = responseInts(p); break; case RIL_REQUEST_SET_FACILITY_LOCK: ret = responseInts(p); break; case RIL_REQUEST_CHANGE_BARRING_PASSWORD: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: ret = responseInts(p); break; case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: ret = responseVoid(p); break; case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : ret = responseOperatorInfos(p); break; case RIL_REQUEST_DTMF_START: ret = responseVoid(p); break; case RIL_REQUEST_DTMF_STOP: ret = responseVoid(p); break; case RIL_REQUEST_BASEBAND_VERSION: ret = responseString(p); break; case RIL_REQUEST_SEPARATE_CONNECTION: ret = responseVoid(p); break; case RIL_REQUEST_SET_MUTE: ret = responseVoid(p); break; case RIL_REQUEST_GET_MUTE: ret = responseInts(p); break; case RIL_REQUEST_QUERY_CLIP: ret = responseInts(p); break; case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: ret = responseInts(p); break; case RIL_REQUEST_DATA_CALL_LIST: ret = responseDataCallList(p); break; case RIL_REQUEST_RESET_RADIO: ret = responseVoid(p); break; case RIL_REQUEST_OEM_HOOK_RAW: ret = responseRaw(p); break; case RIL_REQUEST_OEM_HOOK_STRINGS: ret = responseStrings(p); break; case RIL_REQUEST_SCREEN_STATE: ret = responseVoid(p); break; case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION: ret = responseVoid(p); break; case RIL_REQUEST_WRITE_SMS_TO_SIM: ret = responseInts(p); break; case RIL_REQUEST_DELETE_SMS_ON_SIM: ret = responseVoid(p); break; case RIL_REQUEST_SET_BAND_MODE: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: ret = responseInts(p); break; case RIL_REQUEST_STK_GET_PROFILE: ret = responseString(p); break; case RIL_REQUEST_STK_SET_PROFILE: ret = responseVoid(p); break; case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: ret = responseString(p); break; case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: ret = responseVoid(p); break; case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: ret = responseInts(p); break; case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: ret = responseVoid(p); break; case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: ret = responseVoid(p); break; case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: ret = responseGetPreferredNetworkType(p); break; case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: ret = responseCellList(p); break; case RIL_REQUEST_SET_LOCATION_UPDATES: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE: ret = responseInts(p); break; case RIL_REQUEST_SET_TTY_MODE: ret = responseVoid(p); break; case RIL_REQUEST_QUERY_TTY_MODE: ret = responseInts(p); break; case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE: ret = responseInts(p); break; case RIL_REQUEST_CDMA_FLASH: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_BURST_DTMF: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_SEND_SMS: ret = responseSMS(p); break; case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE: ret = responseVoid(p); break; case RIL_REQUEST_GSM_GET_BROADCAST_CONFIG: ret = responseGmsBroadcastConfig(p); break; case RIL_REQUEST_GSM_SET_BROADCAST_CONFIG: ret = responseVoid(p); break; case RIL_REQUEST_GSM_BROADCAST_ACTIVATION: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_GET_BROADCAST_CONFIG: ret = responseCdmaBroadcastConfig(p); break; case RIL_REQUEST_CDMA_SET_BROADCAST_CONFIG: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_BROADCAST_ACTIVATION: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_SUBSCRIPTION: ret = responseStrings(p); break; case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: ret = responseInts(p); break; case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: ret = responseVoid(p); break; case RIL_REQUEST_DEVICE_IDENTITY: ret = responseStrings(p); break; case RIL_REQUEST_GET_SMSC_ADDRESS: ret = responseString(p); break; case RIL_REQUEST_SET_SMSC_ADDRESS: ret = responseVoid(p); break; case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: ret = responseVoid(p); break; case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: ret = responseVoid(p); break; case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: ret = responseVoid(p); break; case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: ret = responseInts(p); break; case RIL_REQUEST_ISIM_AUTHENTICATION: ret = responseString(p); break; case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: ret = responseVoid(p); break; case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: ret = responseICC_IO(p); break; case RIL_REQUEST_VOICE_RADIO_TECH: ret = responseInts(p); break; default: throw new RuntimeException("Unrecognized solicited response: " + rr.mRequest); //break; }} catch (Throwable tr) { // Exceptions here usually mean invalid RIL responses Log.w(LOG_TAG, rr.serialString() + "< " + requestToString(rr.mRequest) + " exception, possible invalid RIL response", tr); if (rr.mResult != null) { AsyncResult.forMessage(rr.mResult, null, tr); rr.mResult.sendToTarget(); } rr.release(); return; } } // Here and below fake RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, see b/7255789. // This is needed otherwise we don't automatically transition to the main lock // screen when the pin or puk is entered incorrectly. // Note for the I9082: we're faking more than the standard RIL switch (rr.mRequest) { case RIL_REQUEST_ENTER_SIM_PUK: case RIL_REQUEST_ENTER_SIM_PUK2: case RIL_REQUEST_ENTER_SIM_PIN: case RIL_REQUEST_ENTER_SIM_PIN2: case RIL_REQUEST_CHANGE_SIM_PIN: case RIL_REQUEST_CHANGE_SIM_PIN2: case RIL_REQUEST_SET_FACILITY_LOCK: if (mIccStatusChangedRegistrants != null) { if (RILJ_LOGD) { riljLog("ON enter sim puk fakeSimStatusChanged: reg count=" + mIccStatusChangedRegistrants.size()); } mIccStatusChangedRegistrants.notifyRegistrants(); } break; } if (error != 0) { rr.onError(error, ret); rr.release(); return; } if (RILJ_LOGD) riljLog(rr.serialString() + "< " + requestToString(rr.mRequest) + " " + retToString(rr.mRequest, ret)); if (rr.mResult != null) { AsyncResult.forMessage(rr.mResult, ret, null); rr.mResult.sendToTarget(); } rr.release(); } @Override protected Object responseCallList(Parcel p) { int num; int voiceSettings; ArrayList<DriverCall> response; DriverCall dc; num = p.readInt(); response = new ArrayList<DriverCall>(num); for (int i = 0 ; i < num ; i++) { dc = new DriverCall(); dc.state = DriverCall.stateFromCLCC(p.readInt());
[ " dc.index = p.readInt();" ]
1,196
lcc
java
null
ea1234d3d85703f270dfcff3d2aedc39d8ebe2b1d2369a39
package de.fhg.fokus.mdc.odrClientProxy.registry; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fhg.fokus.mdc.odrClientProxy.model.GemoApplicationResource; import de.fhg.fokus.mdc.odrClientProxy.model.GemoMetadata; import de.fhg.fokus.odp.registry.ODRClient; import de.fhg.fokus.odp.registry.ckan.impl.LicenceImpl; import de.fhg.fokus.odp.registry.ckan.impl.ScopeImpl; import de.fhg.fokus.odp.registry.ckan.json.LicenceBean; import de.fhg.fokus.odp.registry.ckan.json.ScopeBean; import de.fhg.fokus.odp.registry.model.Category; import de.fhg.fokus.odp.registry.model.Contact; import de.fhg.fokus.odp.registry.model.Licence; import de.fhg.fokus.odp.registry.model.Metadata; import de.fhg.fokus.odp.registry.model.MetadataEnumType; import de.fhg.fokus.odp.registry.model.Resource; import de.fhg.fokus.odp.registry.model.RoleEnumType; import de.fhg.fokus.odp.registry.model.Scope; /*The MetadataWrapper adds a level of abstraction to the Metadata interface of odrc since in gemo not all the methods are needed to be exposed*/ public class MetadataWrapper { private Metadata odrMetadata; public Metadata getOdrMetadata() { return odrMetadata; } public void setOdrMetadata(Metadata odrMetadata) { this.odrMetadata = odrMetadata; } /** The logger. */ private final Logger LOG = LoggerFactory.getLogger(getClass()); /** The licences. */ private List<Licence> relevantLicences; /** The categories. */ private List<Category> categories; /** The sectors. */ // private List<SectorEnumType> sectors; /** The geo granularities. */ // private List<GeoGranularityEnumType> geoGranularities; /** The temporal granularity enum types. */ // private List<TemporalGranularityEnumType> temporalGranularityEnumTypes; /** The selected categories. */ // private List<String> selectedCategories; /** The selected tags. */ // private List<String> selectedTags; /** The author. */ private Contact author; /** The maintainer. */ // private Contact maintainer; /** The distributor. */ // private Contact distributor; /** The date pattern. */ public final static String DATE_PATTERN = "dd.MM.yyyy"; // adjust the Map<String, Object> appMetadata method // public Metadata init(ODRClient odrc, Map<String, Object> appMetadata) { // odrMetadata = odrc.createMetadata(MetadataEnumType.APPLICATION); // odrMetadata.setTitle(appMetadata.get("name").toString()); // return odrMetadata; // } public String getTitle() { return this.odrMetadata.getTitle(); } public void setTitle(String title) { this.odrMetadata.setTitle(title); } public String getName() { return this.odrMetadata.getTitle(); } public String getAuthor() { return this.odrMetadata.getAuthor(); } public String getLicenceId() { return this.odrMetadata.getLicence().getName(); } /* if odrMetadata is null, registering new */ // TODO do not catch the exception here protected Metadata translateGemoMetadataToODR(ODRClient odrc, GemoMetadata gemoMetadata) { if (odrMetadata == null) { odrMetadata = odrc.createMetadata(MetadataEnumType.DOCUMENT); LOG.debug("created new Metadata object"); } getLicencesforType(odrc); try { writeIntoODRMetadata(odrc, gemoMetadata); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return odrMetadata; } /* if odrMetadata is not null, if it is set with odrc.getM and odrc.queryM */ private void writeIntoODRMetadata(ODRClient odrc, GemoMetadata gemoMetadata) throws JsonGenerationException, JsonMappingException, IOException { // TODO other metadata fields to be mapped // when creating metadata persistMetadata sets the odrMetadata.name // based on title, // when updating metadata, odrMetadata has already a unique name as // identifier, so cannot be changed odrMetadata.setTitle(gemoMetadata.getName()); // set values for the author which is referenced by // metadataimpl.contacts list author = odrMetadata.newContact(RoleEnumType.AUTHOR); author.setName(gemoMetadata.getAuthor()); setLicence(gemoMetadata.getLicenceId()); // why list licences if set already? odrc.listLicenses(); odrMetadata.setNotes(gemoMetadata.getDescription()); categories = odrc.listCategories(); // TODO change this with search for the name that gemometadata specified Category e = null; for (Category c : categories) { if (c.getName().equals(gemoMetadata.getCategory())) e = c; } odrMetadata.getCategories().add(e); // odrMetadata.set List<GemoApplicationResource> gemoResources = gemoMetadata .getResources(); if (gemoResources.size() > 0) { for (GemoApplicationResource gemoR : gemoResources) { Resource r = odrc.createResource(); r.setDescription(gemoR.getDescription()); r.setFormat(gemoR.getFormat()); r.setUrl(gemoR.getUrl()); odrMetadata.getResources().add(r); } } List<ScopeBean> gemoScopes = new ArrayList<ScopeBean>(); gemoScopes = gemoMetadata.getScopes(); if (gemoScopes.size() > 0) { for (ScopeBean scopeBean : gemoScopes) { Scope odrScope = new ScopeImpl(scopeBean); odrMetadata.getScopes().add(odrScope); } } } protected GemoMetadata readIntoGemo(Metadata metadata) { GemoMetadata gemoMetadata = new GemoMetadata(); gemoMetadata.setAuthor(metadata.getContacts().get(0).getName()); gemoMetadata.setName(metadata.getName()); gemoMetadata.setLicenceId(metadata.getLicence().getName()); gemoMetadata.setDescription(metadata.getNotes()); List<GemoApplicationResource> gemoResources = new ArrayList<GemoApplicationResource>(); List<Resource> odrResources = metadata.getResources(); // go through the resources list of metadata, add to gemoresources list for (Resource odrResource : odrResources) { GemoApplicationResource gemoResource = new GemoApplicationResource(); gemoResource.setUrl(odrResource.getUrl()); gemoResource.setFormat(odrResource.getFormat()); gemoResource.setDescription(odrResource.getDescription()); gemoResources.add(gemoResource); } gemoMetadata.setResources(gemoResources); List<ScopeBean> gemoScopes = new ArrayList<ScopeBean>(); List<Scope> odrScopes = metadata.getScopes(); for (Scope s : odrScopes) { ScopeBean gemoScope = new ScopeBean(); gemoScope.setName(s.getName()); gemoScope.setDescription(s.getDescription()); gemoScopes.add(gemoScope); } gemoMetadata.setScopes(gemoScopes); // TODO other metadata fields to be mapped return gemoMetadata; } private void getLicencesforType(ODRClient odrClient) { relevantLicences = new ArrayList<Licence>(); List<Licence> availableLicences = odrClient.listLicenses(); /* * Fill licences according to the metadata type: dataset, app, document */ if (availableLicences.size() > 0) { LOG.debug("Number of available licences: " + availableLicences.size()); try { if (odrMetadata.getType().equals(MetadataEnumType.DATASET) || odrMetadata.getType().equals( MetadataEnumType.UNKNOWN)) { for (Licence licence : availableLicences) { if (licence.isDomainData()) { relevantLicences.add(licence); } } } else if (odrMetadata.getType().equals( MetadataEnumType.APPLICATION)) { for (Licence licence : availableLicences) {
[ "\t\t\t\t\t\tif (licence.isDomainSoftware()) {" ]
679
lcc
java
null
3a16af734adf48dc73f6e28cfaec11262bb343e3da134f90
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using MoonSharp.Interpreter; /// <summary> /// This game object manages a mesh+texture+renderer+material that is /// used to superimpose a semi-transparent "overlay" to the map. /// </summary> [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class OverlayMap : MonoBehaviour { public Dictionary<string, OverlayDescriptor> overlays; /// <summary> /// Starting left corner (x,y) and z-coordinate of mesh and (3d left corner) /// </summary> public Vector3 leftBottomCorner = new Vector3(-0.5f, -0.5f, 1f); /// <summary> /// Transparency of overlay /// </summary> [Range(0,1)] public float transparency = 0.8f; /// <summary> /// Update interval (0 for every Update, inf for never) /// </summary> public float updateInterval = 5f; /// <summary> /// Time since last update /// </summary> float elapsed = 0f; /// <summary> /// Resolution of tile for the overlay /// </summary> public int xPixelsPerTile = 20; public int yPixelsPerTile = 20; /// <summary> /// Internal storage of size of map /// </summary> public int xSize = 10; public int ySize = 10; /// <summary> /// Script with user-defined lua valueAt functions /// </summary> Script script; /// <summary> /// /// </summary> public string currentOverlay; /// <summary> /// You can set any function, overlay will display value of func at point (x,y) /// Depending on how many colors the colorMap has, the displayed values will cycle /// </summary> public Func<int, int, int> valueAt; /// <summary> /// Current color map, setting the map causes the colorMapArray to be recreated /// </summary> private OverlayDescriptor.ColorMap _colorMap; public OverlayDescriptor.ColorMap colorMap { set { _colorMap = value; GenerateColorMap(); } get { return _colorMap; } } /// <summary> /// Name of xml file containing overlay prototypes /// </summary> public string xmlFileName = "overlay_prototypes.xml"; /// <summary> /// Name of lua script containing overlay prototypes functions /// </summary> public string LUAFileName = "overlay_functions.lua"; /// <summary> /// Storage for color map as texture, copied from using copyTexture on GPUs /// This texture is made of n*x times y pixels, where n is the size of the "colorMap" /// x and y is the size of 1 tile of the map (20x20 by default) /// Constructed from the colorMap /// </summary> Texture2D colorMapTexture; /// <summary> /// Mesh data /// </summary> Vector3[] newVertices; Vector3[] newNormals; Vector2[] newUV; int[] newTriangles; MeshRenderer meshRenderer; MeshFilter meshFilter; /// <summary> /// Array with colors for overlay (colormap) /// Each element is a color that will be part of the color palette /// </summary> Color32[] colorMapArray; /// <summary> /// True if Init() has been called (i.e. there is a mesh and a color map) /// </summary> bool initialized = false; // The texture applied to the entire overlay map Texture2D texture; public GameObject parentPanel; /// <summary> /// Grabs references, sets a dummy size and evaluation function /// </summary> void Start() { // Grab references meshRenderer = GetComponent<MeshRenderer>(); meshFilter = GetComponent<MeshFilter>(); // Read xml prototypes overlays = OverlayDescriptor.ReadPrototypes(xmlFileName); // Read LUA UserData.RegisterAssembly(); string scriptFile = System.IO.Path.Combine(UnityEngine.Application.streamingAssetsPath, System.IO.Path.Combine("Overlay", LUAFileName)); string scriptTxt = System.IO.File.ReadAllText(scriptFile); script = new Script(); script.DoString(scriptTxt); // Build GUI CreateGUI(); // TODO: remove this dummy set size SetSize(100, 100); SetOverlay("None"); } /// <summary> /// If update is required, redraw texture ("bake") (kinda expensive) /// </summary> void Update() { elapsed += Time.deltaTime; if (currentOverlay != "None" && elapsed > updateInterval) { Bake(); elapsed = 0f; } // TODO: Prettify Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //World.current.GetTileAt((int) pos.x, (int) pos.y); if(valueAt != null) textView.GetComponent<UnityEngine.UI.Text>().text = string.Format("[DEBUG] Currently over: {0}", valueAt((int)(pos.x + 0.5f), (int)(pos.y + 0.5f))); } void Destroy() { //dropdownObject.GetComponent<UnityEngine.UI.Dropdown>().onValueChanged.RemoveAllListeners(); //Destroy(dropdownObject); } /// <summary> /// If overlay is toggled on, it should be "baked" /// </summary> void Awake() { Bake(); } /// <summary> /// Set size of texture and mesh, recreates mesh /// </summary> /// <param name="x">Num tiles x-dir.</param> /// <param name="y">Num tiles y-dir.</param> public void SetSize(int x, int y) { xSize = x; ySize = y; if (meshRenderer != null) Init(); } /// <summary> /// Generates the mesh and the texture for the colormap. /// </summary> void Init() { GenerateMesh(); GenerateColorMap(); // Size in pixels of overlay texture and create texture int textureWidth = xSize * xPixelsPerTile; int textureHeight = ySize * yPixelsPerTile; texture = new Texture2D(textureWidth, textureHeight); texture.wrapMode = TextureWrapMode.Clamp; // Set material Shader shader = Shader.Find("Transparent/Diffuse"); Material mat = new Material(shader); meshRenderer.material = mat; if(mat == null || meshRenderer == null || texture == null) { Debug.ULogErrorChannel("OverlayMap", "Material or renderer is null. Failing."); } meshRenderer.material.mainTexture = texture; initialized = true; } /// <summary> /// Paint the texture /// </summary> public void Bake() { if (initialized && valueAt != null) GenerateTexture(); } /// <summary> /// Create the colormap texture from the color set /// </summary> void GenerateColorMap() { // TODO: make the map configurable colorMapArray = ColorMap(colorMap, 255); // Colormap texture int textureWidth = colorMapArray.Length * xPixelsPerTile; int textureHeight = yPixelsPerTile; colorMapTexture = new Texture2D(textureWidth, textureHeight); // Loop over each color in the palette and build a noisy texture int n = 0; foreach (Color32 baseColor in colorMapArray) { for (int y = 0; y < yPixelsPerTile; y++) { for (int x = 0; x < xPixelsPerTile; x++) { Color colorCopy = baseColor; colorCopy.a = transparency; // Add some noise to "prettify" colorCopy.r += UnityEngine.Random.Range(-0.03f, 0.03f); colorCopy.b += UnityEngine.Random.Range(-0.03f, 0.03f); colorCopy.g += UnityEngine.Random.Range(-0.03f, 0.03f); colorMapTexture.SetPixel(n * xPixelsPerTile + x, y, colorCopy); } } ++n; } colorMapTexture.Apply(); colorMapView.GetComponent<UnityEngine.UI.Image>().material.mainTexture = colorMapTexture; //colorMapView.GetComponent<UnityEngine.UI.Image>() } /// <summary> /// Build the huge overlay texture /// </summary> void GenerateTexture() { //Debug.ULogChannel("OverlayMap", "Regenerating texture!"); if (colorMapTexture == null) Debug.ULogErrorChannel("OverlayMap", "No color map texture setted!"); for (int y = 0; y < ySize; y++) { for (int x = 0; x < xSize; x++) { float v = valueAt(x, y); Debug.Assert(v >= 0 && v < 256); Graphics.CopyTexture(colorMapTexture, 0, 0, ((int) v % 256) * xPixelsPerTile, 0, xPixelsPerTile, yPixelsPerTile, texture, 0, 0, x * xPixelsPerTile, y * yPixelsPerTile); } } texture.Apply(true); } /// <summary> /// Build mesh /// </summary> void GenerateMesh() { Mesh mesh = new Mesh(); if (meshFilter != null) meshFilter.mesh = mesh; int xSizeP = xSize + 1; int ySizeP = ySize + 1; newVertices = new Vector3[xSizeP * ySizeP]; newNormals = new Vector3[xSizeP * ySizeP]; newUV = new Vector2[xSizeP * ySizeP]; newTriangles = new int[(xSizeP - 1) * (ySizeP - 1) * 6]; for (int y = 0; y < ySizeP; y++) {
[ " for (int x = 0; x < xSizeP; x++)" ]
1,083
lcc
csharp
null
a85ec69aacbcbe8db663b015147d5e8f96ae3e1481e5036c
package org.bitseal.network; import java.net.MalformedURLException; import java.net.URL; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import org.bitseal.core.App; import org.bitseal.data.ServerRecord; import org.bitseal.database.ServerRecordProvider; import android.util.Log; import de.timroes.axmlrpc.XMLRPCClient; import de.timroes.axmlrpc.XMLRPCException; /** * An object which uses the XMLRPC client class to connect to servers running * PyBitmessage and call methods from the PyBitmessage API. * * @author Jonathan Coe */ public class ApiCaller { private URL url; private String username; private String password; private XMLRPCClient newClient; private XMLRPCClient client; private ArrayList<URL> urlList; private ArrayList<String> usernameList; private ArrayList<String> passwordList; private int urlCounter; private int usernameCounter; private int passwordCounter; private int numberOfServers; /** * This constant defines the timeout period for API calls. */ private static final int TIMEOUT_SECONDS = 10; /** * API command used for connection testing */ private static final String API_METHOD_ADD = "add"; private static final String TAG = "API_CALLER"; /** * Creates a new ApiCaller object and sets the URL, username, and password values needed * to connect to the PyBitmessage servers. */ public ApiCaller() { // Check if any server records exist in app storage. If not, set up the default list of server records. ServerRecordProvider servProv = ServerRecordProvider.get(App.getContext()); ArrayList<ServerRecord> retrievedServerRecords = servProv.getAllServerRecords(); if (retrievedServerRecords.size() == 0) { Log.i(TAG, "No server records found in app storage. Setting up list of default servers."); ServerHelper servHelp = new ServerHelper(); servHelp.setupDefaultServers(); // Now the server records should be available from the database retrievedServerRecords = servProv.getAllServerRecords(); } numberOfServers = retrievedServerRecords.size(); // Set up ArrayLists for the URLs, usernames, and passwords of the servers urlList = new ArrayList<URL>(); usernameList = new ArrayList<String>(); passwordList = new ArrayList<String>(); // Randomize the order of the server records list in order to avoid servers always being called in // the same order. Collections.shuffle(retrievedServerRecords, new SecureRandom()); int arrayListIndex = 0; for(ServerRecord s : retrievedServerRecords) { try { urlList.add(arrayListIndex, new URL(s.getURL())); usernameList.add(arrayListIndex, s.getUsername()); passwordList.add(arrayListIndex, s.getPassword()); arrayListIndex ++; } catch (MalformedURLException e) { Log.e(TAG, "Malformed URL exception occurred in ApiCaller constructor. We will ignore the ServerRecord that contains this " + "url. The String representation of the url was " + s.getURL()); arrayListIndex ++; } } // Start at the beginning of each of the three lists urlCounter = 0; usernameCounter = 0; passwordCounter = 0; url = urlList.get(urlCounter); username = usernameList.get(usernameCounter); password = passwordList.get(passwordCounter); client = setUpClient(url, username, password); Log.i(TAG, "ApiCaller setup completed"); } /** * Makes a call to the PyBitmessage XMLRPC API. <br><br> * * Attempts to establish a connection to one of the listed servers. The method will attempt to * connect to each server in sequence, until either a connection is successfully established or * all servers have been tested without any successful connection. If a connection is successfully * established, then the API call will be made. * * @param method - A String which specifies the API method to be called * @param params - One or more Objects which provide the parameters for the API call * * @return An Object containing the result of the API call */ public Object call(String method, Object... params) { while (urlCounter < urlList.size()) { boolean connectionSuccessful = doConnectionTest(); if (connectionSuccessful) { Log.i(TAG, "Successfully connected to " + url.toString()); try { Log.i(TAG, "About to make an API call to " + url.toString()); Object result = client.call(method, params); return result; } catch (XMLRPCException e) { Log.e(TAG, "XMLRPCException occurred in ApiCaller.call() \n" + "Execption message was: " + e.getMessage()); switchToNextServer(); } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException occurred in ApiCaller.call() \n" + "Execption message was: " + e.getMessage()); switchToNextServer(); } catch (Exception e) { Log.e(TAG, "An Exception occurred in ApiCaller.call() \n" + "Execption message was: " + e.getMessage()); switchToNextServer(); } } else { switchToNextServer(); } } throw new RuntimeException("API call failed after trying all listed servers. Last attempted URL was " + url.toString()); } /** * Sets up the XMLRPC client to use the next server in the list. If the end * of the list has been reached, throws a RuntimeException. */ public void switchToNextServer() { if (urlCounter < (urlList.size() - 1)) { Log.i(TAG, "Currently the URL in use is " + url.toString() + ", about to change to next URL"); urlCounter ++; usernameCounter ++; passwordCounter ++; url = urlList.get(urlCounter); username = usernameList.get(usernameCounter); password = passwordList.get(passwordCounter); client = setUpClient(url, username, password); } else { throw new RuntimeException("API call failed after trying all listed servers. Last attempted URL was " + url.toString()); } } /** * Returns the number of servers in use. */ public int getNumberOfServers() { return numberOfServers; } /** * Performs a connection test by calling the "add" method from the PyBitmessage API and * checking if the returned result (if any) is correct. * * @return A boolean indicating whether or not a connection was successfully established */ private boolean doConnectionTest() { Object rawResult = null; try { Log.i(TAG, "Running doConnectionTest() with server at " + url.toString()); int result = -1; // Explicitly set this value to ensure a meaningful test. The testInt values will always be >=0, so the test should never give a false positive result. Random rand = new Random(); int testInt1 = rand.nextInt(5000);
[ "\t\t\tint testInt2 = rand.nextInt(5000);" ]
845
lcc
java
null
d87a8d45371d8a5b1d38f4ab97868fb93ab6a18b81e452ea
/* * OCaml Support For IntelliJ Platform. * Copyright (C) 2010 Maxim Manuylov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package manuylov.maxim.ocaml.lang.feature.completion; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import javax.swing.border.Border; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.event.EditorMouseEventArea; import com.intellij.openapi.editor.event.EditorMouseListener; import com.intellij.openapi.editor.event.EditorMouseMotionListener; import com.intellij.openapi.editor.event.SelectionListener; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import consulo.disposer.Disposable; import consulo.util.dataholder.Key; /** * @author Maxim.Manuylov * Date: 26.05.2010 */ @SuppressWarnings({"ConstantConditions"}) public class MockEditor implements Editor { @Nonnull public Document getDocument() { return new MyMockDocument(); } public boolean isViewer() { return false; } @Nonnull public JComponent getComponent() { return null; } @Nonnull public JComponent getContentComponent() { return null; } @Override public void setBorder(@Nullable Border border) { } @Override public Insets getInsets() { return null; } @Nonnull public SelectionModel getSelectionModel() { return new SelectionModel() { public int getSelectionStart() { return 0; } @Nullable @Override public VisualPosition getSelectionStartPosition() { return null; } public int getSelectionEnd() { return 0; } @Nullable @Override public VisualPosition getSelectionEndPosition() { return null; } public String getSelectedText() { return null; } @Nullable @Override public String getSelectedText(boolean b) { return null; } public int getLeadSelectionOffset() { return 0; } @Nullable @Override public VisualPosition getLeadSelectionPosition() { return null; } public boolean hasSelection() { return false; } @Override public boolean hasSelection(boolean b) { return false; } public void setSelection(final int startOffset, final int endOffset) { } @Override public void setSelection(int i, @Nullable VisualPosition visualPosition, int i1) { } @Override public void setSelection(@Nullable VisualPosition visualPosition, int i, @Nullable VisualPosition visualPosition1, int i1) { } public void removeSelection() { } @Override public void removeSelection(boolean b) { } public void addSelectionListener(final SelectionListener listener) { } public void removeSelectionListener(final SelectionListener listener) { } public void selectLineAtCaret() { } public void selectWordAtCaret(final boolean honorCamelWordsSettings) { } public void copySelectionToClipboard() { } public void setBlockSelection(final LogicalPosition blockStart, final LogicalPosition blockEnd) { } public void removeBlockSelection() { } public boolean hasBlockSelection() { return false; } @Nonnull public int[] getBlockSelectionStarts() {
[ "\t\t\t\treturn new int[0];" ]
431
lcc
java
null
9ebf3a9f0f2f7e7496ccd13c44ec7354a4a0230fe1f15f47
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package org.hotswap.agent.javassist.tools.rmi; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Vector; import org.hotswap.agent.javassist.CannotCompileException; import org.hotswap.agent.javassist.ClassPool; import org.hotswap.agent.javassist.NotFoundException; import org.hotswap.agent.javassist.tools.web.BadHttpRequest; import org.hotswap.agent.javassist.tools.web.Webserver; /** * An AppletServer object is a web server that an ObjectImporter * communicates with. It makes the objects specified by * <code>exportObject()</code> remotely accessible from applets. * If the classes of the exported objects are requested by the client-side * JVM, this web server sends proxy classes for the requested classes. * * @see javassist.tools.rmi.ObjectImporter */ public class AppletServer extends Webserver { private StubGenerator stubGen; private Map<String,ExportedObject> exportedNames; private List<ExportedObject> exportedObjects; private static final byte[] okHeader = "HTTP/1.0 200 OK\r\n\r\n".getBytes(); /** * Constructs a web server. * * @param port port number */ public AppletServer(String port) throws IOException, NotFoundException, CannotCompileException { this(Integer.parseInt(port)); } /** * Constructs a web server. * * @param port port number */ public AppletServer(int port) throws IOException, NotFoundException, CannotCompileException { this(ClassPool.getDefault(), new StubGenerator(), port); } /** * Constructs a web server. * * @param port port number * @param src the source of classs files. */ public AppletServer(int port, ClassPool src) throws IOException, NotFoundException, CannotCompileException { this(new ClassPool(src), new StubGenerator(), port); } private AppletServer(ClassPool loader, StubGenerator gen, int port) throws IOException, NotFoundException, CannotCompileException { super(port); exportedNames = new Hashtable<String,ExportedObject>(); exportedObjects = new Vector<ExportedObject>(); stubGen = gen; addTranslator(loader, gen); } /** * Begins the HTTP service. */ @Override public void run() { super.run(); } /** * Exports an object. * This method produces the bytecode of the proxy class used * to access the exported object. A remote applet can load * the proxy class and call a method on the exported object. * * @param name the name used for looking the object up. * @param obj the exported object. * @return the object identifier * * @see javassist.tools.rmi.ObjectImporter#lookupObject(String) */ public synchronized int exportObject(String name, Object obj) throws CannotCompileException { Class<?> clazz = obj.getClass(); ExportedObject eo = new ExportedObject(); eo.object = obj; eo.methods = clazz.getMethods(); exportedObjects.add(eo); eo.identifier = exportedObjects.size() - 1; if (name != null) exportedNames.put(name, eo); try { stubGen.makeProxyClass(clazz); } catch (NotFoundException e) { throw new CannotCompileException(e); } return eo.identifier; } /** * Processes a request from a web browser (an ObjectImporter). */ @Override public void doReply(InputStream in, OutputStream out, String cmd) throws IOException, BadHttpRequest { if (cmd.startsWith("POST /rmi ")) processRMI(in, out); else if (cmd.startsWith("POST /lookup ")) lookupName(cmd, in, out); else super.doReply(in, out, cmd); } private void processRMI(InputStream ins, OutputStream outs) throws IOException { ObjectInputStream in = new ObjectInputStream(ins); int objectId = in.readInt(); int methodId = in.readInt(); Exception err = null; Object rvalue = null; try { ExportedObject eo = exportedObjects.get(objectId); Object[] args = readParameters(in); rvalue = convertRvalue(eo.methods[methodId].invoke(eo.object, args)); } catch(Exception e) { err = e; logging2(e.toString()); } outs.write(okHeader); ObjectOutputStream out = new ObjectOutputStream(outs); if (err != null) { out.writeBoolean(false); out.writeUTF(err.toString()); } else try { out.writeBoolean(true); out.writeObject(rvalue); } catch (NotSerializableException e) { logging2(e.toString()); } catch (InvalidClassException e) { logging2(e.toString()); } out.flush(); out.close(); in.close(); } private Object[] readParameters(ObjectInputStream in) throws IOException, ClassNotFoundException { int n = in.readInt(); Object[] args = new Object[n]; for (int i = 0; i < n; ++i) { Object a = in.readObject(); if (a instanceof RemoteRef) { RemoteRef ref = (RemoteRef)a; ExportedObject eo = exportedObjects.get(ref.oid); a = eo.object; } args[i] = a; } return args; } private Object convertRvalue(Object rvalue) throws CannotCompileException { if (rvalue == null) return null; // the return type is void. String classname = rvalue.getClass().getName(); if (stubGen.isProxyClass(classname)) return new RemoteRef(exportObject(null, rvalue), classname); return rvalue; } private void lookupName(String cmd, InputStream ins, OutputStream outs) throws IOException { ObjectInputStream in = new ObjectInputStream(ins); String name = DataInputStream.readUTF(in); ExportedObject found = exportedNames.get(name); outs.write(okHeader); ObjectOutputStream out = new ObjectOutputStream(outs); if (found == null) {
[ " logging2(name + \"not found.\");" ]
745
lcc
java
null
42eff230c4b79230f8b478baf6961fc54e1bad443af197c3
/* * ported to v0.37b7 * using automatic conversion tool v0.01 */ package vidhrdw; import static arcadeflex.fucPtr.*; import static arcadeflex.libc_v2.*; import static old.mame.drawgfx.*; import static old.mame.drawgfxH.TRANSPARENCY_NONE; import static mame.mame.Machine; import static mame.osdependH.osd_bitmap; import static old.mame.common.*; import static mame.common.*; import static sound.samples.*; import static mame.mame.*; import static old.mame.drawgfxH.TRANSPARENCY_COLOR; import static old.mame.drawgfxH.TRANSPARENCY_PEN; import old.mame.drawgfxH.rectangle; import static machine.stactics.*; import static old.vidhrdw.generic.*; import static arcadeflex.libc.memset.*; import static mame.commonH.REGION_GFX1; import static mame.drawgfx.decodechar; public class stactics { /* These are needed by machine/stactics.c */ public static int stactics_vblank_count; public static int stactics_shot_standby; public static int stactics_shot_arrive; /* These are needed by driver/stactics.c */ public static UBytePtr stactics_scroll_ram = new UBytePtr(); public static UBytePtr stactics_videoram_b = new UBytePtr(); public static UBytePtr stactics_chardata_b = new UBytePtr(); public static UBytePtr stactics_videoram_d = new UBytePtr(); public static UBytePtr stactics_chardata_d = new UBytePtr(); public static UBytePtr stactics_videoram_e = new UBytePtr(); public static UBytePtr stactics_chardata_e = new UBytePtr(); public static UBytePtr stactics_videoram_f = new UBytePtr(); public static UBytePtr stactics_chardata_f = new UBytePtr(); public static UBytePtr stactics_display_buffer = new UBytePtr(); public static char[] dirty_videoram_b; public static char[] dirty_chardata_b; public static char[] dirty_videoram_d; public static char[] dirty_chardata_d; public static char[] dirty_videoram_e; public static char[] dirty_chardata_e; public static char[] dirty_videoram_f; public static char[] dirty_chardata_f; public static int d_offset; public static int e_offset; public static int f_offset; static int palette_select; static osd_bitmap tmpbitmap2; static osd_bitmap bitmap_B; static osd_bitmap bitmap_D; static osd_bitmap bitmap_E; static osd_bitmap bitmap_F; static UBytePtr beamdata; static int states_per_frame; public static int DIRTY_CHARDATA_SIZE = 0x100; public static int BEAMDATA_SIZE = 0x800; /* The first 16 came from the 7448 BCD to 7-segment decoder data sheet */ /* The rest are made up */ static char stactics_special_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space */ 0x80, 0x80, 0x80, 0xf0, 0x80, 0x80, 0xf0, 0x00, /* extras... */ 0xf0, 0x80, 0x80, 0xf0, 0x00, 0x00, 0xf0, 0x00, /* extras... */ 0x90, 0x90, 0x90, 0xf0, 0x00, 0x00, 0x00, 0x00, /* extras... */ 0x00, 0x00, 0x00, 0xf0, 0x10, 0x10, 0xf0, 0x00, /* extras... */ 0x00, 0x00, 0x00, 0xf0, 0x80, 0x80, 0xf0, 0x00, /* extras... */ 0xf0, 0x90, 0x90, 0xf0, 0x10, 0x10, 0xf0, 0x00, /* 9 */ 0xf0, 0x90, 0x90, 0xf0, 0x90, 0x90, 0xf0, 0x00, /* 8 */ 0xf0, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, /* 7 */ 0xf0, 0x80, 0x80, 0xf0, 0x90, 0x90, 0xf0, 0x00, /* 6 */ 0xf0, 0x80, 0x80, 0xf0, 0x10, 0x10, 0xf0, 0x00, /* 5 */ 0x90, 0x90, 0x90, 0xf0, 0x10, 0x10, 0x10, 0x00, /* 4 */ 0xf0, 0x10, 0x10, 0xf0, 0x10, 0x10, 0xf0, 0x00, /* 3 */ 0xf0, 0x10, 0x10, 0xf0, 0x80, 0x80, 0xf0, 0x00, /* 2 */ 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, /* 1 */ 0xf0, 0x90, 0x90, 0x90, 0x90, 0x90, 0xf0, 0x00, /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space */ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1 pip */ 0x60, 0x90, 0x80, 0x60, 0x10, 0x90, 0x60, 0x00, /* S for Score */ 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 pips */ 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, /* 3 pips */ 0x60, 0x90, 0x80, 0x80, 0x80, 0x90, 0x60, 0x00, /* C for Credits */ 0xe0, 0x90, 0x90, 0xe0, 0x90, 0x90, 0xe0, 0x00, /* B for Barriers */ 0xe0, 0x90, 0x90, 0xe0, 0xc0, 0xa0, 0x90, 0x00, /* R for Rounds */ 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, /* 4 pips */ 0x00, 0x60, 0x60, 0x00, 0x60, 0x60, 0x00, 0x00, /* Colon */ 0x40, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, /* Sight */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space (Unused) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space (Unused) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space (Unused) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Space (Unused) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* Space */}; static int firebeam_state; static int old_firebeam_state; public static VhConvertColorPromPtr stactics_vh_convert_color_prom = new VhConvertColorPromPtr() { public void handler(char[] palette, char[] colortable, UBytePtr color_prom) { int i, j; /* Now make the palette */ int p_ptr = 0; for (i = 0; i < 16; i++) { int bit0, bit1, bit2, bit3; bit0 = i & 1; bit1 = (i >> 1) & 1; bit2 = (i >> 2) & 1; bit3 = (i >> 3) & 1; /* red component */ palette[p_ptr++] = (char) (0xff * bit0); /* green component */ palette[p_ptr++] = (char) (0xff * bit1 - 0xcc * bit3); /* blue component */ palette[p_ptr++] = (char) (0xff * bit2); } /* The color prom in Space Tactics is used for both */ /* color codes, and priority layering of the 4 layers */ /* Since we are taking care of the layering by our */ /* drawing order, we don't need all of the color prom */ /* entries */ /* For each of 4 color schemes */ int c_ptr = 0; for (i = 0; i < 4; i++) { /* For page B - Alphanumerics and alien shots */ for (j = 0; j < 16; j++) { colortable[c_ptr++] = (0); colortable[c_ptr++] = color_prom.read(i * 0x100 + 0x01 * 0x10 + j); } /* For page F - Close Aliens (these are all the same color) */ for (j = 0; j < 16; j++) { colortable[c_ptr++] = 0; colortable[c_ptr++] = color_prom.read(i * 0x100 + 0x02 * 0x10); } /* For page E - Medium Aliens (these are all the same color) */ for (j = 0; j < 16; j++) { colortable[c_ptr++] = 0; colortable[c_ptr++] = color_prom.read(i * 0x100 + 0x04 * 0x10 + j); } /* For page D - Far Aliens (these are all the same color) */ for (j = 0; j < 16; j++) { colortable[c_ptr++] = 0; colortable[c_ptr++] = color_prom.read(i * 0x100 + 0x08 * 0x10 + j); } } } }; /** * ************************************************************************* * * Start the video hardware emulation. * ************************************************************************** */ public static VhStartPtr stactics_vh_start = new VhStartPtr() { public int handler() { int i, j; UBytePtr firebeam_data; char[] firechar = new char[256 * 8 * 9]; if ((tmpbitmap = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } if ((tmpbitmap2 = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } if ((bitmap_B = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } if ((bitmap_D = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } if ((bitmap_E = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } if ((bitmap_F = bitmap_alloc(Machine.drv.screen_width, Machine.drv.screen_height)) == null) { return 1; } /* Allocate dirty buffers */ if ((dirty_videoram_b = new char[videoram_size[0]]) == null) { return 1; } if ((dirty_videoram_d = new char[videoram_size[0]]) == null) { return 1; } if ((dirty_videoram_e = new char[videoram_size[0]]) == null) { return 1; } if ((dirty_videoram_f = new char[videoram_size[0]]) == null) { return 1; } if ((dirty_chardata_b = new char[DIRTY_CHARDATA_SIZE]) == null) { return 1; } if ((dirty_chardata_d = new char[DIRTY_CHARDATA_SIZE]) == null) { return 1; } if ((dirty_chardata_e = new char[DIRTY_CHARDATA_SIZE]) == null) { return 1; } if ((dirty_chardata_f = new char[DIRTY_CHARDATA_SIZE]) == null) { return 1; } memset(dirty_videoram_b, 1, videoram_size[0]); memset(dirty_videoram_d, 1, videoram_size[0]); memset(dirty_videoram_e, 1, videoram_size[0]); memset(dirty_videoram_f, 1, videoram_size[0]); memset(dirty_chardata_b, 1, DIRTY_CHARDATA_SIZE); memset(dirty_chardata_d, 1, DIRTY_CHARDATA_SIZE); memset(dirty_chardata_e, 1, DIRTY_CHARDATA_SIZE); memset(dirty_chardata_f, 1, DIRTY_CHARDATA_SIZE); d_offset = 0; e_offset = 0; f_offset = 0; palette_select = 0; stactics_vblank_count = 0; stactics_shot_standby = 1; stactics_shot_arrive = 0; firebeam_state = 0; old_firebeam_state = 0; /* Create a fake character set for LED fire beam */ memset(firechar, 0, sizeof(firechar)); for (i = 0; i < 256; i++) { for (j = 0; j < 8; j++) { if (((i >> j) & 0x01) != 0) { firechar[i * 9 + (7 - j)] |= (0x01 << (7 - j)); firechar[i * 9 + (7 - j) + 1] |= (0x01 << (7 - j)); } } } for (i = 0; i < 256; i++) { decodechar(Machine.gfx[4], i, new UBytePtr(firechar), Machine.drv.gfxdecodeinfo[4].gfxlayout); } /* Decode the Fire Beam ROM for later */ /* (I am basically just juggling the bytes */ /* and storing it again to make it easier) */ if ((beamdata = new UBytePtr(BEAMDATA_SIZE)) == null) { return 1; } firebeam_data = memory_region(REGION_GFX1); for (i = 0; i < 256; i++) { beamdata.write(i * 8, firebeam_data.read(i)); beamdata.write(i * 8 + 1, firebeam_data.read(i + 1024)); beamdata.write(i * 8 + 2, firebeam_data.read(i + 256)); beamdata.write(i * 8 + 3, firebeam_data.read(i + 1024 + 256)); beamdata.write(i * 8 + 4, firebeam_data.read(i + 512)); beamdata.write(i * 8 + 5, firebeam_data.read(i + 1024 + 512)); beamdata.write(i * 8 + 6, firebeam_data.read(i + 512 + 256)); beamdata.write(i * 8 + 7, firebeam_data.read(i + 1024 + 512 + 256)); } /* Build some characters for simulating the LED displays */ for (i = 0; i < 32; i++) { decodechar(Machine.gfx[5], i, new UBytePtr(stactics_special_chars), Machine.drv.gfxdecodeinfo[5].gfxlayout); } stactics_vblank_count = 0; stactics_vert_pos = 0; stactics_horiz_pos = 0; stactics_motor_on.write(0); return 0; } }; /** * ************************************************************************* * * Stop the video hardware emulation. * ************************************************************************** */ public static VhStopPtr stactics_vh_stop = new VhStopPtr() { public void handler() { dirty_videoram_b = null; dirty_videoram_d = null; dirty_videoram_e = null; dirty_videoram_f = null; dirty_chardata_b = null; dirty_chardata_d = null; dirty_chardata_e = null; dirty_chardata_f = null; beamdata = null; bitmap_free(tmpbitmap); bitmap_free(tmpbitmap2); bitmap_free(bitmap_B); bitmap_free(bitmap_D); bitmap_free(bitmap_E); bitmap_free(bitmap_F); } }; public static WriteHandlerPtr stactics_palette_w = new WriteHandlerPtr() { public void handler(int offset, int data) { int old_palette_select = palette_select; switch (offset) { case 0: palette_select = (palette_select & 0x02) | (data & 0x01); break; case 1: palette_select = (palette_select & 0x01) | ((data & 0x01) << 1); break; default: return; } if (old_palette_select != palette_select) { memset(dirty_videoram_b, 1, videoram_size[0]); memset(dirty_videoram_d, 1, videoram_size[0]); memset(dirty_videoram_e, 1, videoram_size[0]); memset(dirty_videoram_f, 1, videoram_size[0]); } return; } }; public static WriteHandlerPtr stactics_scroll_ram_w = new WriteHandlerPtr() { public void handler(int offset, int data) { int temp; if (stactics_scroll_ram.read(offset) != data) { stactics_scroll_ram.write(offset, data); temp = (offset & 0x700) >> 8; switch (temp) { case 4: // Page D { if ((data & 0x01) != 0) { d_offset = offset & 0xff; } break; } case 5: // Page E { if ((data & 0x01) != 0) { e_offset = offset & 0xff; } break; } case 6: // Page F { if ((data & 0x01) != 0) { f_offset = offset & 0xff; } break; } } } } }; public static WriteHandlerPtr stactics_speed_latch_w = new WriteHandlerPtr() { public void handler(int offset, int data) { /* This writes to a shift register which is clocked by */ /* a 555 oscillator. This value determines the speed of */ /* the LED fire beams as follows: */ /* 555_freq / bits_in_SR * edges_in_SR / states_in_PR67 / frame_rate */ /* = num_led_states_per_frame */ /* 36439 / 8 * x / 32 / 60 ~= 19/8*x */ /* Here, we will count the number of rising edges in the shift register */ int i; int num_rising_edges = 0; for (i = 0; i < 8; i++) { if ((((data >> i) & 0x01) == 1) && (((data >> ((i + 1) % 8)) & 0x01) == 0)) { num_rising_edges++; } } states_per_frame = num_rising_edges * 19 / 8; } }; public static WriteHandlerPtr stactics_shot_trigger_w = new WriteHandlerPtr() { public void handler(int offset, int data) { stactics_shot_standby = 0; } }; public static WriteHandlerPtr stactics_shot_flag_clear_w = new WriteHandlerPtr() { public void handler(int offset, int data) { stactics_shot_arrive = 0; } }; public static WriteHandlerPtr stactics_videoram_b_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_videoram_b.read(offset) != data) { stactics_videoram_b.write(offset, data); dirty_videoram_b[offset] = 1; } } }; public static WriteHandlerPtr stactics_chardata_b_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_chardata_b.read(offset) != data) { stactics_chardata_b.write(offset, data); dirty_chardata_b[offset >> 3] = 1; } } }; public static WriteHandlerPtr stactics_videoram_d_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_videoram_d.read(offset) != data) { stactics_videoram_d.write(offset, data); dirty_videoram_d[offset] = 1; } } }; public static WriteHandlerPtr stactics_chardata_d_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_chardata_d.read(offset) != data) { stactics_chardata_d.write(offset, data); dirty_chardata_d[offset >> 3] = 1; } } }; public static WriteHandlerPtr stactics_videoram_e_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_videoram_e.read(offset) != data) { stactics_videoram_e.write(offset, data); dirty_videoram_e[offset] = 1; } } }; public static WriteHandlerPtr stactics_chardata_e_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_chardata_e.read(offset) != data) { stactics_chardata_e.write(offset, data); dirty_chardata_e[offset >> 3] = 1; } } }; public static WriteHandlerPtr stactics_videoram_f_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_videoram_f.read(offset) != data) { stactics_videoram_f.write(offset, data); dirty_videoram_f[offset] = 1; } } }; public static WriteHandlerPtr stactics_chardata_f_w = new WriteHandlerPtr() { public void handler(int offset, int data) { if (stactics_chardata_f.read(offset) != data) { stactics_chardata_f.write(offset, data); dirty_chardata_f[offset >> 3] = 1; } } }; /* Actual area for visible monitor stuff is only 30*8 lines */ /* The rest is used for the score, etc. */ static rectangle visible_screen_area = new rectangle(0 * 8, 32 * 8, 0 * 8, 30 * 8); /** * ************************************************************************* * * Draw the game screen in the given osd_bitmap. Do NOT call * osd_update_display() from this function, it will be called by the main * emulation engine. * ************************************************************************** */ public static VhUpdatePtr stactics_vh_screenrefresh = new VhUpdatePtr() { public void handler(osd_bitmap bitmap, int full_refresh) { int offs, sx, sy, i; int char_number; int color_code; int pixel_x, pixel_y; int palette_offset = palette_select * 64; for (offs = 0x400 - 1; offs >= 0; offs--) { sx = offs % 32; sy = offs / 32; color_code = palette_offset + (stactics_videoram_b.read(offs) >> 4); /* Draw aliens in Page D */ char_number = stactics_videoram_d.read(offs); if (dirty_chardata_d[char_number] == 1) { decodechar(Machine.gfx[3], char_number, stactics_chardata_d, Machine.drv.gfxdecodeinfo[3].gfxlayout); dirty_chardata_d[char_number] = 2; dirty_videoram_d[offs] = 1; } else if (dirty_chardata_d[char_number] == 2) { dirty_videoram_d[offs] = 1; } if (dirty_videoram_d[offs] != 0) { drawgfx(bitmap_D, Machine.gfx[3], char_number, color_code, 0, 0, sx * 8, sy * 8, Machine.visible_area, TRANSPARENCY_NONE, 0); dirty_videoram_d[offs] = 0; } /* Draw aliens in Page E */ char_number = stactics_videoram_e.read(offs); if (dirty_chardata_e[char_number] == 1) { decodechar(Machine.gfx[2], char_number, stactics_chardata_e, Machine.drv.gfxdecodeinfo[2].gfxlayout); dirty_chardata_e[char_number] = 2; dirty_videoram_e[offs] = 1; } else if (dirty_chardata_e[char_number] == 2) { dirty_videoram_e[offs] = 1; } if (dirty_videoram_e[offs] != 0) { drawgfx(bitmap_E, Machine.gfx[2], char_number, color_code, 0, 0, sx * 8, sy * 8, Machine.visible_area, TRANSPARENCY_NONE, 0); dirty_videoram_e[offs] = 0; } /* Draw aliens in Page F */ char_number = stactics_videoram_f.read(offs); if (dirty_chardata_f[char_number] == 1) { decodechar(Machine.gfx[1], char_number, stactics_chardata_f, Machine.drv.gfxdecodeinfo[1].gfxlayout); dirty_chardata_f[char_number] = 2; dirty_videoram_f[offs] = 1; } else if (dirty_chardata_f[char_number] == 2) { dirty_videoram_f[offs] = 1; } if (dirty_videoram_f[offs] != 0) { drawgfx(bitmap_F, Machine.gfx[1], char_number, color_code, 0, 0, sx * 8, sy * 8, Machine.visible_area, TRANSPARENCY_NONE, 0); dirty_videoram_f[offs] = 0; } /* Draw the page B stuff */ char_number = stactics_videoram_b.read(offs); if (dirty_chardata_b[char_number] == 1) { decodechar(Machine.gfx[0], char_number, stactics_chardata_b, Machine.drv.gfxdecodeinfo[0].gfxlayout); dirty_chardata_b[char_number] = 2; dirty_videoram_b[offs] = 1; } else if (dirty_chardata_b[char_number] == 2) { dirty_videoram_b[offs] = 1; } if (dirty_videoram_b[offs] != 0) { drawgfx(bitmap_B, Machine.gfx[0], char_number, color_code, 0, 0, sx * 8, sy * 8, Machine.visible_area, TRANSPARENCY_NONE, 0); dirty_videoram_b[offs] = 0; } } /* Now, composite the four layers together */ copyscrollbitmap(tmpbitmap2, bitmap_D, 0, null, 1, new int[]{d_offset}, Machine.visible_area, TRANSPARENCY_NONE, 0); copyscrollbitmap(tmpbitmap2, bitmap_E, 0, null, 1, new int[]{e_offset}, Machine.visible_area, TRANSPARENCY_COLOR, 0); copyscrollbitmap(tmpbitmap2, bitmap_F, 0, null, 1, new int[]{f_offset}, Machine.visible_area, TRANSPARENCY_COLOR, 0); copybitmap(tmpbitmap2, bitmap_B, 0, 0, 0, 0, Machine.visible_area, TRANSPARENCY_COLOR, 0); /* Now flip X & simulate the monitor motion */ fillbitmap(bitmap, Machine.pens[0], Machine.visible_area); copybitmap(bitmap, tmpbitmap2, 1, 0, stactics_horiz_pos, stactics_vert_pos, visible_screen_area, TRANSPARENCY_NONE, 0); /* Finally, draw stuff that is on the console or on top of the monitor (LED's) */ /** * *** Draw Score Display **** */ pixel_x = 16; pixel_y = 248; /* Draw an S */ drawgfx(bitmap, Machine.gfx[5], 18, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw a colon */ drawgfx(bitmap, Machine.gfx[5], 25, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw the digits */ for (i = 1; i < 7; i++) { drawgfx(bitmap, Machine.gfx[5], stactics_display_buffer.read(i) & 0x0f, 16, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; } /** * *** Draw Credits Indicator **** */ pixel_x = 64 + 16; /* Draw a C */ drawgfx(bitmap, Machine.gfx[5], 21, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw a colon */ drawgfx(bitmap, Machine.gfx[5], 25, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw the pips */ for (i = 7; i < 9; i++) { drawgfx(bitmap, Machine.gfx[5], 16 + (~stactics_display_buffer.read(i) & 0x0f), 16, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 2; } /** * *** Draw Rounds Indicator **** */ pixel_x = 128 + 16; /* Draw an R */ drawgfx(bitmap, Machine.gfx[5], 22, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw a colon */ drawgfx(bitmap, Machine.gfx[5], 25, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw the pips */ for (i = 9; i < 12; i++) { drawgfx(bitmap, Machine.gfx[5], 16 + (~stactics_display_buffer.read(i) & 0x0f), 16, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 2; } /** * *** Draw Barriers Indicator **** */ pixel_x = 192 + 16; /* Draw a B */ drawgfx(bitmap, Machine.gfx[5], 23, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw a colon */ drawgfx(bitmap, Machine.gfx[5], 25, 0, 0, 0, pixel_x, pixel_y, Machine.visible_area, TRANSPARENCY_NONE, 0); pixel_x += 6; /* Draw the pips */ for (i = 12; i < 16; i++) { drawgfx(bitmap, Machine.gfx[5],
[ " 16 + (~stactics_display_buffer.read(i) & 0x0f)," ]
2,896
lcc
java
null
8d3d0541e92abe43d18a21fd5943d0fee67278670fbf48d8
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Windows.Forms; using SharpDX; using LeagueSharp; using LeagueSharp.Common; using EloBuddy; using LeagueSharp.Common; namespace BadaoSeries.CustomOrbwalker { public static class BadaoPrediction { private static int _wallCastT; private static Vector2 _yasuoWallCastedPos; static BadaoPrediction() { Obj_AI_Base.OnSpellCast += AIHeroClient_OnProcessSpellCast; } private static void AIHeroClient_OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender.IsValid && sender.Team != ObjectManager.Player.Team && args.SData.Name == "YasuoWMovingWall") { _wallCastT = Utils.TickCount; _yasuoWallCastedPos = sender.ServerPosition.To2D(); } } public class PredictionInput { private Vector3 _from; private Vector3 _rangeCheckFrom; /// <summary> /// Set to true make the prediction hit as many enemy heroes as posible. /// </summary> public bool Aoe = false; /// <summary> /// Set to true if the unit collides with units. /// </summary> public bool Collision = false; /// <summary> /// Array that contains the unit types that the skillshot can collide with. /// </summary> public CollisionableObjects[] CollisionObjects = { CollisionableObjects.Minions, CollisionableObjects.YasuoWall }; /// <summary> /// The skillshot delay in seconds. /// </summary> public float Delay; /// <summary> /// The skillshot width's radius or the angle in case of the cone skillshots. /// </summary> public float Radius = 1f; /// <summary> /// The skillshot range in units. /// </summary> public float Range = float.MaxValue; /// <summary> /// The skillshot speed in units per second. /// </summary> public float Speed = float.MaxValue; /// <summary> /// The skillshot type. /// </summary> public SkillshotType Type = SkillshotType.SkillshotLine; /// <summary> /// The unit that the prediction will made for. /// </summary> public Obj_AI_Base Unit = ObjectManager.Player; /// <summary> /// Set to true to increase the prediction radius by the unit bounding radius. /// </summary> public bool UseBoundingRadius = true; /// <summary> /// The position from where the skillshot missile gets fired. /// </summary> public Vector3 From { get { return _from.To2D().IsValid() ? _from : ObjectManager.Player.ServerPosition; } set { _from = value; } } /// <summary> /// The position from where the range is checked. /// </summary> public Vector3 RangeCheckFrom { get { return _rangeCheckFrom.To2D().IsValid() ? _rangeCheckFrom : (From.To2D().IsValid() ? From : ObjectManager.Player.ServerPosition); } set { _rangeCheckFrom = value; } } internal float RealRadius { get { return Radius; } } } public class PredictionOutput { internal int _aoeTargetsHitCount; private Vector3 _castPosition; private Vector3 _unitPosition; /// <summary> /// The list of the targets that the spell will hit (only if aoe was enabled). /// </summary> public List<AIHeroClient> AoeTargetsHit = new List<AIHeroClient>(); /// <summary> /// The list of the units that the skillshot will collide with. /// </summary> public List<Obj_AI_Base> CollisionObjects = new List<Obj_AI_Base>(); /// <summary> /// Returns the hitchance. /// </summary> public HitChance Hitchance = HitChance.Impossible; internal PredictionInput Input; /// <summary> /// The position where the skillshot should be casted to increase the accuracy. /// </summary> public Vector3 CastPosition { get { return _castPosition.IsValid() && _castPosition.To2D().IsValid() ? _castPosition.SetZ() : Input.Unit.ServerPosition; } set { _castPosition = value; } } /// <summary> /// The number of targets the skillshot will hit (only if aoe was enabled). /// </summary> //public int AoeTargetsHitCount //{ // get { return Math.Max(_aoeTargetsHitCount, AoeTargetsHit.Count); } //} /// <summary> /// The position where the unit is going to be when the skillshot reaches his position. /// </summary> public Vector3 UnitPosition { get { return _unitPosition.To2D().IsValid() ? _unitPosition.SetZ() : Input.Unit.ServerPosition; } set { _unitPosition = value; } } } //public static bool BadaoCast2(this Spell spell, Obj_AI_Base target) //{ // var prediction = spell.GetBadao2Prediction(target); // if (!spell.IsSkillshot) // return false; // //if (prediction.Hitchance < spell.MinHitChance) // // return false; // return ObjectManager.Player.Spellbook.CastSpell(spell.Slot, prediction); //} //public static Vector3 GetBadao2Prediction(this Spell spell, Obj_AI_Base target) //{ // Vector3 chuot = Prediction.GetPrediction(target, 1).UnitPosition; // float dis = spell.From.Distance(target.Position); // float rad = target.BoundingRadius + spell.Width - 50; // double x = math.t(target.MoveSpeed, spell.Speed, dis, spell.Delay + Game.Ping / 2 / 1000, rad, spell.From.To2D(), target.Position.To2D(), chuot.To2D()); // if (x != 0 && !target.IsDashing()) { return target.Position.Extend(chuot, (float)x * target.MoveSpeed - rad); } // else return target.Position; //} public static bool BadaoCast(this Spell spell, Obj_AI_Base target) { var prediction = spell.GetBadaoPrediction(target); if (!spell.IsSkillshot) return false; if (prediction.Hitchance < spell.MinHitChance) return false; return ObjectManager.Player.Spellbook.CastSpell(spell.Slot, prediction.CastPosition); } public static PredictionOutput GetBadaoPrediction(this Spell spell, Obj_AI_Base target, bool collideyasuowall = true) { PredictionOutput result = null; if (!target.IsValidTarget(float.MaxValue, false)) { return new PredictionOutput(); } if (target.IsDashing()) { var dashDtata = target.GetDashInfo(); result = spell.GetBadaoStandarPrediction(target, new List<Vector2>() {target.ServerPosition.To2D(), dashDtata.Path.Last()},dashDtata.Speed); if (result.Hitchance >= HitChance.High) result.Hitchance = HitChance.Dashing; } else { //Unit is immobile. var remainingImmobileT = UnitIsImmobileUntil(target); if (remainingImmobileT >= 0d) { var timeToReachTargetPosition = spell.Delay + target.Position.To2D().Distance(spell.From.To2D()) / spell.Speed; if (spell.RangeCheckFrom.To2D().Distance(target.Position.To2D()) <= spell.Range) { if (timeToReachTargetPosition <= remainingImmobileT + (target.BoundingRadius + spell.Width - 40)/target.MoveSpeed) { result = new PredictionOutput { CastPosition = target.ServerPosition, UnitPosition = target.ServerPosition, Hitchance = HitChance.Immobile }; } else result = new PredictionOutput { CastPosition = target.ServerPosition, UnitPosition = target.ServerPosition, Hitchance = HitChance.High /*timeToReachTargetPosition - remainingImmobileT + input.RealRadius / input.Unit.MoveSpeed < 0.4d ? HitChance.High : HitChance.Medium*/ }; } else { result = new PredictionOutput(); } } } //Normal prediction if (result == null) { result = spell.GetBadaoStandarPrediction(target,target.Path.ToList().To2D()); } //Check for collision if (spell.Collision) { var positions = new List<Vector3> { result.UnitPosition, result.CastPosition, target.Position }; var originalUnit = target; result.CollisionObjects = spell.GetCollision(positions); result.CollisionObjects.RemoveAll(x => x.NetworkId == originalUnit.NetworkId); result.Hitchance = result.CollisionObjects.Count > 0 ? HitChance.Collision : result.Hitchance; } //Check yasuo wall collision else if (collideyasuowall) { var positions = new List<Vector3> { result.UnitPosition, result.CastPosition, target.Position }; var originalUnit = target; result.CollisionObjects = spell.GetCollision(positions); result.CollisionObjects.Any(x => x.NetworkId == ObjectManager.Player.NetworkId); result.Hitchance = result.CollisionObjects.Any(x => x.NetworkId == ObjectManager.Player.NetworkId) ? HitChance.Collision : result.Hitchance; } return result; } public static PredictionOutput GetBadaoStandarPrediction(this Spell spell, Obj_AI_Base target, List<Vector2> path, float speed = -1) { // check the unit speed input speed = (Math.Abs(speed - (-1)) < float.Epsilon) ? target.MoveSpeed : speed; // set standar output Vector2 castpos = target.ServerPosition.To2D(); Vector2 unitpos = target.ServerPosition.To2D(); HitChance hitchance = HitChance.Impossible; // target standing like a statue (performing an attack, casting spell, afk, aimbush.....) if (path.Count <= 1) { // set standar position castpos = target.ServerPosition.To2D(); unitpos = target.ServerPosition.To2D(); // target in range if (spell.RangeCheckFrom.To2D().Distance(castpos) <= spell.Range) hitchance = HitChance.High; // target out of range else { // skill shot circle if (spell.Type == SkillshotType.SkillshotCircle) { // check for extra radius if (spell.RangeCheckFrom.To2D().Distance(castpos) <= spell.Range + spell.Width + target.BoundingRadius - 40) { castpos = spell.RangeCheckFrom.To2D().Extend(castpos, spell.Range); hitchance = HitChance.Medium; } else { castpos = spell.RangeCheckFrom.To2D().Extend(castpos, spell.Range); hitchance = HitChance.OutOfRange; } } else hitchance = HitChance.OutOfRange; } return new PredictionOutput() { UnitPosition = unitpos.To3D(), CastPosition = castpos.To3D(), Hitchance = hitchance }; } //Skillshots with only a delay if (Math.Abs(spell.Speed - float.MaxValue) < float.Epsilon && path.Count >= 2) { var a = path[0]; var b = path[1]; var distance = a.Distance(b); // skillshot circle if (spell.Type == SkillshotType.SkillshotCircle) { //standar distance var x = speed*(spell.Delay + Game.Ping/2000f + 0.06f); // position 1 properties var distance01 = x - (target.BoundingRadius + spell.Width)/2; var pos01 = a.Extend(b, distance01); // position 2 properties var distance02 = x; var pos02 = a.Extend(b, distance02); // position 3 properties var distance03 = x + (target.BoundingRadius + spell.Width)/2; var pos03 = pos02.Extend(spell.From.To2D(), distance03); // lines length var length01 = pos01.Distance(pos02); var length02 = pos02.Distance(pos03); // set standar position unitpos = pos02; castpos = pos02; // list cast poses List<Vector2> poses = new List<Vector2>(); for (int i = 0; i <= 10; i++) { poses.Add(i <= 5 ? pos01.Extend(pos02, i*length01/6) : pos02.Extend(pos03, (i - 5)*length02/5)); } // check cast pos for (int i = 0; i <= 10; i++) { if (poses[i].Distance(spell.RangeCheckFrom.To2D()) <= spell.Range && poses[i].Distance(a) <= distance) { if (i <= 3) { hitchance = HitChance.VeryHigh; } else if (i <= 6) { hitchance = HitChance.High; } else hitchance = HitChance.Medium; return new PredictionOutput { UnitPosition = unitpos.To3D(), CastPosition = poses[i].To3D(), Hitchance = hitchance }; } } // hitchance out of range return new PredictionOutput { UnitPosition = unitpos.To3D(), CastPosition = castpos.To3D(), Hitchance = HitChance.OutOfRange }; } // skill shot line and cone else { //standar distance var x = speed*(spell.Delay + Game.Ping/2000f + 0.06f); // position properties var distance01 = x; var pos01 = a.Extend(b, distance01); var range01 = spell.RangeCheckFrom.To2D().Distance(pos01); // set standar position unitpos = pos01; castpos = pos01; // hitchance high if (distance01 < distance && range01 <= spell.Range) { castpos = pos01; hitchance = HitChance.High; return new PredictionOutput { UnitPosition = unitpos.To3D(), CastPosition = castpos.To3D(), Hitchance = hitchance }; } // hitchance out of range return new PredictionOutput { UnitPosition = unitpos.To3D(), CastPosition = castpos.To3D(), Hitchance = HitChance.OutOfRange }; } } // skill shot with a delay and speed if (Math.Abs(spell.Speed - float.MaxValue) > float.Epsilon) { var a = path[0]; var b = path[1]; var distance = a.Distance(b); // standar prediction float dis = spell.From.To2D().Distance(a); float rad = 0; double time = math.t(speed, spell.Speed, dis, spell.Delay + Game.Ping/2f/1000 + 0.06f, 0, spell.From.To2D(), a, b); var unitpos02 = !double.IsNaN(time) ? a.Extend(b, (float) time*speed) : new Vector2(); var castpos02 = unitpos02; // very high prediction rad = (target.BoundingRadius + spell.Width)/2; time = math.t(target.MoveSpeed, spell.Speed, dis, spell.Delay + Game.Ping/2f/1000 + 0.06f, rad, spell.From.To2D(), a, b); var unitpos01 = !double.IsNaN(time) ? a.Extend(b, (float) time*speed- rad) : new Vector2(); var castpos01 = unitpos01; // medium prediction time = math.t(target.MoveSpeed, spell.Speed, dis, spell.Delay + Game.Ping/2f/1000 + 0.06f -rad/spell.Speed, 0, spell.From.To2D(), a, b); var unitpos03 = !double.IsNaN(time) ? a.Extend(b, (float) time*speed) : new Vector2(); var castpos03 = unitpos03.IsValid() ? spell.From.To2D().Extend(unitpos03, spell.From.To2D().Distance(unitpos03) - rad) : new Vector2(); if (castpos01.IsValid() && castpos02.IsValid() && castpos03.IsValid()) { var length01 = castpos01.Distance(castpos02); var length02 = castpos02.Distance(castpos03); var Acosb = Math.Acos( Math.Abs(float.IsNaN(math.CosB(spell.From.To2D(), a, b)) ? 0.99f : Math.Abs(math.CosB(spell.From.To2D(), a, b))))*(180/Math.PI); // skillshot circle + line if (spell.Type == SkillshotType.SkillshotCircle || (spell.Type == SkillshotType.SkillshotLine && Acosb <= 110 && Acosb >= 70)) { List<Vector2> poses = new List<Vector2>(); for (int i = 0; i <= 10; i++) { poses.Add(i <= 5 ? castpos01.Extend(castpos02, i*length01/6) : castpos02.Extend(castpos03, (i - 5)*length02/5)); } // check cast pos for (int i = 0; i <= 10; i++) { if (poses[i].Distance(spell.RangeCheckFrom.To2D()) <= spell.Range && poses[i].Distance(a) <= distance) { if (i <= 3) { hitchance = HitChance.VeryHigh; } else if (i <= 6) { hitchance = HitChance.High; } else hitchance = HitChance.Medium; return new PredictionOutput { UnitPosition = unitpos02.To3D(), CastPosition = poses[i].To3D(), Hitchance = hitchance }; } } // hitchance out of range return new PredictionOutput { UnitPosition = unitpos02.To3D(), CastPosition = castpos02.To3D(), Hitchance = HitChance.OutOfRange }; } // skillshot line + cone else { var distance02 = a.Distance(castpos02); var range01 = spell.RangeCheckFrom.To2D().Distance(castpos02); // hitchance high if (distance02 < distance && range01 <= spell.Range) { return new PredictionOutput { UnitPosition = unitpos02.To3D(), CastPosition = castpos02.To3D(), Hitchance = HitChance.High }; } // hitchance out of range return new PredictionOutput { UnitPosition = unitpos02.To3D(), CastPosition = castpos02.To3D(), Hitchance = HitChance.OutOfRange }; } } } return new PredictionOutput { UnitPosition = unitpos.To3D(), CastPosition = castpos.To3D(), Hitchance = hitchance }; } internal static double UnitIsImmobileUntil(Obj_AI_Base unit) { var result = unit.Buffs.Where( buff => buff.IsActive && Game.Time <= buff.EndTime && (buff.Type == BuffType.Charm || buff.Type == BuffType.Knockup || buff.Type == BuffType.Stun || buff.Type == BuffType.Suppression || buff.Type == BuffType.Snare)) .Aggregate(0d, (current, buff) => Math.Max(current, buff.EndTime)); return (result - Game.Time); } public static List<Obj_AI_Base> GetCollision(this Spell spell, List<Vector3> positions) { var objects = new List<CollisionableObjects>(){CollisionableObjects.YasuoWall,CollisionableObjects.Minions, CollisionableObjects.Heroes}; var result = new List<Obj_AI_Base>(); foreach (var position in positions) { foreach (var objectType in objects) { switch (objectType) { case CollisionableObjects.Minions: foreach (var minion in ObjectManager.Get<Obj_AI_Minion>() .Where( minion => minion.IsValidTarget( Math.Min(spell.Range + spell.Width + 100, 2000), true, spell.RangeCheckFrom))) { var target = minion; var minionPrediction = spell.GetBadaoStandarPrediction(target,target.Path.ToList().To2D()); if ( minionPrediction.UnitPosition.To2D()
[ " .Distance(spell.From.To2D(), position.To2D(), true, true) <=" ]
1,895
lcc
csharp
null
fe60cba2f4bf6cfc13feac0963a3f83ff7a28080318e5bde
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.search; import edu.cmu.tetrad.data.IKnowledge; import edu.cmu.tetrad.data.Knowledge2; import edu.cmu.tetrad.graph.*; import edu.cmu.tetrad.util.TetradLogger; import java.util.*; /** * Extends Erin Korber's implementation of the Fast Causal Inference algorithm (found in FCI.java) with Jiji Zhang's * Augmented FCI rules (found in sec. 4.1 of Zhang's 2006 PhD dissertation, "Causal Inference and Reasoning in Causally * Insufficient Systems"). * <p> * This class is based off a copy of FCI.java taken from the repository on 2008/12/16, revision 7306. The extension is * done by extending doFinalOrientation() with methods for Zhang's rules R5-R10 which implements the augmented search. * (By a remark of Zhang's, the rule applications can be staged in this way.) * * @author Erin Korber, June 2004 * @author Alex Smith, December 2008 * @author Joseph Ramsey * @author Choh-Man Teng */ public final class DagToPag { private final Graph dag; // private final IndTestDSep dsep; /* * The background knowledge. */ private IKnowledge knowledge = new Knowledge2(); /** * Glag for complete rule set, true if should use complete rule set, false otherwise. */ private boolean completeRuleSetUsed = false; /** * The logger to use. */ private TetradLogger logger = TetradLogger.getInstance(); /** * True iff verbose output should be printed. */ private boolean verbose = false; private int maxPathLength = -1; private Graph truePag; //============================CONSTRUCTORS============================// /** * Constructs a new FCI search for the given independence test and background knowledge. */ public DagToPag(Graph dag) { this.dag = dag; } //========================PUBLIC METHODS==========================// public Graph convert() { if (dag == null) throw new NullPointerException(); logger.log("info", "Starting DAG to PAG."); if (verbose) { System.out.println("DAG to PAG: Starting adjacency search"); } Graph graph = calcAdjacencyGraph(); if (verbose) { System.out.println("DAG to PAG: Starting collider orientation"); } orientUnshieldedColliders2(graph, dag); if (verbose) { System.out.println("DAG to PAG: Starting final orientation"); } final FciOrient fciOrient = new FciOrient(new DagSepsets(dag)); fciOrient.setCompleteRuleSetUsed(completeRuleSetUsed); fciOrient.skipDiscriminatingPathRule(false); fciOrient.setChangeFlag(false); fciOrient.setMaxPathLength(maxPathLength); fciOrient.doFinalOrientation(graph); if (verbose) { System.out.println("Finishing final orientation"); } return graph; } private Graph calcAdjacencyGraph() { List<Node> allNodes = dag.getNodes(); List<Node> measured = new ArrayList<>(); for (Node node : allNodes) { if (node.getNodeType() == NodeType.MEASURED) { measured.add(node); } } Graph graph = new EdgeListGraphSingleConnections(measured); for (int i = 0; i < measured.size(); i++) { addAdjacencies(measured.get(i), dag, graph); } return graph; } public static Set<Node> addAdjacencies(Node x, Graph dag, Graph builtGraph) { if (x.getNodeType() != NodeType.MEASURED) throw new IllegalArgumentException(); final LinkedList<Node> path = new LinkedList<>(); path.add(x); Set<Node> induced = new HashSet<>(); for (Node b : dag.getAdjacentNodes(x)) { collectInducedNodesVisit2(dag, x, b, path, builtGraph); } return induced; } public static void collectInducedNodesVisit2(Graph dag, Node x, Node b, LinkedList<Node> path, Graph builtGraph) { if (path.contains(b)) { return; } path.addLast(b); if (b.getNodeType() == NodeType.MEASURED && path.size() >= 2) { Node y = path.getLast(); for (int i = 0; i < path.size() - 2; i++) { Node _a = path.get(i); Node _b = path.get(i + 1); Node _c = path.get(i + 2); if (_b.getNodeType() == NodeType.MEASURED) { if (!dag.isDefCollider(_a, _b, _c)) { path.removeLast(); return; } } if (dag.isDefCollider(_a, _b, _c)) { if (!(dag.isAncestorOf(_b, x) || dag.isAncestorOf(_b, y))) { path.removeLast(); return; } } } if (!builtGraph.isAdjacentTo(x, b)) { builtGraph.addEdge(Edges.nondirectedEdge(x, b)); } } for (Node c : dag.getAdjacentNodes(b)) { collectInducedNodesVisit2(dag, x, c, path, builtGraph); } path.removeLast(); } private void orientUnshieldedColliders(Graph graph, Graph dag) { graph.reorientAllWith(Endpoint.CIRCLE); List<Node> allNodes = dag.getNodes(); List<Node> measured = new ArrayList<>(); for (Node node : allNodes) { if (node.getNodeType() == NodeType.MEASURED) { measured.add(node); } } for (Node b : measured) { List<Node> adjb = graph.getAdjacentNodes(b); if (adjb.size() < 2) continue; for (int i = 0; i < adjb.size(); i++) { for (int j = i + 1; j < adjb.size(); j++) { Node a = adjb.get(i); Node c = adjb.get(j); if (graph.isDefCollider(a, b, c)) { continue; } if (graph.isAdjacentTo(a, c)) { continue; } boolean found = foundCollider(dag, a, b, c); if (found) { if (verbose) { System.out.println("Orienting collider " + a + "*->" + b + "<-*" + c); } graph.setEndpoint(a, b, Endpoint.ARROW); graph.setEndpoint(c, b, Endpoint.ARROW); } } } } } private void orientUnshieldedColliders2(Graph graph, Graph dag) { // graph.reorientAllWith(Endpoint.CIRCLE); List<Node> allNodes = dag.getNodes(); List<Node> measured = new ArrayList<>(); for (Node node : allNodes) { if (node.getNodeType() == NodeType.MEASURED) { measured.add(node); } } for (Node b : measured) { List<Node> adjb = graph.getAdjacentNodes(b); if (adjb.size() < 2) continue; for (int i = 0; i < adjb.size(); i++) { for (int j = i + 1; j < adjb.size(); j++) { Node a = adjb.get(i); Node c = adjb.get(j); // List<Node> d = new ArrayList<>(); // d.add(a); // d.add(c); // // List<Node> anc = dag.getAncestors(d); if (!graph.isAdjacentTo(a, c) && !dag.isAncestorOf(b, a) && !dag.isAncestorOf(b, c)) {// !anc.contains(b)) { // if (verbose) { // System.out.println("Orienting collider " + a + "*->" + b + "<-*" + c); // } graph.setEndpoint(a, b, Endpoint.ARROW); graph.setEndpoint(c, b, Endpoint.ARROW); } } } } } private boolean foundCollider(Graph dag, Node a, Node b, Node c) { boolean ipba = existsInducingPathInto(b, a, dag); boolean ipbc = existsInducingPathInto(b, c, dag); if (!(ipba && ipbc)) { printTrueDefCollider(a, b, c, false); return false; } printTrueDefCollider(a, b, c, true); return true; } private void printTrueDefCollider(Node a, Node b, Node c, boolean found) { if (truePag != null) { final boolean defCollider = truePag.isDefCollider(a, b, c); if (verbose) { if (!found && defCollider) { System.out.println("FOUND COLLIDER FCI"); } else if (found && !defCollider) { System.out.println("DIDN'T FIND COLLIDER FCI"); } } } } public static boolean existsInducingPathInto(Node x, Node y, Graph graph) { if (x.getNodeType() != NodeType.MEASURED) throw new IllegalArgumentException(); if (y.getNodeType() != NodeType.MEASURED) throw new IllegalArgumentException();
[ " final LinkedList<Node> path = new LinkedList<>();" ]
1,093
lcc
java
null
513f349427eab3898c563f007083539809e961ebeaa5b59d
/** * The i3DML Project * Author: Keyvan M. Kambakhsh * * UNDER GPL V3 LICENSE **/ using System; using i3DML.ObjectModel.Components; namespace i3DML.ObjectModel { /// <summary> /// Provides a drawable or a container element. /// </summary> public abstract class Drawable : WorldElement,Ii3DMLInitializable,IDisposable { #region Fields private ScriptManager _ScriptManager; private Point _Position; private Rotation _Rotation; private Ratio _RotationOrigin; private Ratio _Scale; #endregion #region Properties #region Parents /// <summary> /// Root element. /// </summary> [i3DMLReaderIgnore] public World World { get; internal set; } /// <summary> /// Parent element. /// </summary> [i3DMLReaderIgnore] public PlaceBase Parent { get; internal set; } #endregion #region Visiblity /// <summary> /// Is the element visible on the screen? /// </summary> public bool Visible { get; set; } #endregion #region Position /// <summary> /// Position of element in the element's local space. /// </summary> public Point Position { get { return _Position; } set { if (value != null) _Position = value; } } /// <summary> /// Absolute position of element in the root element. /// </summary> [i3DMLReaderIgnore] public Point AbsolutePosition { get { Point absRot = new Point(); absRot.X = OriginPosition.X; absRot.Y = OriginPosition.Y; absRot.Z = OriginPosition.Z; Drawable parent = this.Parent; Drawable lastParent = null; while (parent.Parent != null) { absRot += parent.OriginPosition; absRot = Matrix.Transform(absRot, Matrix.Rotate(parent.Rotation)); lastParent = parent; parent = parent.Parent; } if (lastParent != null) { Point lp = Matrix.Transform(lastParent.OriginPosition, Matrix.Rotate(lastParent.Rotation)); return (absRot - lp + lastParent.OriginPosition); } else return absRot; } } /// <summary> /// The element's center position in the element's local space (Before scaling). /// </summary> [i3DMLReaderIgnore] public Point CenterPosition { get { Point ret; if (this is Shape) ret = (this as Shape).Size * RotationOrigin; else if (this is Surface) { Size2D s = (this as Surface).Size * RotationOrigin; ret = new Point(s.X, 0, s.Y); } else ret = new Point(0, 0, 0); ret = Matrix.Transform(ret, Matrix.Rotate(Rotation)); return ret; } } /// <summary> /// The element's center position in the element's local space (After scaling). /// </summary> [i3DMLReaderIgnore] public Point OriginPosition { get { return (Position * AbsoluteScale / Scale) - CenterPosition * AbsoluteScale; } } #endregion #region Rotation /// <summary> /// The element's rotation in the element's local space. /// </summary> public Rotation Rotation { get { return _Rotation; } set { if (value != null)_Rotation = value; } } /// <summary> /// The element's absolute rotation matrix in the root element. /// </summary> [i3DMLReaderIgnore] public Matrix AbsoluteRotationMatrix { get { Matrix ret = Matrix.Rotate(Rotation); Drawable parent=Parent; while (parent != null) { ret *= Matrix.Rotate(parent.Rotation); parent = parent.Parent; } return ret; } } /// <summary> /// The element's rotation origin point ratio. /// </summary> public Ratio RotationOrigin { get { return _RotationOrigin; } set { if (value != null)_RotationOrigin = value; } } #endregion #region Scale /// <summary> /// The element's scale in the element's local space. /// </summary> public Ratio Scale { get { return _Scale; } set { if (value != null) _Scale = value; } } /// <summary> /// The element's absolute scale in the root element. /// </summary> [i3DMLReaderIgnore] public Ratio AbsoluteScale { get { Ratio absScale = new Ratio() { X = Scale.X, Y = Scale.Y, Z = Scale.Z }; Drawable parent = Parent; while (parent != null) { absScale *= parent.Scale; parent = parent.Parent; } return absScale; } } #endregion #region Scripts /// <summary> /// Corresponding ScriptManager for this drawable. /// </summary> [i3DMLReaderIgnore] protected ScriptManager ScriptManager { get { return _ScriptManager; } private set { _ScriptManager = value; } } /// <summary> /// Contains drawable scripts. /// </summary> public string Script { get; set; } #region Events public string OnUpdate { get; set; } #endregion #endregion #endregion public Drawable() { this.ScriptManager = new ScriptManager(this); this.RotationOrigin = new Ratio() { X = 0.5d, Y = 0.5d, Z = 0.5d }; this.Position = new Point() { X = 0d, Y = 0d, Z = 0d }; this.Rotation = new Rotation { X = 0d, Y = 0d, Z = 0d }; this.Scale = new Ratio() { X = 1, Y = 1, Z = 1 }; this.Visible = true; } /// <summary> /// Find an element with a specified name by looking to the descendants of this element. /// </summary> /// <param name="Name">Name of the element we are looking for</param> /// <returns>The found element</returns> public Drawable FindElement(string Name) { if (this.Name == Name) return this; var plcs=new System.Collections.Generic.Stack<PlaceBase>(); if (this is PlaceBase) plcs.Push(this as PlaceBase); while (plcs.Count != 0) { PlaceBase pop=plcs.Pop(); if (pop.Name == Name) return pop; for (int i = 0; i < pop.Length; i++) {
[ " if (pop[i] is PlaceBase)" ]
756
lcc
csharp
null
e1cfeee7b51ffa6e208f12e8fc7a842cb7e910013cd3b8fe
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.coi.notesandattachments.attachments; import org.apache.commons.lang3.StringUtils; import org.apache.struts.upload.FormFile; import org.kuali.coeus.common.framework.attachment.AttachmentFile; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.SkipVersioning; import org.kuali.kra.coi.PersonFinIntDisclosureAssociate; import org.kuali.kra.coi.personfinancialentity.PersonFinIntDisclosure; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class FinancialEntityAttachment extends PersonFinIntDisclosureAssociate implements Comparable<FinancialEntityAttachment>{ private static final long serialVersionUID = 8722598360752485817L; private Long attachmentId; private Long fileId; private Long financialEntityId; private PersonFinIntDisclosure financialEntity; private transient AttachmentFile attachmentFile; private transient FormFile newFile; @SkipVersioning private transient String updateUserFullName; private Long personFinIntDisclosureId; private String description; private String contactName; private String contactEmailAddress; private String contactPhoneNumber; private String comments; private String statusCode; private Timestamp updateTimestamp; public FinancialEntityAttachment() { super(); } public FinancialEntityAttachment(FinancialEntityAttachment oldAtt) { this.attachmentId = null; this.fileId = oldAtt.fileId; this.financialEntityId = oldAtt.financialEntityId; this.personFinIntDisclosureId = oldAtt.personFinIntDisclosureId; this.description = oldAtt.description; this.contactName = oldAtt.contactName; this.contactEmailAddress = oldAtt.contactEmailAddress; this.contactPhoneNumber = oldAtt.contactPhoneNumber; this.comments = oldAtt.comments; this.statusCode = oldAtt.statusCode; this.updateTimestamp = oldAtt.updateTimestamp; this.attachmentFile = (AttachmentFile)ObjectUtils.deepCopy(oldAtt.getAttachmentFile()); } public FinancialEntityAttachment(PersonFinIntDisclosure personFinIntDisclosure) { this.setPersonFinIntDisclosure(personFinIntDisclosure); } public Long getFinancialEntityId() { return financialEntityId; } public void setFinancialEntityId(Long financialEntityId) { this.financialEntityId = financialEntityId; } public PersonFinIntDisclosure getFinancialEntity() { return financialEntity; } public void setFinancialEntity(PersonFinIntDisclosure financialEntity) { this.financialEntity = financialEntity; } public Timestamp getUpdateTimestamp() { return updateTimestamp; } public void setUpdateTimestamp(Timestamp updateTimestamp) { this.updateTimestamp = updateTimestamp; } public String getContactEmailAddress() { return contactEmailAddress; } public void setContactEmailAddress(String contactEmailAddress) { this.contactEmailAddress = contactEmailAddress; } public String getContactPhoneNumber() { return contactPhoneNumber; } public void setContactPhoneNumber(String contactPhoneNumber) { this.contactPhoneNumber = contactPhoneNumber; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public Long getAttachmentId() { return attachmentId; } public void setAttachmentId(Long attachmentId) { this.attachmentId = attachmentId; } public Long getFileId() { return fileId; } public void setFileId(Long fileId) { this.fileId = fileId; } public AttachmentFile getAttachmentFile() { return attachmentFile; } public String getFileName() { return (attachmentFile == null) ? "" : attachmentFile.getName(); } public void setFile(AttachmentFile attachmentFile) { this.attachmentFile = attachmentFile; } public FormFile getNewFile() { return newFile; } public void setNewFile(FormFile newFile) { this.newFile = newFile; } public String getUpdateUserFullName() { return updateUserFullName; } public void setUpdateUserFullName(String updateUserFullName) { this.updateUserFullName = updateUserFullName; } public Long getPersonFinIntDisclosureId() { return personFinIntDisclosureId; } public void setPersonFinIntDisclosureId(Long personFinIntDisclosureId) { this.personFinIntDisclosureId = personFinIntDisclosureId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public String getStatusCode() { return statusCode; } public void setUpdateUser(String updateUser) { if (updateUser == null || getUpdateUser() == null ) { super.setUpdateUser(updateUser); } } @Override public int compareTo(FinancialEntityAttachment arg0) { return 0; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } FinancialEntityAttachment other = (FinancialEntityAttachment) obj; if (description == null) { if (other.description != null) { return false; } } else if (!description.equals(other.description)) { return false; } if (this.attachmentFile == null) { if (other.attachmentFile != null) { return false; } } else if (!this.attachmentFile.equals(other.attachmentFile)) { return false; } if (this.fileId == null) { if (other.fileId != null) { return false; } } else if (!this.fileId.equals(other.fileId)) { return false; } return true; } public boolean matches(FinancialEntityAttachment other) { if (this == other) { return true; }
[ " else if (!this.getFileId().equals(other.getFileId())) {" ]
677
lcc
java
null
aebc1dbdefd0470032eb19b36673cec2767fbc28f3a13fd5
using Server.Spells; using Server.Targeting; using System; using System.Collections; using System.Collections.Generic; namespace Server.Items { public abstract class BaseConflagrationPotion : BasePotion { public abstract int MinDamage { get; } public abstract int MaxDamage { get; } public override bool RequireFreeHand => false; public BaseConflagrationPotion(PotionEffect effect) : base(0xF06, effect) { Hue = 0x489; } public BaseConflagrationPotion(Serial serial) : base(serial) { } public override void Drink(Mobile from) { if (from.Paralyzed || from.Frozen || (from.Spell != null && from.Spell.IsCasting)) { from.SendLocalizedMessage(1062725); // You can not use that potion while paralyzed. return; } int delay = GetDelay(from); if (delay > 0) { from.SendLocalizedMessage(1072529, string.Format("{0}\t{1}", delay, delay > 1 ? "seconds." : "second.")); // You cannot use that for another ~1_NUM~ ~2_TIMEUNITS~ return; } ThrowTarget targ = from.Target as ThrowTarget; if (targ != null && targ.Potion == this) return; from.RevealingAction(); if (!m_Users.Contains(from)) m_Users.Add(from); from.Target = new ThrowTarget(this); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } private readonly List<Mobile> m_Users = new List<Mobile>(); public void Explode_Callback(object state) { object[] states = (object[])state; Explode((Mobile)states[0], (Point3D)states[1], (Map)states[2]); } public virtual void Explode(Mobile from, Point3D loc, Map map) { if (Deleted || map == null) return; Consume(); // Check if any other players are using this potion for (int i = 0; i < m_Users.Count; i++) { ThrowTarget targ = m_Users[i].Target as ThrowTarget; if (targ != null && targ.Potion == this) Target.Cancel(from); } // Effects Effects.PlaySound(loc, map, 0x20C); for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { Point3D p = new Point3D(loc.X + i, loc.Y + j, loc.Z); SpellHelper.AdjustField(ref p, map, 16, true); if (SpellHelper.CheckField(p, map) && map.LineOfSight(new Point3D(loc.X, loc.Y, loc.Z + 14), p)) new InternalItem(from, p, map, MinDamage, MaxDamage); } } } #region Delay private static readonly Hashtable m_Delay = new Hashtable(); public static void AddDelay(Mobile m) { Timer timer = m_Delay[m] as Timer; if (timer != null) timer.Stop(); m_Delay[m] = Timer.DelayCall(TimeSpan.FromSeconds(30), new TimerStateCallback(EndDelay_Callback), m); } public static int GetDelay(Mobile m) { Timer timer = m_Delay[m] as Timer; if (timer != null && timer.Next > DateTime.UtcNow) return (int)(timer.Next - DateTime.UtcNow).TotalSeconds; return 0; } private static void EndDelay_Callback(object obj) { if (obj is Mobile) EndDelay((Mobile)obj); } public static void EndDelay(Mobile m) { Timer timer = m_Delay[m] as Timer; if (timer != null) { timer.Stop(); m_Delay.Remove(m); } } #endregion private class ThrowTarget : Target { private readonly BaseConflagrationPotion m_Potion; public BaseConflagrationPotion Potion => m_Potion; public ThrowTarget(BaseConflagrationPotion potion) : base(12, true, TargetFlags.None) { m_Potion = potion; } protected override void OnTarget(Mobile from, object targeted) { if (m_Potion.Deleted || m_Potion.Map == Map.Internal) return; IPoint3D p = targeted as IPoint3D; if (p == null || from.Map == null) return; // Add delay if (from.AccessLevel == AccessLevel.Player) { AddDelay(from); } SpellHelper.GetSurfaceTop(ref p); from.RevealingAction(); IEntity to; if (p is Mobile) to = (Mobile)p; else to = new Entity(Serial.Zero, new Point3D(p), from.Map); Effects.SendMovingEffect(from, to, 0xF0D, 7, 0, false, false, m_Potion.Hue, 0); Timer.DelayCall(TimeSpan.FromSeconds(1.5), new TimerStateCallback(m_Potion.Explode_Callback), new object[] { from, new Point3D(p), from.Map }); } } public class InternalItem : Item { private Mobile m_From; private int m_MinDamage; private int m_MaxDamage; private DateTime m_End; private Timer m_Timer; public Mobile From => m_From; public override bool BlocksFit => true; public InternalItem(Mobile from, Point3D loc, Map map, int min, int max) : base(0x398C) { Movable = false; Light = LightType.Circle300; MoveToWorld(loc, map); m_From = from; m_End = DateTime.UtcNow + TimeSpan.FromSeconds(10); SetDamage(min, max); m_Timer = new InternalTimer(this, m_End); m_Timer.Start(); } public override void OnAfterDelete() { base.OnAfterDelete(); if (m_Timer != null) m_Timer.Stop(); } public InternalItem(Serial serial) : base(serial) { } public int GetDamage() { return Utility.RandomMinMax(m_MinDamage, m_MaxDamage); } private void SetDamage(int min, int max) { /* new way to apply alchemy bonus according to Stratics' calculator. this gives a mean to values 25, 50, 75 and 100. Stratics' calculator is outdated. Those goals will give 2 to alchemy bonus. It's not really OSI-like but it's an approximation. */ m_MinDamage = min; m_MaxDamage = max; if (m_From == null) return; int alchemySkill = m_From.Skills.Alchemy.Fixed; int alchemyBonus = alchemySkill / 125 + alchemySkill / 250; m_MinDamage = Scale(m_From, m_MinDamage + alchemyBonus); m_MaxDamage = Scale(m_From, m_MaxDamage + alchemyBonus); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); // version writer.Write(m_From); writer.Write(m_End); writer.Write(m_MinDamage); writer.Write(m_MaxDamage); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); m_From = reader.ReadMobile(); m_End = reader.ReadDateTime(); m_MinDamage = reader.ReadInt(); m_MaxDamage = reader.ReadInt(); m_Timer = new InternalTimer(this, m_End); m_Timer.Start(); } public override bool OnMoveOver(Mobile m) { if (Visible && m_From != null && m != m_From && SpellHelper.ValidIndirectTarget(m_From, m) && m_From.CanBeHarmful(m, false)) { m_From.DoHarmful(m); AOS.Damage(m, m_From, GetDamage(), 0, 100, 0, 0, 0); m.PlaySound(0x208); } return true; } private class InternalTimer : Timer { private readonly InternalItem m_Item; private readonly DateTime m_End; public InternalTimer(InternalItem item, DateTime end) : base(TimeSpan.Zero, TimeSpan.FromSeconds(1.0)) { m_Item = item; m_End = end; Priority = TimerPriority.FiftyMS; } protected override void OnTick() { if (m_Item.Deleted) return; if (DateTime.UtcNow > m_End) { m_Item.Delete(); Stop(); return; } Mobile from = m_Item.From; if (m_Item.Map == null || from == null) return; List<Mobile> mobiles = new List<Mobile>(); IPooledEnumerable eable = m_Item.GetMobilesInRange(0); foreach (Mobile mobile in eable) mobiles.Add(mobile); eable.Free(); for (int i = 0; i < mobiles.Count; i++) {
[ " Mobile m = mobiles[i];" ]
864
lcc
csharp
null
0e11139b864daa3a41696de69d95d0a294335165cb569f6a
#region Header // Vorspire _,-'/-'/ Channel.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2016 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion #region References using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using Server; using Server.Misc; using Server.Mobiles; #endregion namespace VitaNex.Modules.WorldChat { public struct WorldChatMessage { public PlayerMobile User { get; private set; } public string Text { get; private set; } public MapPoint Place { get; private set; } public DateTime Time { get; private set; } public WorldChatMessage(PlayerMobile user, string text, MapPoint place, DateTime time) : this() { User = user; Text = text; Place = place; Time = time; } public override string ToString() { return Text; } } public abstract class WorldChatChannel : PropertyObject { private static int _NextUID; public static event Action<WorldChatChannel, PlayerMobile> OnUserJoin; public static event Action<WorldChatChannel, PlayerMobile> OnUserLeave; public static event Action<WorldChatChannel, PlayerMobile> OnUserKicked; public static event Action<WorldChatChannel, PlayerMobile> OnUserBanned; public static event Action<WorldChatChannel, PlayerMobile> OnUserUnbanned; public static event Action<WorldChatChannel, PlayerMobile, WorldChatMessage> OnUserMessage; private static void InvokeUserJoin(WorldChatChannel channel, PlayerMobile user) { if (OnUserJoin != null) { OnUserJoin(channel, user); } } private static void InvokeUserLeave(WorldChatChannel channel, PlayerMobile user) { if (OnUserLeave != null) { OnUserLeave(channel, user); } } private static void InvokeUserKicked(WorldChatChannel channel, PlayerMobile user) { if (OnUserKicked != null) { OnUserKicked(channel, user); } } private static void InvokeUserBanned(WorldChatChannel channel, PlayerMobile user) { if (OnUserBanned != null) { OnUserBanned(channel, user); } } private static void InvokeUserUnbanned(WorldChatChannel channel, PlayerMobile user) { if (OnUserUnbanned != null) { OnUserUnbanned(channel, user); } } private static void InvokeUserMessage(WorldChatChannel channel, PlayerMobile user, WorldChatMessage message) { if (OnUserMessage != null) { OnUserMessage(channel, user, message); } } public Dictionary<PlayerMobile, DateTime> Users { get; private set; } public Dictionary<PlayerMobile, DateTime> Bans { get; private set; } public Dictionary<PlayerMobile, WorldChatMessage> History { get; private set; } private readonly int _UID; [CommandProperty(WorldChat.Access)] public int UID { get { return _UID; } } [CommandProperty(WorldChat.Access)] public bool Permanent { get { return WorldChat.PermaChannels.Contains(this); } } [CommandProperty(WorldChat.Access)] public string Name { get; set; } [CommandProperty(WorldChat.Access)] public string Summary { get; set; } [CommandProperty(WorldChat.Access)] public string Token { get; set; } [CommandProperty(WorldChat.Access)] public bool AutoJoin { get; set; } [CommandProperty(WorldChat.Access)] public bool Available { get; set; } [CommandProperty(WorldChat.Access)] public AccessLevel Access { get; set; } [CommandProperty(WorldChat.Access)] public ProfanityAction ProfanityAction { get; set; } [CommandProperty(WorldChat.Access)] public TimeSpan SpamDelay { get; set; } [CommandProperty(WorldChat.Access)] public KnownColor TextColor { get; set; } [CommandProperty(WorldChat.Access)] public int TextHue { get; set; } [CommandProperty(WorldChat.Access)] public int UserLimit { get; set; } [CommandProperty(WorldChat.Access)] public int UserCount { get { return Users.Keys.Count(u => u.AccessLevel <= Access); } } [CommandProperty(WorldChat.Access)] public int BanCount { get { return Bans.Count; } } [CommandProperty(WorldChat.Access)] public int HistoryCount { get { return History.Count; } } public WorldChatChannel() { _UID = _NextUID++; Name = "Chat"; Summary = ""; ProfanityAction = ProfanityAction.None; TextColor = KnownColor.LawnGreen; TextHue = 85; UserLimit = 500; SpamDelay = TimeSpan.FromSeconds(5.0); History = new Dictionary<PlayerMobile, WorldChatMessage>(); Users = new Dictionary<PlayerMobile, DateTime>(); Bans = new Dictionary<PlayerMobile, DateTime>(); Token = _UID.ToString(CultureInfo.InvariantCulture); } public WorldChatChannel(GenericReader reader) : base(reader) { } public override void Clear() { Name = "Chat"; Summary = ""; Token = UID.ToString(CultureInfo.InvariantCulture); Available = false; ProfanityAction = ProfanityAction.None; TextColor = KnownColor.LawnGreen; TextHue = 85; UserLimit = 0; SpamDelay = TimeSpan.Zero; History.Clear(); Bans.Clear(); } public override void Reset() { Name = "Chat"; Summary = ""; Token = UID.ToString(CultureInfo.InvariantCulture); Available = true; ProfanityAction = ProfanityAction.None; TextColor = KnownColor.LawnGreen; TextHue = 85; UserLimit = 500; SpamDelay = TimeSpan.FromSeconds(5.0); History.Clear(); Bans.Clear(); } public virtual Dictionary<PlayerMobile, WorldChatMessage> GetHistoryView(PlayerMobile user) { var list = new Dictionary<PlayerMobile, WorldChatMessage>(); History.Where(kv => CanSee(user, kv.Value)).ForEach(kv => list.Add(kv.Key, kv.Value)); return list; } public virtual bool CanSee(PlayerMobile user, WorldChatMessage message) { return user != null && (user == message.User || (IsUser(user) && !IsBanned(user))); } public virtual bool IsUser(PlayerMobile user) { return user != null && Users.ContainsKey(user); } public virtual bool IsBanned(PlayerMobile user) { return user != null && Bans.ContainsKey(user) && Bans[user] > DateTime.Now; } protected virtual bool OnProfanityDetected(PlayerMobile user, string text, bool message = true) { return false; } public virtual string FormatMessage(PlayerMobile user, string text) { return String.Format( "[{0}] [{1}{2}]: {3}", Name, WorldChat.CMOptions.AccessPrefixes[user.AccessLevel], user.RawName, text); } public virtual bool CanMessage(PlayerMobile user, string text, bool message = true) { if (!Available) { if (message) { InternalMessage(user, "The channel '{0}' is currently unavailable.", Name); } return false; } if (!IsUser(user) && user.AccessLevel < AccessLevel.Counselor) { if (message) { InternalMessage(user, "You are not in the channel '{0}'", Name); } return false; } if (user.AccessLevel < Access) { if (message) { InternalMessage(user, "You do not have sufficient access to speak in the channel '{0}'", Name); } return false; } if (IsUser(user) && user.AccessLevel < AccessLevel.Counselor && Users[user] > DateTime.Now) { if (message) { InternalMessage(user, "Spam detected, message blocked."); } return false; } if ( !NameVerification.Validate( text, 0, Int32.MaxValue, true, true, false, Int32.MaxValue, ProfanityProtection.Exceptions, ProfanityProtection.Disallowed, ProfanityProtection.StartDisallowed)) { switch (ProfanityAction) { case ProfanityAction.None: return true; case ProfanityAction.Criminal: user.Criminal = true; return true; case ProfanityAction.CriminalAction: user.CriminalAction(true); return true; case ProfanityAction.Disallow: return false; case ProfanityAction.Disconnect: Kick(user, false, message); return false; case ProfanityAction.Other: return OnProfanityDetected(user, text, message); } } return true; } public virtual void InternalMessage(PlayerMobile user, string text, params object[] args) { text = Utility.FixHtml(text); if (args != null && args.Length > 0) { user.SendMessage(TextHue, text, args); } else { user.SendMessage(TextHue, text); } } public virtual void MessageTo(PlayerMobile user, PlayerMobile to, string text) { InternalMessage(to, text); } public virtual bool Message(PlayerMobile user, string text, bool message = true) { if (!CanMessage(user, text, message)) { return false; } if (!IsUser(user)) { Join(user, message); } var msg = new WorldChatMessage(user, text, user.ToMapPoint(), DateTime.Now); var formatted = FormatMessage(user, text); Users.Keys.Where(u => CanSee(u, msg)).ForEach(u => MessageTo(user, u, formatted)); if (WorldChat.CMOptions.HistoryBuffer > 0) {
[ "\t\t\t\twhile (HistoryCount >= WorldChat.CMOptions.HistoryBuffer)" ]
964
lcc
csharp
null
1d26c663ec47ee3d35774aa3b47622ec574c5ea151b49857
/* * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.admin.mock; import com.silverpeas.admin.components.WAComponent; import com.stratelia.webactiv.beans.admin.*; import org.silverpeas.util.ListSlice; import javax.inject.Named; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock; /** * A wrapper around an OrganizationController mock for testing purpose. * It is managed by the IoC container and it plays the role of an OrganizationController instance * for the business objects involved in a test. For doing, it delegates the invoked methods to * the wrapped mock. * You can get the wrapped mock for registering some behaviours an OrganizationController instance * should have in the tests. */ @Named("organizationController") public class OrganizationControllerMockWrapper extends OrganizationController { private static final long serialVersionUID = 2449731617524868440L; private OrganizationController mock; public OrganizationControllerMockWrapper() { mock = mock(OrganizationController.class); } /** * Gets the mock of the OrganizationController class wrapped by this instance. * @return an OrganizationController mock. */ public OrganizationController getMock() { return mock; } @Override public String[] searchUsersIds(String groupId, String componentId, String[] profileId, UserDetail filterUser) { return mock.searchUsersIds(groupId, componentId, profileId, filterUser); } @Override public UserDetail[] searchUsers(UserDetail modelUser, boolean isAnd) { return mock.searchUsers(modelUser, isAnd); } @Override public ListSlice<UserDetail> searchUsers(UserDetailsSearchCriteria criteria) { return mock.searchUsers(criteria); } @Override public ListSlice<Group> searchGroups(GroupsSearchCriteria criteria) { return mock.searchGroups(criteria); } @Override public String[] searchGroupsIds(boolean isRootGroup, String componentId, String[] profileId, Group modelGroup) { return mock.searchGroupsIds(isRootGroup, componentId, profileId, modelGroup); } @Override public Group[] searchGroups(Group modelGroup, boolean isAnd) { return mock.searchGroups(modelGroup, isAnd); } @Override public void reloadAdminCache() { mock.reloadAdminCache(); } @Override public boolean isSpaceAvailable(String spaceId, String userId) { return mock.isSpaceAvailable(spaceId, userId); } @Override public boolean isObjectAvailable(int objectId, ObjectType objectType, String componentId, String userId) { return mock.isObjectAvailable(objectId, objectType, componentId, userId); } @Override public boolean isComponentManageable(String componentId, String userId) { return mock.isComponentManageable(componentId, userId); } @Override public boolean isComponentExist(String componentId) { return mock.isComponentExist(componentId); } @Override public boolean isComponentAvailable(String componentId, String userId) { return mock.isComponentAvailable(componentId, userId); } @Override public boolean isAnonymousAccessActivated() { return mock.isAnonymousAccessActivated(); } @Override public String[] getUsersIdsByRoleNames(String componentId, String objectId, ObjectType objectType, List<String> profileNames) { return mock.getUsersIdsByRoleNames(componentId, objectId, objectType, profileNames); } @Override public String[] getUsersIdsByRoleNames(String componentId, List<String> profileNames) { return mock.getUsersIdsByRoleNames(componentId, profileNames); } @Override public UserDetail[] getUsers(String sPrefixTableName, String sComponentName, String sProfile) { return mock.getUsers(sPrefixTableName, sComponentName, sProfile); } @Override public String[] getUserProfiles(String userId, String componentId, int objectId, ObjectType objectType) { return mock.getUserProfiles(userId, componentId, objectId, objectType); } @Override public String[] getUserProfiles(String userId, String componentId) { return mock.getUserProfiles(userId, componentId); } @Override public ProfileInst getUserProfile(String profileId) { return mock.getUserProfile(profileId); } @Override public String[] getUserManageableSpaceIds(String sUserId) { return mock.getUserManageableSpaceIds(sUserId); } @Override public UserFull getUserFull(String sUserId) { return mock.getUserFull(sUserId); } @Override public UserDetail[] getUserDetails(String[] asUserIds) { return mock.getUserDetails(asUserIds); } @Override public String getUserDetailByDBId(int id) { return mock.getUserDetailByDBId(id); } @Override public UserDetail getUserDetail(String sUserId) { return mock.getUserDetail(sUserId); } @Override public int getUserDBId(String sUserId) { return mock.getUserDBId(sUserId); } @Override public List<SpaceInstLight> getSubSpacesContainingComponent(String spaceId, String userId, String componentName) { return mock.getSubSpacesContainingComponent(spaceId, userId, componentName); } @Override public List<SpaceInstLight> getSpaceTreeview(String userId) { return mock.getSpaceTreeview(userId); } @Override public List<SpaceInst> getSpacePathToComponent(String componentId) { return mock.getSpacePathToComponent(componentId); } @Override public List<SpaceInst> getSpacePath(String spaceId) { return mock.getSpacePath(spaceId); } @Override public String[] getSpaceNames(String[] asSpaceIds) { return mock.getSpaceNames(asSpaceIds); } @Override public SpaceInstLight getSpaceInstLightById(String spaceId) { return mock.getSpaceInstLightById(spaceId); } @Override public SpaceInst getSpaceInstById(String sSpaceId) { return mock.getSpaceInstById(sSpaceId); } @Override public List<SpaceInstLight> getRootSpacesContainingComponent(String userId, String componentName) { return mock.getRootSpacesContainingComponent(userId, componentName); } @Override public SpaceInstLight getRootSpace(String spaceId) { return mock.getRootSpace(spaceId); } @Override public List<String> getPathToGroup(String groupId) { return mock.getPathToGroup(groupId); } @Override public Group[] getGroups(String[] groupsId) { return mock.getGroups(groupsId); } @Override public Group getGroup(String sGroupId) { return mock.getGroup(sGroupId); } @Override public String getGeneralSpaceId() { return mock.getGeneralSpaceId(); } @Override public UserDetail[] getFiltredDirectUsers(String sGroupId, String sUserLastNameFilter) { return mock.getFiltredDirectUsers(sGroupId, sUserLastNameFilter); } @Override public Domain getDomain(String domainId) { return mock.getDomain(domainId); } @Override public String[] getDirectGroupIdsOfUser(String userId) { return mock.getDirectGroupIdsOfUser(userId); } @Override public String getComponentParameterValue(String sComponentId, String parameterName) { return mock.getComponentParameterValue(sComponentId, parameterName); } @Override public ComponentInstLight getComponentInstLight(String sComponentId) { return mock.getComponentInstLight(sComponentId); } @Override public ComponentInst getComponentInst(String sComponentId) { return mock.getComponentInst(sComponentId); } @Override public String[] getComponentIdsForUser(String sUserId, String sCompoName) { return mock.getComponentIdsForUser(sUserId, sCompoName); } @Override public String[] getCompoId(String sCompoName) { return mock.getCompoId(sCompoName); } @Override public CompoSpace[] getCompoForUser(String sUserId, String sCompoName) { return mock.getCompoForUser(sUserId, sCompoName); } @Override public String[] getAvailDriverCompoIds(String sClientSpaceId, String sUserId) { return mock.getAvailDriverCompoIds(sClientSpaceId, sUserId); } @Override public List<ComponentInstLight> getAvailComponentInstLights(String userId, String componentName) { return mock.getAvailComponentInstLights(userId, componentName); } @Override public String[] getAvailCompoIdsAtRoot(String sClientSpaceId, String sUserId) { return mock.getAvailCompoIdsAtRoot(sClientSpaceId, sUserId); } @Override public String[] getAvailCompoIds(String sClientSpaceId, String sUserId) {
[ " return mock.getAvailCompoIds(sClientSpaceId, sUserId);" ]
882
lcc
java
null
b519f9921c8764941f3609154c5ff4b26d6c0630555f325d
package com.bkoneti.fileManager.controller; import android.app.Activity; import android.app.DialogFragment; import android.content.Intent; import android.net.Uri; import android.util.SparseBooleanArray; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.widget.AbsListView; import android.widget.AbsListView.MultiChoiceModeListener; import com.bkoneti.fileManager.BrowserActivity; import com.bkoneti.fileManager.R; import com.bkoneti.fileManager.SearchActivity; import com.bkoneti.fileManager.adapters.BookmarksAdapter; import com.bkoneti.fileManager.dialogs.DeleteFilesDialog; import com.bkoneti.fileManager.dialogs.FilePropertiesDialog; import com.bkoneti.fileManager.dialogs.GroupOwnerDialog; import com.bkoneti.fileManager.dialogs.RenameDialog; import com.bkoneti.fileManager.dialogs.ZipFilesDialog; import com.bkoneti.fileManager.settings.Settings; import com.bkoneti.fileManager.utils.ClipBoard; import com.bkoneti.fileManager.utils.SimpleUtils; import java.io.File; import java.util.ArrayList; public final class ActionModeController { private final MultiChoiceModeListener multiChoiceListener; private final Activity mActivity; private AbsListView mListView; private ActionMode mActionMode; public ActionModeController(final Activity activity) { this.mActivity = activity; this.multiChoiceListener = new MultiChoiceListener(); } public void finishActionMode() { if (this.mActionMode != null) { this.mActionMode.finish(); } } public void setListView(AbsListView list) { if (this.mActionMode != null) { this.mActionMode.finish(); } this.mListView = list; this.mListView.setMultiChoiceModeListener(this.multiChoiceListener); } public boolean isActionMode() { return mActionMode != null; } private final class MultiChoiceListener implements MultiChoiceModeListener { final String mSelected = mActivity.getString(R.string._selected); @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { menu.clear(); mActivity.getMenuInflater().inflate(R.menu.actionmode, menu); if (mActivity instanceof SearchActivity) { menu.removeItem(R.id.actiongroupowner); menu.removeItem(R.id.actionrename); menu.removeItem(R.id.actionzip); if (mListView.getCheckedItemCount() > 1) { menu.removeItem(R.id.actiondetails); } } else { if (!Settings.rootAccess()) menu.removeItem(R.id.actiongroupowner); if (mListView.getCheckedItemCount() > 1) { menu.removeItem(R.id.actionrename); menu.removeItem(R.id.actiongroupowner); menu.removeItem(R.id.actiondetails); } } return true; } @Override public void onDestroyActionMode(ActionMode mode) { ActionModeController.this.mActionMode = null; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { ActionModeController.this.mActionMode = mode; return true; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { final SparseBooleanArray items = mListView.getCheckedItemPositions(); final int checkedItemSize = items.size(); final String[] files = new String[mListView.getCheckedItemCount()]; int index = -1; switch (item.getItemId()) { case R.id.actionmove: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { files[++index] = (String) mListView.getItemAtPosition(key); } } ClipBoard.cutMove(files); mode.finish(); mActivity.invalidateOptionsMenu(); return true; case R.id.actioncopy: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { files[++index] = (String) mListView.getItemAtPosition(key); } } ClipBoard.cutCopy(files); mode.finish(); mActivity.invalidateOptionsMenu(); return true; case R.id.actiongroupowner: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { final DialogFragment dialog9 = GroupOwnerDialog .instantiate(new File((String) mListView .getItemAtPosition(key))); mode.finish(); dialog9.show(mActivity.getFragmentManager(), BrowserActivity.TAG_DIALOG); break; } } return true; case R.id.actiondelete: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { files[++index] = (String) mListView.getItemAtPosition(key); } } final DialogFragment dialog1 = DeleteFilesDialog.instantiate(files); mode.finish(); dialog1.show(mActivity.getFragmentManager(), BrowserActivity.TAG_DIALOG); return true; case R.id.actionshare: final ArrayList<Uri> uris = new ArrayList<>(mListView.getCheckedItemCount()); for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { final File selected = new File((String) mListView.getItemAtPosition(key)); if (!selected.isDirectory()) { uris.add(Uri.fromFile(selected)); } } } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND_MULTIPLE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType("*/*"); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); mode.finish(); mActivity.startActivity(Intent.createChooser(intent, mActivity.getString(R.string.share))); return true; case R.id.actionshortcut: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { files[++index] = (String) mListView.getItemAtPosition(key); } } for (String a : files) { SimpleUtils.createShortcut(mActivity, a); } mode.finish(); return true; case R.id.actionbookmark: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) { files[++index] = (String) mListView.getItemAtPosition(key); } } BookmarksAdapter mAdapter = BrowserActivity.getBookmarksAdapter(); for (String a : files) { mAdapter.createBookmark(new File(a)); } mode.finish(); return true; case R.id.actionzip: for (int i = 0; i < checkedItemSize; i++) { final int key = items.keyAt(i); if (items.get(key)) {
[ " files[++index] = (String) mListView.getItemAtPosition(key);" ]
526
lcc
java
null
3bd9b54a05c3a1d9fac2ee41a5e9f728a8b777e66409b700
package net.minecraft.server; import com.google.common.collect.Queues; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalEventLoopGroup; import io.netty.channel.local.LocalServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.timeout.TimeoutException; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.net.SocketAddress; import java.util.Queue; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.crypto.SecretKey; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; public class NetworkManager extends SimpleChannelInboundHandler<Packet> { private static final Logger g = LogManager.getLogger(); public static final Marker a = MarkerManager.getMarker("NETWORK"); public static final Marker b = MarkerManager.getMarker("NETWORK_PACKETS", NetworkManager.a); public static final AttributeKey<EnumProtocol> c = AttributeKey.valueOf("protocol"); public static final LazyInitVar<NioEventLoopGroup> d = new LazyInitVar() { protected NioEventLoopGroup a() { return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); } protected Object init() { return this.a(); } }; public static final LazyInitVar<EpollEventLoopGroup> e = new LazyInitVar() { protected EpollEventLoopGroup a() { return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build()); } protected Object init() { return this.a(); } }; public static final LazyInitVar<LocalEventLoopGroup> f = new LazyInitVar() { protected LocalEventLoopGroup a() { return new LocalEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build()); } protected Object init() { return this.a(); } }; private final EnumProtocolDirection h; private final Queue<NetworkManager.QueuedPacket> i = Queues.newConcurrentLinkedQueue(); private final ReentrantReadWriteLock j = new ReentrantReadWriteLock(); public Channel channel; // Spigot Start // PAIL public SocketAddress l; public java.util.UUID spoofedUUID; public com.mojang.authlib.properties.Property[] spoofedProfile; public boolean preparing = true; // Spigot End private PacketListener m; private IChatBaseComponent n; private boolean o; private boolean p; public NetworkManager(EnumProtocolDirection enumprotocoldirection) { this.h = enumprotocoldirection; } public void channelActive(ChannelHandlerContext channelhandlercontext) throws Exception { super.channelActive(channelhandlercontext); this.channel = channelhandlercontext.channel(); this.l = this.channel.remoteAddress(); // Spigot Start this.preparing = false; // Spigot End try { this.a(EnumProtocol.HANDSHAKING); } catch (Throwable throwable) { NetworkManager.g.fatal(throwable); } } public void a(EnumProtocol enumprotocol) { this.channel.attr(NetworkManager.c).set(enumprotocol); this.channel.config().setAutoRead(true); NetworkManager.g.debug("Enabled auto read"); } public void channelInactive(ChannelHandlerContext channelhandlercontext) throws Exception { this.close(new ChatMessage("disconnect.endOfStream", new Object[0])); } public void exceptionCaught(ChannelHandlerContext channelhandlercontext, Throwable throwable) throws Exception { ChatMessage chatmessage; if (throwable instanceof TimeoutException) { chatmessage = new ChatMessage("disconnect.timeout", new Object[0]); } else { chatmessage = new ChatMessage("disconnect.genericReason", new Object[] { "Internal Exception: " + throwable}); } this.close(chatmessage); if (MinecraftServer.getServer().isDebugging()) throwable.printStackTrace(); // Spigot } protected void a(ChannelHandlerContext channelhandlercontext, Packet packet) throws Exception { if (this.channel.isOpen()) { try { packet.a(this.m); } catch (CancelledPacketHandleException cancelledpackethandleexception) { ; } } } public void a(PacketListener packetlistener) { Validate.notNull(packetlistener, "packetListener", new Object[0]); NetworkManager.g.debug("Set listener of {} to {}", new Object[] { this, packetlistener}); this.m = packetlistener; } public void handle(Packet packet) { if (this.g()) { this.m(); this.a(packet, (GenericFutureListener[]) null); } else { this.j.writeLock().lock(); try { this.i.add(new NetworkManager.QueuedPacket(packet, (GenericFutureListener[]) null)); } finally { this.j.writeLock().unlock(); } } } public void a(Packet packet, GenericFutureListener<? extends Future<? super Void>> genericfuturelistener, GenericFutureListener<? extends Future<? super Void>>... agenericfuturelistener) { if (this.g()) { this.m(); this.a(packet, (GenericFutureListener[]) ArrayUtils.add(agenericfuturelistener, 0, genericfuturelistener)); } else { this.j.writeLock().lock(); try { this.i.add(new NetworkManager.QueuedPacket(packet, (GenericFutureListener[]) ArrayUtils.add(agenericfuturelistener, 0, genericfuturelistener))); } finally { this.j.writeLock().unlock(); } } } private void a(final Packet packet, final GenericFutureListener<? extends Future<? super Void>>[] agenericfuturelistener) { final EnumProtocol enumprotocol = EnumProtocol.a(packet); final EnumProtocol enumprotocol1 = (EnumProtocol) this.channel.attr(NetworkManager.c).get(); if (enumprotocol1 != enumprotocol) { NetworkManager.g.debug("Disabled auto read"); this.channel.config().setAutoRead(false); } if (this.channel.eventLoop().inEventLoop()) { if (enumprotocol != enumprotocol1) { this.a(enumprotocol); } ChannelFuture channelfuture = this.channel.writeAndFlush(packet); if (agenericfuturelistener != null) { channelfuture.addListeners(agenericfuturelistener); } channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } else { this.channel.eventLoop().execute(new Runnable() { public void run() { if (enumprotocol != enumprotocol1) { NetworkManager.this.a(enumprotocol); } ChannelFuture channelfuture = NetworkManager.this.channel.writeAndFlush(packet); if (agenericfuturelistener != null) { channelfuture.addListeners(agenericfuturelistener); } channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } }); } } private void m() { if (this.channel != null && this.channel.isOpen()) { this.j.readLock().lock(); try { while (!this.i.isEmpty()) { NetworkManager.QueuedPacket networkmanager_queuedpacket = (NetworkManager.QueuedPacket) this.i.poll(); this.a(networkmanager_queuedpacket.a, networkmanager_queuedpacket.b); } } finally { this.j.readLock().unlock(); } } } public void a() { this.m();
[ " if (this.m instanceof IUpdatePlayerListBox) {" ]
598
lcc
java
null
12a85487bcc201bf5b2d1aed937af17781714f568e2f4f03
# -*- coding: utf-8 -*- """ BIRRP =========== * deals with inputs and outputs from BIRRP Created on Tue Sep 20 14:33:20 2016 @author: jrpeacock """ #============================================================================== import numpy as np import os import subprocess import time from datetime import datetime import mtpy.core.z as mtz import mtpy.utils.configfile as mtcfg import mtpy.utils.filehandling as mtfh import mtpy.utils.exceptions as mtex import mtpy.core.edi as mtedi #============================================================================== class BIRRP_Parameters(object): """ class to hold and produce the appropriate parameters given the input parameters. """ def __init__(self, ilev=0, **kwargs): # set the input level self.ilev = ilev self.ninp = 2 self._nout = 3 self._nref = 2 self.nr2 = 0 self.nr3 = 0 self.tbw = 2.0 self.nfft = 2**18 self.nsctmax = 14 self.ofil = 'mt' self.nlev = 0 self.nar = 5 self.imode = 0 self.jmode = 0 self.nfil = 0 self.nrr = 1 self.nsctinc = 2 self.nsctmax = int(np.floor(np.log2(self.nfft))-4) self.nf1 = int(self.tbw+2) self.nfinc = int(self.tbw) self.nfsect = 2 self.mfft = 2 self.uin = 0 self.ainlin = 0.0001 self.ainuin = 0.9999 self.c2threshb = 0.0 self.c2threshe = 0.0 self.nz = 0 self.perlo = 1000 self.perhi = .0001 self.nprej = 0 self.prej = None self.c2threshe1 = 0 self.thetae = [0, 90, 0] self.thetab = [0, 90, 0] self.thetaf = [0, 90, 0] # set any attributes that are given for key in kwargs.keys(): setattr(self, key, kwargs[key]) self._validate_parameters() def _get_parameters(self): """ get appropriate parameters """ param_dict = {} param_dict['ninp'] = self.ninp param_dict['nout'] = self._nout param_dict['nref'] = self._nref param_dict['tbw'] = self.tbw param_dict['nfft'] = self.nfft param_dict['nsctmax'] = self.nsctmax param_dict['ofil'] = self.ofil param_dict['nlev'] = self.nlev param_dict['nar'] = self.nar param_dict['imode'] = self.imode param_dict['jmode'] = self.jmode param_dict['nfil'] = self.nfil param_dict['thetae'] = self.thetae param_dict['thetab'] = self.thetab param_dict['thetaf'] = self.thetaf if self.ilev == 0: param_dict['uin'] = self.uin param_dict['ainuin'] = self.ainuin param_dict['c2threshe'] = self.c2threshe param_dict['nz'] = self.nz param_dict['c2thresh1'] = self.c2threshe1 elif self.ilev == 1: if self._nref > 3: param_dict['nref2'] = self._nref_2 param_dict['nref3'] = self._nref_3 param_dict['nrr'] = self.nrr param_dict['nsctinc'] = self.nsctinc param_dict['nsctmax'] = self.nsctmax param_dict['nf1'] = self.nf1 param_dict['nfinc'] = self.nfinc param_dict['nfsect'] = self.nfsect param_dict['uin'] = self.uin param_dict['ainlin'] = self.ainlin param_dict['ainuin'] = self.ainuin if self.nrr == 1: param_dict['c2thresh'] = self.c2threshb param_dict['c2threse'] = self.c2threshe if self.c2threshe == 0 and self.c2threshb == 0: param_dict['nz'] = self.nz else: param_dict['nz'] = self.nz param_dict['perlo'] = self.perlo param_dict['perhi'] = self.perhi elif self.nrr == 0: param_dict['c2threshb'] = self.c2threshb param_dict['c2threse'] = self.c2threshe param_dict['nprej'] = self.nprej param_dict['prej'] = self.prej param_dict['c2thresh1'] = self.c2threshe1 return param_dict def _validate_parameters(self): """ check to make sure the parameters are legit. """ # be sure the if self.ninp not in [1, 2, 3]: print 'Number of inputs {0} not allowed.'.format(self.ninp) self.ninp = 2 print ' --> setting ninp to {0}'.format(self.ninp) if self._nout not in [2, 3]: print 'Number of outputs {0} not allowed.'.format(self._nout) self._nout = 2 print ' --> setting nout to {0}'.format(self._nout) if self._nref > 3: print 'nref > 3, setting ilev to 1' self.ilev = 1 if self.tbw < 0 or self.tbw > 4: print 'Total bandwidth of slepian window {0} not allowed.'.format(self.tbw) self.tbw = 2 print ' --> setting tbw to {0}'.format(self.tbw) if np.remainder(np.log2(self.nfft), 2) != 0: print 'Window length nfft should be a power of 2 not {0}'.format(self.nfft) self.nfft = 2**np.floor(np.log2(self.nfft)) print ' -- > setting nfft to {0}, (2**{1:.0f})'.format(self.nfft, np.log2(self.nfft)) if np.log2(self.nfft)-self.nsctmax < 4: print 'Maximum number of windows {0} is too high'.format(self.nsctmax) self.nsctmax = np.log2(self.nfft)-4 print ' --> setting nsctmax to {0}'.format(self.nsctmax) if self.uin != 0: print 'You\'re playing with fire if uin is not 0.' self.uin = 0 print ' --> setting uin to 0, if you don\'t want that change it back' if self.imode not in [0, 1, 2, 3]: raise BIRRP_Parameter_Error('Invalid number for time series mode,' 'imode, {0}, should be 0, 1, 2, or 3'.format(self.imode)) if self.jmode not in [0, 1]: raise BIRRP_Parameter_Error('Invalid number for time mode,' 'imode, {0}, should be 0, or 1'.format(self.imode)) if self.ilev == 1: if self.nsctinc != 2: print '!WARNING! Check decimation increment nsctinc, should be 2 not {0}'.format(self.nsctinc) if self.nfsect != 2: print 'Will get an error from BIRRP if nfsect is not 2.' print 'number of frequencies per section is {0}'.format(self.nfsect) self.nfsect = 2 print ' --> setting nfsect to 2' if self.nf1 != self.tbw+2: print '!WARNING! First frequency should be around tbw+2.' print 'nf1 currently set to {0}'.format(self.nf1) if self.nfinc != self.tbw: print '!WARNING! sequence of frequencies per window should be around tbw.' print 'nfinc currently set to {0}'.format(self.nfinc) if self.nprej != 0: if self.prej is None or type(self.prej) is not list: raise BIRRP_Parameter_Error('Need to input a prejudice list if nprej != 0'+ '\nInput as a list of frequencies' ) if self.nrr not in [0, 1]: print('!WARNING! Value for picking remote reference or '+ 'two stage processing, nrr, '+ 'should be 0 or 1 not {0}'.format(self.nrr)) self.nrr = 0 print ' --> setting nrr to {0}'.format(self.nrr) if self.c2threshe != 0 or self.c2threshb != 0: if not self.perhi: raise BIRRP_Parameter_Error('Need to input a high period (s) threshold as perhi') if not self.perlo: raise BIRRP_Parameter_Error('Need to input a low period (s) threshold as perlo') if len(self.thetae) != 3: print 'Electric rotation angles not input properly {0}'.format(self.thetae) print 'input as north, east, orthogonal rotation' self.thetae = [0, 90, 0] print ' --> setting thetae to {0}'.format(self.thetae) if len(self.thetab) != 3: print 'Magnetic rotation angles not input properly {0}'.format(self.thetab) print 'input as north, east, orthogonal rotation' self.thetab = [0, 90, 0] print ' --> setting thetab to {0}'.format(self.thetab) if len(self.thetaf) != 3: print 'Fiedl rotation angles not input properly {0}'.format(self.thetaf) print 'input as north, east, orthogonal rotation' self.thetaf = [0, 90, 0] print ' --> setting thetaf to {0}'.format(self.thetaf) def read_config_file(self, birrp_config_fn): """ read in a configuration file and fill in the appropriate parameters """ birrp_dict = mtcfg.read_configfile(birrp_config_fn) for birrp_key in birrp_dict.keys(): try: b_value = float(birrp_dict[birrp_key]) if np.remainder(b_value, 1) == 0: b_value = int(b_value) except ValueError: b_value = birrp_dict[birrp_key] setattr(self, birrp_key, b_value) def write_config_file(self, save_fn): """ write a config file for birrp parameters """ cfg_fn = mtfh.make_unique_filename('{0}_birrp_params.cfg'.format(save_fn)) birrp_dict = self._get_parameters() mtcfg.write_dict_to_configfile(birrp_dict, cfg_fn) print 'Wrote BIRRP config file for edi file to {0}'.format(cfg_fn) #============================================================================== # Error classes #============================================================================== class BIRRP_Parameter_Error(Exception): pass class Script_File_Error(Exception): pass #============================================================================== # write script file #============================================================================== class ScriptFile(BIRRP_Parameters): """ class to read and write script file **Arguments** -------------------- **fn_arr** : numpy.ndarray numpy.ndarray([[block 1], [block 2]]) .. note:: [block n] is a numpy structured array with data type =================== ================================= ================= Name Description Type =================== ================================= ================= fn file path/name string nread number of points to read int nskip number of points to skip int comp component [ ex | ey | hx hy | hz ] calibration_fn calibration file path/name string rr a remote reference channel [ True | False ] rr_num remote reference pair number int =================== ================================= ================= **BIRRP Parameters** ------------------------- ================== ======================================================== parameter description ================== ======================================================== ilev processing mode 0 for basic and 1 for advanced RR-2 stage nout Number of Output time series (2 or 3-> for BZ) ninp Number of input time series for E-field (1,2,3) nref Number of reference channels (2 for MT) nrr bounded remote reference (0) or 2 stage bounded influence (1) tbw Time bandwidth for Sepian sequence deltat Sampling rate (+) for (s), (-) for (Hz) nfft Length of FFT (should be even) nsctinc section increment divisor (2 to divide by half) nsctmax Number of windows used in FFT nf1 1st frequency to extract from FFT window (>=3) nfinc frequency extraction increment nfsect number of frequencies to extract mfft AR filter factor, window divisor (2 for half) uin Quantile factor determination ainlin Residual rejection factor low end (usually 0) ainuin Residual rejection factor high end (.95-.99) c2threshb Coherence threshold for magnetics (0 if undesired) c2threshe Coherence threshold for electrics (0 if undesired) nz Threshold for Bz (0=separate from E, 1=E threshold, 2=E and B) Input if 3 B components else None c2thresh1 Squared coherence for Bz, input if NZ=0, Nout=3 perlo longest period to apply coherence threshold over perhi shortes period to apply coherence threshold over ofil Output file root(usually three letters, can add full path) nlev Output files (0=Z; 1=Z,qq; 2=Z,qq,w; 3=Z,qq,w,d) nprej number of frequencies to reject prej frequencies to reject (+) for period, (-) for frequency npcs Number of independent data to be processed (1 for one segement) nar Prewhitening Filter (3< >15) or 0 if not desired', imode Output file mode (0=ascii; 1=binary; 2=headerless ascii; 3=ascii in TS mode', jmode input file mode (0=user defined; 1=sconvert2tart time YYYY-MM-DD HH:MM:SS)', nread Number of points to be read for each data set (if segments>1 -> npts1,npts2...)', nfil Filter parameters (0=none; >0=input parameters; <0=filename) nskip Skip number of points in time series (0) if no skip, (if segements >1 -> input1,input2...)', nskipr Number of points to skip over (0) if none, (if segements >1 -> input1,input2...)', thetae Rotation angles for electrics (relative to geomagnetic North)(N,E,rot)', thetab Rotation angles for magnetics (relative to geomagnetic North)(N,E,rot)', thetar Rotation angles for calculation (relative to geomagnetic North)(N,E,rot)' ================== ======================================================== .. note:: Currently only supports jmode = 0 and imode = 0 .. seealso:: BIRRP Manual and publications by Chave and Thomson for more details on the parameters found at: http://www.whoi.edu/science/AOPE/people/achave/Site/Next1.html """ def __init__(self, script_fn=None, fn_arr=None, **kwargs): super(ScriptFile, self).__init__(fn_arr=None, **kwargs) self.fn_arr = fn_arr self.script_fn = None self._npcs = 0 self._nref = 2 self._nref_2 = 0 self._nref_3 = 0 self._comp_list = None self.deltat = None self._fn_dtype = np.dtype([('fn', 'S100'), ('nread', np.int), ('nskip', np.int), ('comp', 'S2'), ('calibration_fn', 'S100'), ('rr', np.bool), ('rr_num', np.int), ('start_dt', 'S19'), ('end_dt', 'S19')]) if self.fn_arr is not None: self._validate_fn_arr() for key in kwargs.keys(): setattr(self, key, kwargs[key]) def _validate_fn_arr(self): """ make sure fn_arr is an np.array """ if type(self.fn_arr[0]) is not np.ndarray: raise Script_File_Error('Input fn_arr elements should be numpy arrays' 'with dtype {0}'.format(self._fn_dtype)) if self.fn_arr[0].dtype is not self._fn_dtype: raise Script_File_Error('fn_arr.dtype needs to be {0}'.format(self._fn_dtype)) print self.fn_arr @property def nout(self): if self.fn_arr is not None: self._nout = len(np.where(self.fn_arr[0]['rr']==False)[0])-2 else: print 'fn_arr is None, set nout to 0' self._nout = 0 return self._nout @property def npcs(self): if self.fn_arr is not None: self._npcs = len(self.fn_arr) else: print 'fn_arr is None, set npcs to 0' self._npcs = 0 return self._npcs @property def nref(self): if self.fn_arr is not None: num_ref = np.where(self.fn_arr[0]['rr'] == True)[0] self._nref = len(num_ref) else: print 'fn_arr is None, set nref to 0' self._nref = 0 if self._nref > 3: self.nr2 = self.fn_arr[0]['rr_num'].max() return self._nref @property def comp_list(self): num_comp = self.ninp+self.nout if num_comp == 4: self._comp_list = ['ex', 'ey', 'hx', 'hy'] elif num_comp == 5: self._comp_list = ['ex', 'ey', 'hz', 'hx', 'hy'] else: raise ValueError('Number of components {0} invalid, check inputs'.format(num_comp)) if self.nref == 0: self._comp_list += ['hx', 'hy'] else: for ii in range(int(self.nref/2)): self._comp_list += ['rrhx_{0:02}'.format(ii+1), 'rrhy_{0:02}'.format(ii+1)] return self._comp_list def write_script_file(self, script_fn=None, ofil=None): if ofil is not None: self.ofil = ofil if script_fn is not None: self.script_fn = script_fn # be sure all the parameters are correct according to BIRRP self.nout self.nref self.npcs self.comp_list self._validate_parameters() # begin writing script file s_lines = [] s_lines += ['{0:0.0f}'.format(self.ilev)] s_lines += ['{0:0.0f}'.format(self.nout)] s_lines += ['{0:0.0f}'.format(self.ninp)] if self.ilev == 0: s_lines += ['{0:.3f}'.format(self.tbw)] s_lines += ['{0:.3f}'.format(self.deltat)] s_lines += ['{0:0.0f},{1:0.0f}'.format(self.nfft, self.nsctmax)] s_lines += ['y'] s_lines += ['{0:.5f},{1:.5f}'.format(self.uin, self.ainuin)] s_lines += ['{0:.3f}'.format(self.c2threshe)] #parameters for bz component if ninp=3 if self.nout == 3: if self.c2threshe == 0: s_lines += ['{0:0.0f}'.format(0)] s_lines += ['{0:.3f}'.format(self.c2threshe1)] else: s_lines += ['{0:0.0f}'.format(self.nz)] s_lines += ['{0:.3f}'.format(self.c2threshe1)] else: pass s_lines += [self.ofil] s_lines += ['{0:0.0f}'.format(self.nlev)] elif self.ilev == 1: print 'Writing Advanced mode' s_lines += ['{0:0.0f}'.format(self.nref)] if self.nref > 3: s_lines += ['{0:0.0f},{1:0.0f}'.format(self.nr3, self.nr2)] s_lines += ['{0:0.0f}'.format(self.nrr)] s_lines += ['{0:.3f}'.format(self.tbw)] s_lines += ['{0:.3f}'.format(self.deltat)] s_lines += ['{0:0.0f},{1:.2g},{2:0.0f}'.format(self.nfft, self.nsctinc, self.nsctmax)] s_lines += ['{0:0.0f},{1:.2g},{2:0.0f}'.format(self.nf1, self.nfinc, self.nfsect)] s_lines += ['y'] s_lines += ['{0:.2g}'.format(self.mfft)] s_lines += ['{0:.5g},{1:.5g},{2:.5g}'.format(self.uin, self.ainlin, self.ainuin)] #if remote referencing if int(self.nrr) == 0: s_lines += ['{0:.3f}'.format(self.c2threshe)] #parameters for bz component if ninp=3 if self.nout == 3: if self.c2threshe != 0: s_lines += ['{0:0.0f}'.format(self.nz)] s_lines += ['{0:.3f}'.format(self.c2threshe1)] else: s_lines += ['{0:0.0f}'.format(0)] s_lines += ['{0:.3f}'.format(self.c2threshe1)] if self.c2threshe1 != 0.0 or self.c2threshe != 0.0: s_lines += ['{0:.6g},{1:.6g}'.format(self.perlo, self.perhi)] else: if self.c2threshe != 0.0: s_lines += ['{0:.6g},{1:.6g}'.format(self.perlo, self.perhi)] #if 2 stage processing elif int(self.nrr) == 1: s_lines += ['{0:.3f}'.format(self.c2threshb)] s_lines += ['{0:.3f}'.format(self.c2threshe)] if self.nout == 3: if self.c2threshb != 0 or self.c2threshe != 0: s_lines += ['{0:0.0f}'.format(self.nz)] s_lines += ['{0:.3f}'.format(self.c2threshe1)] elif self.c2threshb == 0 and self.c2threshe == 0: s_lines += ['{0:0.0f}'.format(0)] s_lines += ['{0:.3f}'.format(0)] if self.c2threshb != 0.0 or self.c2threshe != 0.0: s_lines += ['{0:.6g},{1:.6g}'.format(self.perlo, self.perhi)] s_lines += [self.ofil] s_lines += ['{0:0.0f}'.format(self.nlev)] s_lines += ['{0:0.0f}'.format(self.nprej)] if self.nprej != 0: if type(self.prej) is not list: self.prej = [self.prej] s_lines += ['{0:.5g}'.format(nn) for nn in self.prej] s_lines += ['{0:0.0f}'.format(self.npcs)] s_lines += ['{0:0.0f}'.format(self.nar)] s_lines += ['{0:0.0f}'.format(self.imode)] s_lines += ['{0:0.0f}'.format(self.jmode)] #write in filenames if self.jmode == 0: # loop over each data block for ff, fn_arr in enumerate(self.fn_arr): # get the least amount of data points to read s_lines += ['{0:0.0f}'.format(fn_arr['nread'].min())] for cc in self.comp_list: if 'rr' in cc: rr_num = int(cc[5:]) rr = True cc = cc[2:4] else: rr = False rr_num = 0 try: fn_index = np.where((fn_arr['comp']==cc) & \ (fn_arr['rr']==rr) & \ (fn_arr['rr_num']==rr_num))[0][0] except IndexError: print 'Something a miss with remote reference' print self.comp_list print len(np.where(fn_arr['rr']==True)[0]) print fn_arr['fn'] print self.nref raise ValueError('Fuck!') if ff == 0: fn_lines = self.make_fn_lines_block_00(fn_arr[fn_index]) else: fn_lines = self.make_fn_lines_block_n(fn_arr[fn_index]) s_lines += fn_lines #write rotation angles s_lines += [' '.join(['{0:.2f}'.format(theta) for theta in self.thetae])] s_lines += [' '.join(['{0:.2f}'.format(theta) for theta in self.thetab])] s_lines += [' '.join(['{0:.2f}'.format(theta) for theta in self.thetaf])] if self.nref > 3: for kk in range(self.nref): s_lines += [' '.join(['{0:.2f}'.format(theta) for theta in self.thetab])] with open(self.script_fn, 'w') as fid: fid.write('\n'.join(s_lines)) print 'Wrote script file to {0}'.format(self.script_fn) def make_fn_lines_block_00(self, fn_arr): """ make lines for file in script file which includes - nread - filter_fn - fn - nskip """ lines = [] if fn_arr['calibration_fn'] in ['', 0]: lines += ['0'] else: lines += ['-2'] lines += [fn_arr['calibration_fn']] lines += [fn_arr['fn']] lines += ['{0:d}'.format(fn_arr['nskip'])] return lines def make_fn_lines_block_n(self, fn_arr): """ make lines for file in script file which includes - nread - filter_fn - fn - nskip """ lines = [] lines += [fn_arr['fn']] lines += ['{0:d}'.format(fn_arr['nskip'])] return lines #============================================================================== # run birrp #============================================================================== def run(birrp_exe, script_file): """ run a birrp script file from command line via python subprocess. Arguments -------------- **birrp_exe** : string full path to the compiled birrp executable **script_file** : string full path to input script file following the guidelines of the BIRRP documentation. Outputs --------------- **log_file.log** : a log file of how BIRRP ran .. seealso:: BIRRP Manual and publications by Chave and Thomson for more details on the parameters found at: http://www.whoi.edu/science/AOPE/people/achave/Site/Next1.html """ # check to make sure the given executable is legit if not os.path.isfile(birrp_exe): raise mtex.MTpyError_inputarguments('birrp executable not found:'+ '{0}'.format(birrp_exe)) # get the current working directory so we can go back to it later current_dir = os.path.abspath(os.curdir) #change directory to directory of the script file os.chdir(os.path.dirname(script_file)) local_script_fn = os.path.basename(script_file) print os.getcwd() # # get an input string for communicating with the birrp executable # with open(script_file, 'r') as sfid: # input_string = ''.join(sfid.readlines()) # # #correct inputstring for potential errorneous line endings due to strange # #operating systems: # temp_string = input_string.split() # temp_string = [i.strip() for i in temp_string] # input_string = '\n'.join(temp_string) # input_string += '\n' #open a log file to catch process and errors of BIRRP executable #log_file = open('birrp_logfile.log','w') print '*'*10 print 'Processing {0} with {1}'.format(script_file, birrp_exe) print 'Starting Birrp processing at {0}...'.format(time.ctime()) st = time.ctime() birrp_process = subprocess.Popen(birrp_exe+'< {0}'.format(local_script_fn), stdin=subprocess.PIPE, shell=True) # stdout=log_file, # stderr=log_file) birrp_process.wait() #log_file.close() print '_'*20 print 'Starting Birrp processing at {0}...'.format(st) print 'Endec Birrp processing at {0}...'.format(time.ctime()) #print 'Closed log file: {0}'.format(log_file.name) # # print 'Outputs: {0}'.format(out) # print 'Errors: {0}'.format(err) #go back to initial directory os.chdir(current_dir) print '\n{0} DONE !!! {0}\n'.format('='*20) #============================================================================== # Class to read j_file #============================================================================== class JFile(object): """ be able to read and write a j-file """ def __init__(self, j_fn=None): self._j_lines = None self._set_j_fn(j_fn) self.header_dict = None self.metadata_dict = None self.Z = None self.Tipper = None def _set_j_fn(self, j_fn): self._j_fn = j_fn self._get_j_lines() def _get_j_fn(self): return self._j_fn j_fn = property(_get_j_fn, _set_j_fn) def _get_j_lines(self): """ read in the j_file as a list of lines, put the lines in attribute _j_lines """ if self.j_fn is None: print 'j_fn is None' return if os.path.isfile(os.path.abspath(self.j_fn)) is False: raise IOError('Could not find {0}, check path'.format(self.j_fn)) self._validate_j_file() with open(self.j_fn, 'r') as fid: self._j_lines = fid.readlines() print 'read in {0}'.format(self.j_fn) def _validate_j_file(self): """ change the lat, lon, elev lines to something machine readable, if they are not. """ # need to remove any weird characters in lat, lon, elev with open(self.j_fn, 'r') as fid: j_str = fid.read() # change lat j_str = self._rewrite_line('latitude', j_str) # change lon j_str = self._rewrite_line('longitude', j_str) # change elev j_str = self._rewrite_line('elevation', j_str) with open(self.j_fn, 'w') as fid: fid.write(j_str) print 'rewrote j-file {0} to make lat, lon, elev float values'.format(self.j_fn) def _get_str_value(self, string): value = string.split('=')[1].strip() try: value = float(value) except ValueError: value = 0.0 return value def _rewrite_line(self, variable, file_str): variable_str = '>'+variable.upper() index_begin = file_str.find(variable_str) index_end = index_begin+file_str[index_begin:].find('\n') value = self._get_str_value(file_str[index_begin:index_end]) print 'Changed {0} to {1}'.format(variable.upper(), value) new_line = '{0} = {1:<.2f}'.format(variable_str, value) file_str = file_str[0:index_begin]+new_line+file_str[index_end:] return file_str def read_header(self): """ Parsing the header lines of a j-file to extract processing information. Input: - j-file as list of lines (output of readlines()) Output: - Dictionary with all parameters found """ if self._j_lines is None: print "specify a file with jfile.j_fn = path/to/j/file" header_lines = [j_line for j_line in self._j_lines if '#' in j_line] header_dict = {'title':header_lines[0][1:].strip()} fn_count = 0 theta_count = 0 # put the information into a dictionary for h_line in header_lines[1:]: # replace '=' with a ' ' to be sure that when split is called there is a # split, especially with filenames h_list = h_line[1:].strip().replace('=', ' ').split() # skip if there is only one element in the list if len(h_list) == 1: continue # get the key and value for each parameter in the given line for h_index in range(0, len(h_list), 2): h_key = h_list[h_index] # if its the file name, make the dictionary value be a list so that # we can append nread and nskip to it, and make the name unique by # adding a counter on the end if h_key == 'filnam': h_key = '{0}_{1:02}'.format(h_key, fn_count) fn_count += 1 h_value = [h_list[h_index+1]] header_dict[h_key] = h_value continue elif h_key == 'nskip' or h_key == 'nread': h_key = 'filnam_{0:02}'.format(fn_count-1) h_value = int(h_list[h_index+1]) header_dict[h_key].append(h_value) # if its the line of angles, put them all in a list with a unique key elif h_key == 'theta1': h_key = '{0}_{1:02}'.format(h_key, theta_count) theta_count += 1 h_value = float(h_list[h_index+1]) header_dict[h_key] = [h_value] elif h_key == 'theta2' or h_key == 'phi': h_key = '{0}_{1:02}'.format('theta1', theta_count-1) h_value = float(h_list[h_index+1]) header_dict[h_key].append(h_value) else: try: h_value = float(h_list[h_index+1]) except ValueError: h_value = h_list[h_index+1] header_dict[h_key] = h_value self.header_dict = header_dict def read_metadata(self, j_lines=None, j_fn=None): """ read in the metadata of the station, or information of station logistics like: lat, lon, elevation Not really needed for a birrp output since all values are nan's """ if self._j_lines is None: print "specify a file with jfile.j_fn = path/to/j/file" metadata_lines = [j_line for j_line in self._j_lines if '>' in j_line] metadata_dict = {} for m_line in metadata_lines: m_list = m_line.strip().split('=') m_key = m_list[0][1:].strip().lower() try: m_value = float(m_list[0].strip()) except ValueError: m_value = 0.0 metadata_dict[m_key] = m_value self.metadata_dict = metadata_dict def read_j_file(self): """ read_j_file will read in a *.j file output by BIRRP (better than reading lots of *.<k>r<l>.rf files) Input: j-filename Output: 4-tuple - periods : N-array - Z_array : 2-tuple - values and errors - tipper_array : 2-tuple - values and errors - processing_dict : parsed processing parameters from j-file header """ # read data z_index_dict = {'zxx':(0, 0), 'zxy':(0, 1), 'zyx':(1, 0), 'zyy':(1, 1)} t_index_dict = {'tzx':(0, 0), 'tzy':(0, 1)} if self._j_lines is None: print "specify a file with jfile.j_fn = path/to/j/file" self.read_header() self.read_metadata() data_lines = [j_line for j_line in self._j_lines if not '>' in j_line and not '#' in j_line][1:] # sometimes birrp outputs some missing periods, so the best way to deal with # this that I could come up with was to get things into dictionaries with # key words that are the period values, then fill in Z and T from there # leaving any missing values as 0 # make empty dictionary that have keys as the component z_dict = dict([(z_key, {}) for z_key in z_index_dict.keys()]) t_dict = dict([(t_key, {}) for t_key in t_index_dict.keys()]) for d_line in data_lines: # check to see if we are at the beginning of a component block, if so # set the dictionary key to that value if 'z' in d_line.lower(): d_key = d_line.strip().split()[0].lower() # if we are at the number of periods line, skip it elif len(d_line.strip().split()) == 1 and 'r' not in d_line.lower(): continue elif 'r' in d_line.lower(): break # get the numbers into the correct dictionary with a key as period and # for now we will leave the numbers as a list, which we will parse later else: # split the line up into each number d_list = d_line.strip().split() # make a copy of the list to be sure we don't rewrite any values, # not sure if this is necessary at the moment d_value_list = list(d_list) for d_index, d_value in enumerate(d_list): # check to see if the column number can be converted into a float # if it can't, then it will be set to 0, which is assumed to be # a masked number when writing to an .edi file try: d_value = float(d_value) # need to check for masked points represented by # birrp as -999, apparently if d_value == -999 or np.isnan(d_value): d_value_list[d_index] = 0.0 else: d_value_list[d_index] = d_value except ValueError: d_value_list[d_index] = 0.0 # put the numbers in the correct dictionary as: # key = period, value = [real, imaginary, error] if d_key in z_index_dict.keys(): z_dict[d_key][d_value_list[0]] = d_value_list[1:4] elif d_key in t_index_dict.keys(): t_dict[d_key][d_value_list[0]] = d_value_list[1:4] # --> now we need to get the set of periods for all components # check to see if there is any tipper data output all_periods = [] for z_key in z_index_dict.keys(): for f_key in z_dict[z_key].keys(): all_periods.append(f_key) if len(t_dict['tzx'].keys()) == 0: print 'Could not find any Tipper data in {0}'.format(self.j_fn) find_tipper = False else: for t_key in t_index_dict.keys(): for f_key in t_dict[t_key].keys(): all_periods.append(f_key) find_tipper = True all_periods = np.array(sorted(list(set(all_periods)))) all_periods = all_periods[np.nonzero(all_periods)] num_per = len(all_periods) # fill arrays using the period key from all_periods z_arr = np.zeros((num_per, 2, 2), dtype=np.complex) z_err_arr = np.zeros((num_per, 2, 2), dtype=np.float) t_arr = np.zeros((num_per, 1, 2), dtype=np.complex) t_err_arr = np.zeros((num_per, 1, 2), dtype=np.float) for p_index, per in enumerate(all_periods): for z_key in sorted(z_index_dict.keys()): kk = z_index_dict[z_key][0]
[ " ll = z_index_dict[z_key][1]" ]
3,693
lcc
python
null
fbd2ce3fa32ecbd53cedd8e6e94c4011c99d452dc926cd2e
package org.thoughtcrime.securesms.util; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.annotation.UiThread; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.storage.TextSecureIdentityKeyStore; import org.thoughtcrime.securesms.crypto.storage.TextSecureSessionStore; import org.thoughtcrime.securesms.database.Address; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.GroupDatabase; import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.database.IdentityDatabase.IdentityRecord; import org.thoughtcrime.securesms.database.MessagingDatabase.InsertResult; import org.thoughtcrime.securesms.database.SmsDatabase; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.sms.IncomingIdentityDefaultMessage; import org.thoughtcrime.securesms.sms.IncomingIdentityUpdateMessage; import org.thoughtcrime.securesms.sms.IncomingIdentityVerifiedMessage; import org.thoughtcrime.securesms.sms.IncomingTextMessage; import org.thoughtcrime.securesms.sms.OutgoingIdentityDefaultMessage; import org.thoughtcrime.securesms.sms.OutgoingIdentityVerifiedMessage; import org.thoughtcrime.securesms.sms.OutgoingTextMessage; import org.thoughtcrime.securesms.util.concurrent.ListenableFuture; import org.thoughtcrime.securesms.util.concurrent.SettableFuture; import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.SignalProtocolAddress; import org.whispersystems.libsignal.state.IdentityKeyStore; import org.whispersystems.libsignal.state.SessionRecord; import org.whispersystems.libsignal.state.SessionStore; import org.whispersystems.libsignal.util.guava.Optional; import org.whispersystems.signalservice.api.messages.SignalServiceGroup; import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage; import java.util.List; import static org.whispersystems.libsignal.SessionCipher.SESSION_LOCK; public class IdentityUtil { private static final String TAG = IdentityUtil.class.getSimpleName(); @SuppressLint("StaticFieldLeak") @UiThread public static ListenableFuture<Optional<IdentityRecord>> getRemoteIdentityKey(final Context context, final Recipient recipient) { final SettableFuture<Optional<IdentityRecord>> future = new SettableFuture<>(); new AsyncTask<Recipient, Void, Optional<IdentityRecord>>() { @Override protected Optional<IdentityRecord> doInBackground(Recipient... recipient) { return DatabaseFactory.getIdentityDatabase(context) .getIdentity(recipient[0].getAddress()); } @Override protected void onPostExecute(Optional<IdentityRecord> result) { future.set(result); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, recipient); return future; } public static void markIdentityVerified(Context context, Recipient recipient, boolean verified, boolean remote) { long time = System.currentTimeMillis(); SmsDatabase smsDatabase = DatabaseFactory.getSmsDatabase(context); GroupDatabase groupDatabase = DatabaseFactory.getGroupDatabase(context); GroupDatabase.Reader reader = groupDatabase.getGroups(); GroupDatabase.GroupRecord groupRecord; while ((groupRecord = reader.getNext()) != null) { if (groupRecord.getMembers().contains(recipient.getAddress()) && groupRecord.isActive() && !groupRecord.isMms()) { SignalServiceGroup group = new SignalServiceGroup(groupRecord.getId()); if (remote) { IncomingTextMessage incoming = new IncomingTextMessage(recipient.getAddress(), 1, time, null, Optional.of(group), 0, false); if (verified) incoming = new IncomingIdentityVerifiedMessage(incoming); else incoming = new IncomingIdentityDefaultMessage(incoming); smsDatabase.insertMessageInbox(incoming); } else { Recipient groupRecipient = Recipient.from(context, Address.fromSerialized(GroupUtil.getEncodedId(group.getGroupId(), false)), true); long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(groupRecipient); OutgoingTextMessage outgoing ; if (verified) outgoing = new OutgoingIdentityVerifiedMessage(recipient); else outgoing = new OutgoingIdentityDefaultMessage(recipient); DatabaseFactory.getSmsDatabase(context).insertMessageOutbox(threadId, outgoing, false, time, null); } } } if (remote) { IncomingTextMessage incoming = new IncomingTextMessage(recipient.getAddress(), 1, time, null, Optional.absent(), 0, false); if (verified) incoming = new IncomingIdentityVerifiedMessage(incoming); else incoming = new IncomingIdentityDefaultMessage(incoming); smsDatabase.insertMessageInbox(incoming); } else { OutgoingTextMessage outgoing; if (verified) outgoing = new OutgoingIdentityVerifiedMessage(recipient); else outgoing = new OutgoingIdentityDefaultMessage(recipient); long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipient); Log.i(TAG, "Inserting verified outbox..."); DatabaseFactory.getSmsDatabase(context).insertMessageOutbox(threadId, outgoing, false, time, null); } } public static void markIdentityUpdate(Context context, Recipient recipient) { long time = System.currentTimeMillis(); SmsDatabase smsDatabase = DatabaseFactory.getSmsDatabase(context); GroupDatabase groupDatabase = DatabaseFactory.getGroupDatabase(context); GroupDatabase.Reader reader = groupDatabase.getGroups(); GroupDatabase.GroupRecord groupRecord; while ((groupRecord = reader.getNext()) != null) { if (groupRecord.getMembers().contains(recipient.getAddress()) && groupRecord.isActive()) { SignalServiceGroup group = new SignalServiceGroup(groupRecord.getId()); IncomingTextMessage incoming = new IncomingTextMessage(recipient.getAddress(), 1, time, null, Optional.of(group), 0, false); IncomingIdentityUpdateMessage groupUpdate = new IncomingIdentityUpdateMessage(incoming); smsDatabase.insertMessageInbox(groupUpdate); } } IncomingTextMessage incoming = new IncomingTextMessage(recipient.getAddress(), 1, time, null, Optional.absent(), 0, false); IncomingIdentityUpdateMessage individualUpdate = new IncomingIdentityUpdateMessage(incoming); Optional<InsertResult> insertResult = smsDatabase.insertMessageInbox(individualUpdate); if (insertResult.isPresent()) { MessageNotifier.updateNotification(context, insertResult.get().getThreadId()); } } public static void saveIdentity(Context context, String number, IdentityKey identityKey) { synchronized (SESSION_LOCK) { IdentityKeyStore identityKeyStore = new TextSecureIdentityKeyStore(context); SessionStore sessionStore = new TextSecureSessionStore(context); SignalProtocolAddress address = new SignalProtocolAddress(number, 1); if (identityKeyStore.saveIdentity(address, identityKey)) { if (sessionStore.containsSession(address)) { SessionRecord sessionRecord = sessionStore.loadSession(address); sessionRecord.archiveCurrentState(); sessionStore.storeSession(address, sessionRecord); } } } } public static void processVerifiedMessage(Context context, VerifiedMessage verifiedMessage) { synchronized (SESSION_LOCK) { IdentityDatabase identityDatabase = DatabaseFactory.getIdentityDatabase(context); Recipient recipient = Recipient.from(context, Address.fromExternal(context, verifiedMessage.getDestination()), true); Optional<IdentityRecord> identityRecord = identityDatabase.getIdentity(recipient.getAddress()); if (!identityRecord.isPresent() && verifiedMessage.getVerified() == VerifiedMessage.VerifiedState.DEFAULT) { Log.w(TAG, "No existing record for default status"); return; } if (verifiedMessage.getVerified() == VerifiedMessage.VerifiedState.DEFAULT && identityRecord.isPresent() && identityRecord.get().getIdentityKey().equals(verifiedMessage.getIdentityKey()) && identityRecord.get().getVerifiedStatus() != IdentityDatabase.VerifiedStatus.DEFAULT) { identityDatabase.setVerified(recipient.getAddress(), identityRecord.get().getIdentityKey(), IdentityDatabase.VerifiedStatus.DEFAULT); markIdentityVerified(context, recipient, false, true); } if (verifiedMessage.getVerified() == VerifiedMessage.VerifiedState.VERIFIED && (!identityRecord.isPresent() || (identityRecord.isPresent() && !identityRecord.get().getIdentityKey().equals(verifiedMessage.getIdentityKey())) || (identityRecord.isPresent() && identityRecord.get().getVerifiedStatus() != IdentityDatabase.VerifiedStatus.VERIFIED))) { saveIdentity(context, verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()); identityDatabase.setVerified(recipient.getAddress(), verifiedMessage.getIdentityKey(), IdentityDatabase.VerifiedStatus.VERIFIED); markIdentityVerified(context, recipient, true, true); } } } public static @Nullable String getUnverifiedBannerDescription(@NonNull Context context, @NonNull List<Recipient> unverified) { return getPluralizedIdentityDescription(context, unverified, R.string.IdentityUtil_unverified_banner_one, R.string.IdentityUtil_unverified_banner_two, R.string.IdentityUtil_unverified_banner_many); } public static @Nullable String getUnverifiedSendDialogDescription(@NonNull Context context, @NonNull List<Recipient> unverified) { return getPluralizedIdentityDescription(context, unverified, R.string.IdentityUtil_unverified_dialog_one, R.string.IdentityUtil_unverified_dialog_two, R.string.IdentityUtil_unverified_dialog_many); } public static @Nullable String getUntrustedSendDialogDescription(@NonNull Context context, @NonNull List<Recipient> untrusted) { return getPluralizedIdentityDescription(context, untrusted, R.string.IdentityUtil_untrusted_dialog_one, R.string.IdentityUtil_untrusted_dialog_two, R.string.IdentityUtil_untrusted_dialog_many); } private static @Nullable String getPluralizedIdentityDescription(@NonNull Context context, @NonNull List<Recipient> recipients, @StringRes int resourceOne, @StringRes int resourceTwo, @StringRes int resourceMany) { if (recipients.isEmpty()) return null; if (recipients.size() == 1) { String name = recipients.get(0).toShortString();
[ " return context.getString(resourceOne, name);" ]
625
lcc
java
null
952e4fb549d3a952e37556b53313cdbf932f75f456f15901
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. import os from os import path import contextlib import subprocess from subprocess import PIPE import sys import toml from mach.registrar import Registrar @contextlib.contextmanager def cd(new_path): """Context manager for changing the current working directory""" previous_path = os.getcwd() try: os.chdir(new_path) yield finally: os.chdir(previous_path) def host_triple(): os_type = subprocess.check_output(["uname", "-s"]).strip().lower() if os_type == "linux": os_type = "unknown-linux-gnu" elif os_type == "darwin": os_type = "apple-darwin" elif os_type == "android": os_type = "linux-androideabi" else: os_type = "unknown" cpu_type = subprocess.check_output(["uname", "-m"]).strip().lower() if cpu_type in ["i386", "i486", "i686", "i768", "x86"]: cpu_type = "i686" elif cpu_type in ["x86_64", "x86-64", "x64", "amd64"]: cpu_type = "x86_64" elif cpu_type == "arm": cpu_type = "arm" else: cpu_type = "unknown" return "%s-%s" % (cpu_type, os_type) class CommandBase(object): """Base class for mach command providers. This mostly handles configuration management, such as .servobuild.""" def __init__(self, context): self.context = context def resolverelative(category, key): # Allow ~ self.config[category][key] = path.expanduser(self.config[category][key]) # Resolve relative paths self.config[category][key] = path.join(context.topdir, self.config[category][key]) if not hasattr(self.context, "bootstrapped"): self.context.bootstrapped = False config_path = path.join(context.topdir, ".servobuild") if path.exists(config_path): with open(config_path) as f: self.config = toml.loads(f.read()) else: self.config = {} # Handle missing/default items self.config.setdefault("tools", {}) default_cache_dir = os.environ.get("SERVO_CACHE_DIR", path.join(context.topdir, ".servo")) self.config["tools"].setdefault("cache-dir", default_cache_dir) resolverelative("tools", "cache-dir") self.config["tools"].setdefault("cargo-home-dir", path.join(context.topdir, ".cargo")) resolverelative("tools", "cargo-home-dir") context.sharedir = self.config["tools"]["cache-dir"] self.config["tools"].setdefault("system-rust", False) self.config["tools"].setdefault("system-cargo", False) self.config["tools"].setdefault("rust-root", "") self.config["tools"].setdefault("cargo-root", "") if not self.config["tools"]["system-rust"]: self.config["tools"]["rust-root"] = path.join( context.sharedir, "rust", self.rust_snapshot_path()) if not self.config["tools"]["system-cargo"]: self.config["tools"]["cargo-root"] = path.join( context.sharedir, "cargo", self.cargo_build_id()) self.config["tools"].setdefault("rustc-with-gold", True) self.config.setdefault("build", {}) self.config["build"].setdefault("android", False) self.config["build"].setdefault("mode", "") self.config["build"].setdefault("debug-mozjs", False) self.config["build"].setdefault("ccache", "") self.config.setdefault("android", {}) self.config["android"].setdefault("sdk", "") self.config["android"].setdefault("ndk", "") self.config["android"].setdefault("toolchain", "") self.config["android"].setdefault("target", "arm-linux-androideabi") self.config.setdefault("gonk", {}) self.config["gonk"].setdefault("b2g", "") self.config["gonk"].setdefault("product", "flame") _rust_snapshot_path = None _cargo_build_id = None def rust_snapshot_path(self): if self._rust_snapshot_path is None: filename = path.join(self.context.topdir, "rust-snapshot-hash") with open(filename) as f: snapshot_hash = f.read().strip() self._rust_snapshot_path = ("%s/rustc-nightly-%s" % (snapshot_hash, host_triple())) return self._rust_snapshot_path def cargo_build_id(self): if self._cargo_build_id is None: filename = path.join(self.context.topdir, "cargo-nightly-build") with open(filename) as f: self._cargo_build_id = f.read().strip() return self._cargo_build_id def get_top_dir(self): return self.context.topdir def get_target_dir(self): if "CARGO_TARGET_DIR" in os.environ: return os.environ["CARGO_TARGET_DIR"] else: return path.join(self.context.topdir, "target") def get_binary_path(self, release, dev, android=False): base_path = self.get_target_dir() if android: base_path = path.join(base_path, self.config["android"]["target"]) release_path = path.join(base_path, "release", "servo") dev_path = path.join(base_path, "debug", "servo") # Prefer release if both given if release and dev: dev = False release_exists = path.exists(release_path) dev_exists = path.exists(dev_path) if not release_exists and not dev_exists: print("No Servo binary found. Please run './mach build' and try again.") sys.exit() if release and release_exists: return release_path if dev and dev_exists: return dev_path if not dev and not release and release_exists and dev_exists: print("You have multiple profiles built. Please specify which " "one to run with '--release' or '--dev'.") sys.exit() if not dev and not release: if release_exists: return release_path else: return dev_path print("The %s profile is not built. Please run './mach build%s' " "and try again." % ("release" if release else "dev", " --release" if release else "")) sys.exit() def build_env(self, gonk=False, hosts_file_path=None): """Return an extended environment dictionary.""" env = os.environ.copy() extra_path = [] extra_lib = [] if not self.config["tools"]["system-rust"] \ or self.config["tools"]["rust-root"]: env["RUST_ROOT"] = self.config["tools"]["rust-root"] # These paths are for when rust-root points to an unpacked installer extra_path += [path.join(self.config["tools"]["rust-root"], "rustc", "bin")] extra_lib += [path.join(self.config["tools"]["rust-root"], "rustc", "lib")] # These paths are for when rust-root points to a rustc sysroot extra_path += [path.join(self.config["tools"]["rust-root"], "bin")] extra_lib += [path.join(self.config["tools"]["rust-root"], "lib")] if not self.config["tools"]["system-cargo"] \ or self.config["tools"]["cargo-root"]: # This path is for when rust-root points to an unpacked installer extra_path += [ path.join(self.config["tools"]["cargo-root"], "cargo", "bin")] # This path is for when rust-root points to a rustc sysroot extra_path += [ path.join(self.config["tools"]["cargo-root"], "bin")] if extra_path:
[ " env[\"PATH\"] = \"%s%s%s\" % (" ]
635
lcc
python
null
d5aeb3ac7b9ce924600b49b84fc825d3230cb90e4711eb37
import json import os import re from collections import defaultdict from six import iteritems, itervalues, viewkeys from .item import ManualTest, WebdriverSpecTest, Stub, RefTestNode, RefTest, TestharnessTest, SupportFile, ConformanceCheckerTest, VisualTest from .log import get_logger from .utils import from_os_path, to_os_path, rel_path_to_url CURRENT_VERSION = 4 class ManifestError(Exception): pass class ManifestVersionMismatch(ManifestError): pass def sourcefile_items(args): tests_root, url_base, rel_path, status = args source_file = SourceFile(tests_root, rel_path, url_base) return rel_path, source_file.manifest_items() class Manifest(object): def __init__(self, url_base="/"): assert url_base is not None self._path_hash = {} self._data = defaultdict(dict) self._reftest_nodes_by_url = None self.url_base = url_base def __iter__(self): return self.itertypes() def itertypes(self, *types): if not types: types = sorted(self._data.keys()) for item_type in types: for path, tests in sorted(iteritems(self._data[item_type])): yield item_type, path, tests def iterpath(self, path): for type_tests in self._data.values(): for test in type_tests.get(path, set()): yield test def iterdir(self, dir_name): if not dir_name.endswith(os.path.sep): dir_name = dir_name + os.path.sep for type_tests in self._data.values(): for path, tests in type_tests.iteritems(): if path.startswith(dir_name): for test in tests: yield test @property def reftest_nodes_by_url(self): if self._reftest_nodes_by_url is None: by_url = {} for path, nodes in iteritems(self._data.get("reftests", {})): for node in nodes: by_url[node.url] = node self._reftest_nodes_by_url = by_url return self._reftest_nodes_by_url def get_reference(self, url): return self.reftest_nodes_by_url.get(url) def update(self, tree): new_data = defaultdict(dict) new_hashes = {} reftest_nodes = [] old_files = defaultdict(set, {k: set(viewkeys(v)) for k, v in iteritems(self._data)}) changed = False reftest_changes = False for source_file in tree: rel_path = source_file.rel_path file_hash = source_file.hash is_new = rel_path not in self._path_hash hash_changed = False if not is_new: old_hash, old_type = self._path_hash[rel_path] old_files[old_type].remove(rel_path) if old_hash != file_hash: new_type, manifest_items = source_file.manifest_items() hash_changed = True else: new_type, manifest_items = old_type, self._data[old_type][rel_path] else: new_type, manifest_items = source_file.manifest_items() if new_type in ("reftest", "reftest_node"): reftest_nodes.extend(manifest_items) if is_new or hash_changed: reftest_changes = True elif new_type: new_data[new_type][rel_path] = set(manifest_items) new_hashes[rel_path] = (file_hash, new_type) if is_new or hash_changed: changed = True if reftest_changes or old_files["reftest"] or old_files["reftest_node"]: reftests, reftest_nodes, changed_hashes = self._compute_reftests(reftest_nodes) new_data["reftest"] = reftests new_data["reftest_node"] = reftest_nodes new_hashes.update(changed_hashes) else: new_data["reftest"] = self._data["reftest"] new_data["reftest_node"] = self._data["reftest_node"] if any(itervalues(old_files)): changed = True self._data = new_data self._path_hash = new_hashes return changed def _compute_reftests(self, reftest_nodes): self._reftest_nodes_by_url = {} has_inbound = set() for item in reftest_nodes: for ref_url, ref_type in item.references: has_inbound.add(ref_url) reftests = defaultdict(set) references = defaultdict(set) changed_hashes = {} for item in reftest_nodes: if item.url in has_inbound: # This is a reference if isinstance(item, RefTest): item = item.to_RefTestNode() changed_hashes[item.source_file.rel_path] = (item.source_file.hash, item.item_type) references[item.source_file.rel_path].add(item) self._reftest_nodes_by_url[item.url] = item else: if isinstance(item, RefTestNode): item = item.to_RefTest() changed_hashes[item.source_file.rel_path] = (item.source_file.hash, item.item_type) reftests[item.source_file.rel_path].add(item) return reftests, references, changed_hashes def to_json(self): out_items = { test_type: { from_os_path(path): [t for t in sorted(test.to_json() for test in tests)] for path, tests in iteritems(type_paths) } for test_type, type_paths in iteritems(self._data) } rv = {"url_base": self.url_base, "paths": {from_os_path(k): v for k, v in iteritems(self._path_hash)}, "items": out_items, "version": CURRENT_VERSION} return rv @classmethod def from_json(cls, tests_root, obj): version = obj.get("version") if version != CURRENT_VERSION: raise ManifestVersionMismatch self = cls(url_base=obj.get("url_base", "/")) if not hasattr(obj, "items") and hasattr(obj, "paths"): raise ManifestError self._path_hash = {to_os_path(k): v for k, v in iteritems(obj["paths"])} item_classes = {"testharness": TestharnessTest, "reftest": RefTest, "reftest_node": RefTestNode, "manual": ManualTest, "stub": Stub, "wdspec": WebdriverSpecTest, "conformancechecker": ConformanceCheckerTest, "visual": VisualTest, "support": SupportFile} source_files = {} for test_type, type_paths in iteritems(obj["items"]): if test_type not in item_classes: raise ManifestError test_cls = item_classes[test_type] tests = defaultdict(set)
[ " for path, manifest_tests in iteritems(type_paths):" ]
530
lcc
python
null
94a45bef4dfbdc205ca29907ce87ecff9c3d6548141c05a7
/* * Freeplane - mind map editor * Copyright (C) 2012 Dimitry * * This file author is Dimitry * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.plugin.script; import java.io.File; import java.io.PrintStream; import java.security.AccessControlException; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.regex.Matcher; import javax.swing.SwingUtilities; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.customizers.ImportCustomizer; import org.codehaus.groovy.runtime.InvokerHelper; import org.freeplane.features.map.IMapSelection; import org.freeplane.features.map.NodeModel; import org.freeplane.features.mode.Controller; import org.freeplane.plugin.script.proxy.ScriptUtils; import groovy.lang.Binding; import groovy.lang.GroovyRuntimeException; import groovy.lang.Script; /** * Special scripting implementation for Groovy. */ public class GroovyScript implements IScript { final private Object script; private final ScriptingPermissions specificPermissions; private FreeplaneScriptBaseClass compiledScript; private Throwable errorsInScript; private CompileTimeStrategy compileTimeStrategy; private ScriptClassLoader scriptClassLoader; public GroovyScript(String script) { this((Object) script); } public GroovyScript(File script) { this((Object) script); compileTimeStrategy = new CompileTimeStrategy(script); } public GroovyScript(String script, ScriptingPermissions permissions) { this((Object) script, permissions); } public GroovyScript(File script, ScriptingPermissions permissions) { this((Object) script, permissions); compileTimeStrategy = new CompileTimeStrategy(script); } private GroovyScript(Object script, ScriptingPermissions permissions) { super(); this.script = script; this.specificPermissions = permissions; compiledScript = null; errorsInScript = null; compileTimeStrategy = new CompileTimeStrategy(null); } private GroovyScript(Object script) { this(script, null); } public Script getCompiledScript() { return compiledScript; } @Override public Object execute(final NodeModel node, PrintStream outStream, IFreeplaneScriptErrorHandler errorHandler, ScriptContext scriptContext) { try { if (errorsInScript != null && compileTimeStrategy.canUseOldCompiledScript()) { throw new ExecuteScriptException(errorsInScript.getMessage(), errorsInScript); } final PrintStream oldOut = System.out; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { trustedCompileAndCache(outStream); Thread.currentThread().setContextClassLoader(scriptClassLoader); FreeplaneScriptBaseClass scriptWithBinding = AccessController.doPrivileged(new PrivilegedAction<FreeplaneScriptBaseClass>() { @Override public FreeplaneScriptBaseClass run() { return compiledScript.withBinding(node, scriptContext); } }); System.setOut(outStream); final Object result = scriptWithBinding.run(); return result; } finally { System.setOut(oldOut); Thread.currentThread().setContextClassLoader(contextClassLoader); } } catch (final GroovyRuntimeException e) { handleScriptRuntimeException(e, outStream, errorHandler); // :fixme: This throw is only reached, if // handleScriptRuntimeException // does not raise an exception. Should it be here at all? // And if: Shouldn't it raise an ExecuteScriptException? throw new RuntimeException(e); } catch (final Throwable e) { IMapSelection selection = Controller.getCurrentController().getSelection(); if (selection != null && node != null && ! node.equals(selection.getSelected()) && node.hasVisibleContent()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Controller.getCurrentModeController().getMapController().select(node); } }); } throw new ExecuteScriptException(e.getMessage(), e); } } private ScriptingSecurityManager createScriptingSecurityManager(PrintStream outStream) { return new ScriptSecurity(script, specificPermissions, outStream) .getScriptingSecurityManager(); } private void trustedCompileAndCache(PrintStream outStream) throws Throwable { AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws PrivilegedActionException { try { final ScriptingSecurityManager scriptingSecurityManager = createScriptingSecurityManager(outStream); compileAndCache(scriptingSecurityManager); } catch (Exception e) { throw new PrivilegedActionException(e); } catch (Error e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } return null; } }); } private static boolean accessPermissionCheckerChecked = false; private Script compileAndCache(final ScriptingSecurityManager scriptingSecurityManager) throws Throwable { checkAccessPermissionCheckerExists(); if (compileTimeStrategy.canUseOldCompiledScript()) { scriptClassLoader.setSecurityManager(scriptingSecurityManager); return compiledScript; } removeOldScript(); errorsInScript = null; if (script instanceof Script) { return (Script) script; } else { try { final Binding binding = createBindingForCompilation(); scriptClassLoader = ScriptClassLoader.createClassLoader(); scriptClassLoader.setSecurityManager(scriptingSecurityManager); final GroovyShell shell = new GroovyShell(scriptClassLoader, binding, createCompilerConfiguration()); compileTimeStrategy.scriptCompileStart(); if (script instanceof String) { compiledScript = (FreeplaneScriptBaseClass) shell.parse((String) script); } else if (script instanceof File) { compiledScript = (FreeplaneScriptBaseClass) shell.parse((File) script); } else { throw new IllegalArgumentException(); } compiledScript.setScript(script); compileTimeStrategy.scriptCompiled(); return compiledScript; } catch (Throwable e) { errorsInScript = e; throw e; } } } static void checkAccessPermissionCheckerExists() { if(!accessPermissionCheckerChecked){ if(System.getSecurityManager() != null){ try { GroovyScript.class.getClassLoader().loadClass("org.codehaus.groovy.reflection.AccessPermissionChecker"); } catch (ClassNotFoundException e) { throw new AccessControlException("class org.codehaus.groovy.reflection.AccessPermissionChecker not found"); } } accessPermissionCheckerChecked = true; } } private void removeOldScript() {
[ " if (compiledScript != null) {" ]
651
lcc
java
null
8c9bb2b76a046b253799f5ca041ded912c0cd8fc4381f3c1
// CANAPE Network Testing Tool // Copyright (C) 2014 Context Information Security // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using CANAPE.DataAdapters; using CANAPE.DataFrames; using CANAPE.Utils; namespace CANAPE.Net.Layers { /// <summary> /// Simpler dynamic base network layer class, makes it easier to implement in a class and for python /// </summary> /// <typeparam name="T">Type of configuration</typeparam> /// <typeparam name="R">Type to reference configuration</typeparam> public abstract class WrappedNetworkLayer<T, R> : BaseNetworkLayer<T, R> where R : class where T : class, R, new() { private class WrapperServerDataAdapter : IDataAdapter { WrappedNetworkLayer<T,R> _networkLayer; string _description; public WrapperServerDataAdapter(WrappedNetworkLayer<T, R> networkLayer, string description) { _networkLayer = networkLayer; _description = description; } public DataFrame Read() { return _networkLayer.ServerRead(); } public void Write(DataFrame frame) { _networkLayer.ServerWrite(frame); } public void Close() { _networkLayer.ServerClose(); } public string Description { get { return _description; } } public int ReadTimeout { get { return _networkLayer.ServerGetTimeout(); } set { _networkLayer.ServerSetTimeout(value); } } public bool CanTimeout { get { return _networkLayer.ServerCanTimeout(); } } public void Dispose() { Close(); } public void Reconnect() { throw new NotImplementedException(); } } private class WrapperClientDataAdapter : IDataAdapter { WrappedNetworkLayer<T, R> _networkLayer; string _description; public WrapperClientDataAdapter(WrappedNetworkLayer<T, R> networkLayer, string description) { _networkLayer = networkLayer; _description = description; } public DataFrame Read() { return _networkLayer.ClientRead(); } public void Write(DataFrame frame) { _networkLayer.ClientWrite(frame); } public void Close() { _networkLayer.ClientClose(); } public string Description { get { return _description; } } public int ReadTimeout { get { return _networkLayer.ClientGetTimeout(); } set { _networkLayer.ClientSetTimeout(value); } } public bool CanTimeout { get { return _networkLayer.ClientCanTimeout(); } } public void Dispose() { Close(); } public void Reconnect() { throw new NotImplementedException(); } } /// <summary> /// Method to override writing for a wrapped client adapter /// </summary> /// <param name="frame">The wraper to write</param> protected abstract void ClientWrite(DataFrame frame); /// <summary> /// Method to override reading for a wrapped client adapter /// </summary> /// <returns>A data frame read from the adapter, null on end of stream</returns> protected abstract DataFrame ClientRead(); /// <summary> /// Method to override closing for a wrapped client adapter /// </summary> protected abstract void ClientClose(); /// <summary> /// Method to override setting a timeout for a wrapped client adapter /// </summary> /// <param name="timeout">The timeout in milliseconds</param> protected virtual void ClientSetTimeout(int timeout) { throw new NotSupportedException(); } /// <summary> /// Method to override getting a timeout for a wrapped client adapter /// </summary> /// <returns>The timeout in milliseconds</returns> protected virtual int ClientGetTimeout() { throw new NotSupportedException(); } /// <summary> /// Method to override indicating whether we can timeout or not /// </summary> /// <returns>True indicates a timeout can be set</returns> protected virtual bool ClientCanTimeout() { throw new NotSupportedException(); } /// <summary> /// Method to override writing for a wrapped server adapter /// </summary> /// <param name="frame">The frame to write</param> protected abstract void ServerWrite(DataFrame frame); /// <summary> /// Method to override reading for a wrapped server adapter /// </summary> /// <returns>A data frame read from the adapter, null on end of stream</returns> protected abstract DataFrame ServerRead(); /// <summary> /// Method to override setting a timeout for a wrapped server adapter /// </summary> /// <param name="timeout">The timeout in milliseconds</param> protected virtual void ServerSetTimeout(int timeout) { throw new NotSupportedException(); } /// <summary> /// Method to override getting a timeout for a wrapped client adapter /// </summary> /// <returns>The timeout in milliseconds</returns> protected virtual int ServerGetTimeout() {
[ " throw new NotSupportedException();" ]
659
lcc
csharp
null
a1513f998bc527a864d8e16254a66a40d622fcb15412fae3
""" Contains an abstract base class that supports data transformations. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import numpy as np import warnings from functools import partial from deepchem.utils.save import save_to_disk from deepchem.utils.save import load_from_disk from deepchem.utils import pad_array import shutil from deepchem.data import DiskDataset, NumpyDataset def undo_transforms(y, transformers): """Undoes all transformations applied.""" # Note that transformers have to be undone in reversed order for transformer in reversed(transformers): if transformer.transform_y: y = transformer.untransform(y) return y def undo_grad_transforms(grad, tasks, transformers): for transformer in reversed(transformers): if transformer.transform_y: grad = transformer.untransform_grad(grad, tasks) return grad def get_grad_statistics(dataset): """Computes and returns statistics of a dataset This function assumes that the first task of a dataset holds the energy for an input system, and that the remaining tasks holds the gradient for the system. """ if len(dataset) == 0: return None, None, None, None y = dataset.y energy = y[:,0] grad = y[:,1:] for i in range(energy.size): grad[i] *= energy[i] ydely_means = np.sum(grad, axis=0)/len(energy) return grad, ydely_means class Transformer(object): """ Abstract base class for different ML models. """ # Hack to allow for easy unpickling: # http://stefaanlippens.net/pickleproblem __module__ = os.path.splitext(os.path.basename(__file__))[0] def __init__(self, transform_X=False, transform_y=False, transform_w=False, dataset=None): """Initializes transformation based on dataset statistics.""" self.dataset = dataset self.transform_X = transform_X self.transform_y = transform_y self.transform_w = transform_w # One, but not both, transform_X or tranform_y is true assert transform_X or transform_y or transform_w # Use fact that bools add as ints in python assert (transform_X + transform_y + transform_w) == 1 def transform_array(self, X, y, w): """Transform the data in a set of (X, y, w) arrays.""" raise NotImplementedError( "Each Transformer is responsible for its own transform_array method.") def untransform(self, z): """Reverses stored transformation on provided data.""" raise NotImplementedError( "Each Transformer is responsible for its own untransfomr method.") def transform(self, dataset, parallel=False): """ Transforms all internally stored data. Adds X-transform, y-transform columns to metadata. """ return dataset.transform(lambda X, y, w: self.transform_array(X, y, w)) def transform_on_array(self, X, y, w): """ Transforms numpy arrays X, y, and w """ X, y, w = self.transform_array(X, y, w) return X, y, w class NormalizationTransformer(Transformer): def __init__(self, transform_X=False, transform_y=False, transform_w=False, dataset=None, transform_gradients=False): """Initialize normalization transformation.""" super(NormalizationTransformer, self).__init__( transform_X=transform_X, transform_y=transform_y, transform_w=transform_w, dataset=dataset) if transform_X: X_means, X_stds = dataset.get_statistics(X_stats=True, y_stats=False) self.X_means = X_means self.X_stds = X_stds elif transform_y: y_means, y_stds = dataset.get_statistics(X_stats=False, y_stats=True) self.y_means = y_means # Control for pathological case with no variance. y_stds[y_stds == 0] = 1. self.y_stds = y_stds self.transform_gradients = transform_gradients if self.transform_gradients: true_grad, ydely_means = get_grad_statistics(dataset) self.grad = np.reshape(true_grad, (true_grad.shape[0],-1,3)) self.ydely_means = ydely_means def transform(self, dataset, parallel=False): return super(NormalizationTransformer, self).transform( dataset, parallel=parallel) def transform_array(self, X, y, w): """Transform the data in a set of (X, y, w) arrays.""" if self.transform_X: X = np.nan_to_num((X - self.X_means) / self.X_stds) if self.transform_y: y = np.nan_to_num((y - self.y_means) / self.y_stds) return (X, y, w) def untransform(self, z): """ Undo transformation on provided data. """ if self.transform_X: return z * self.X_stds + self.X_means elif self.transform_y: return z * self.y_stds + self.y_means def untransform_grad(self, grad, tasks): """ Undo transformation on gradient. """ if self.transform_y: grad_means = self.y_means[1:] energy_var = self.y_stds[0] grad_var = 1/energy_var*(self.ydely_means-self.y_means[0]*self.y_means[1:]) energy = tasks[:,0] transformed_grad = [] for i in range(energy.size): Etf = energy[i] grad_Etf = grad[i].flatten() grad_E = Etf*grad_var+energy_var*grad_Etf+grad_means grad_E = np.reshape(grad_E, (-1,3)) transformed_grad.append(grad_E) transformed_grad = np.asarray(transformed_grad) return transformed_grad class AtomicNormalizationTransformer(Transformer): """ TODO(rbharath): Needs more discussion of what a gradient is semantically. It's evident that not every Dataset has meaningful gradient information, so this transformer can't be applied to all data. Should there be a subclass of Dataset named GradientDataset perhaps? """ def __init__(self, transform_X=False, transform_y=False, transform_w=False, dataset=None): """Initialize normalization transformation.""" super(AtomicNormalizationTransformer, self).__init__( transform_X=transform_X, transform_y=transform_y, transform_w=transform_w, dataset=dataset) X_means, X_stds, y_means, y_stds = dataset.get_statistics() self.X_means = X_means self.X_stds = X_stds self.y_means = y_means # Control for pathological case with no variance. y_stds[y_stds == 0] = 1. self.y_stds = y_stds true_grad, ydely_means = get_grad_statistics(dataset) self.grad = np.reshape(true_grad, (true_grad.shape[0],-1,3)) self.ydely_means = ydely_means def transform(self, dataset, parallel=False): return super(AtomicNormalizationTransformer, self).transform( dataset, parallel=parallel) def transform_row(self, i, df, data_dir): """ Normalizes the data (X, y, w, ...) in a single row). """ row = df.iloc[i] if self.transform_X: X = load_from_disk( os.path.join(data_dir, row['X-transformed'])) X = np.nan_to_num((X - self.X_means) / self.X_stds) save_to_disk(X, os.path.join(data_dir, row['X-transformed'])) if self.transform_y: y = load_from_disk(os.path.join(data_dir, row['y-transformed'])) # transform tasks as normal y = np.nan_to_num((y - self.y_means) / self.y_stds) # add 2nd order correction term to gradients grad_var = 1/self.y_stds[0]*(self.ydely_means-self.y_means[0]*self.y_means[1:]) for i in range(y.shape[0]): y[i,1:] = y[i,1:] - grad_var*y[i,0]/self.y_stds[0] save_to_disk(y, os.path.join(data_dir, row['y-transformed'])) def transform_array(self, X, y, w): """Transform the data in a set of (X, y, w) arrays.""" if self.transform_X: X = np.nan_to_num((X - self.X_means) / self.X_stds) if self.transform_y: # transform tasks as normal y = np.nan_to_num((y - self.y_means) / self.y_stds) # add 2nd order correction term to gradients grad_var = 1/self.y_stds[0]*(self.ydely_means-self.y_means[0]*self.y_means[1:]) for i in range(y.shape[0]): y[i,1:] = y[i,1:] - grad_var*y[i,0]/self.y_stds[0] return (X, y, w) def untransform(self, z): """ Undo transformation on provided data. """ if self.transform_X: return z * self.X_stds + self.X_means elif self.transform_y: # untransform grad grad_var = 1/self.y_stds[0]*(self.ydely_means-self.y_means[0]*self.y_means[1:]) for i in range(z.shape[0]): z[i,1:] = z[i,0]*grad_var + self.y_stds[0]*z[i,1:] + self.y_means[1:] # untransform energy z[:,0] = z[:,0] * self.y_stds[0] + self.y_means[0] return z def untransform_grad(self, grad, tasks): """ Undo transformation on gradient. """ if self.transform_y: grad_means = self.y_means[1:] energy_var = self.y_stds[0] grad_var = 1/energy_var*(self.ydely_means-self.y_means[0]*self.y_means[1:]) energy = tasks[:,0] transformed_grad = []
[ " for i in range(energy.size):" ]
874
lcc
python
null
fb636e04ae087216fc1ed273e49b1e03ab82872bf4ab05e0
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.vo; /** * Linked to OCRR.OrderingResults.OrderInvestigation business object (ID: 1070100002). */ public class OrderInvestigationForStatusChangeVo extends ims.ocrr.orderingresults.vo.OrderInvestigationRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public OrderInvestigationForStatusChangeVo() { } public OrderInvestigationForStatusChangeVo(Integer id, int version) { super(id, version); } public OrderInvestigationForStatusChangeVo(ims.ocrr.vo.beans.OrderInvestigationForStatusChangeVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.ordinvcurrentstatus = bean.getOrdInvCurrentStatus() == null ? null : bean.getOrdInvCurrentStatus().buildVo(); this.ordinvstatushistory = ims.ocrr.vo.OrderedInvestigationStatusVoCollection.buildFromBeanCollection(bean.getOrdInvStatusHistory()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.beans.OrderInvestigationForStatusChangeVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.ordinvcurrentstatus = bean.getOrdInvCurrentStatus() == null ? null : bean.getOrdInvCurrentStatus().buildVo(map); this.ordinvstatushistory = ims.ocrr.vo.OrderedInvestigationStatusVoCollection.buildFromBeanCollection(bean.getOrdInvStatusHistory()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.ocrr.vo.beans.OrderInvestigationForStatusChangeVoBean bean = null; if(map != null) bean = (ims.ocrr.vo.beans.OrderInvestigationForStatusChangeVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.ocrr.vo.beans.OrderInvestigationForStatusChangeVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ORDINVCURRENTSTATUS")) return getOrdInvCurrentStatus(); if(fieldName.equals("ORDINVSTATUSHISTORY")) return getOrdInvStatusHistory(); return super.getFieldValueByFieldName(fieldName); } public boolean getOrdInvCurrentStatusIsNotNull() { return this.ordinvcurrentstatus != null; } public ims.ocrr.vo.OrderedInvestigationStatusVo getOrdInvCurrentStatus() { return this.ordinvcurrentstatus; } public void setOrdInvCurrentStatus(ims.ocrr.vo.OrderedInvestigationStatusVo value) { this.isValidated = false; this.ordinvcurrentstatus = value; } public boolean getOrdInvStatusHistoryIsNotNull() { return this.ordinvstatushistory != null; } public ims.ocrr.vo.OrderedInvestigationStatusVoCollection getOrdInvStatusHistory() { return this.ordinvstatushistory; } public void setOrdInvStatusHistory(ims.ocrr.vo.OrderedInvestigationStatusVoCollection value) { this.isValidated = false; this.ordinvstatushistory = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } if(this.ordinvcurrentstatus != null) { if(!this.ordinvcurrentstatus.isValidated()) { this.isBusy = false; return false; } } if(this.ordinvstatushistory != null) { if(!this.ordinvstatushistory.isValidated()) { this.isBusy = false; return false; } } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.ordinvcurrentstatus == null) listOfErrors.add("OrdInvCurrentStatus is mandatory"); if(this.ordinvcurrentstatus != null) { String[] listOfOtherErrors = this.ordinvcurrentstatus.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.ordinvstatushistory != null) { String[] listOfOtherErrors = this.ordinvstatushistory.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; OrderInvestigationForStatusChangeVo clone = new OrderInvestigationForStatusChangeVo(this.id, this.version); if(this.ordinvcurrentstatus == null) clone.ordinvcurrentstatus = null; else clone.ordinvcurrentstatus = (ims.ocrr.vo.OrderedInvestigationStatusVo)this.ordinvcurrentstatus.clone(); if(this.ordinvstatushistory == null) clone.ordinvstatushistory = null; else clone.ordinvstatushistory = (ims.ocrr.vo.OrderedInvestigationStatusVoCollection)this.ordinvstatushistory.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; }
[ "\t\tif(caseInsensitive); // this is to avoid eclipse warning only." ]
664
lcc
java
null
9516693902335ad7c898f1e9ec8d1799680dac2988c0259d
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.workspace.server.spi.tck; import com.google.inject.Inject; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.notification.EventService; import org.eclipse.che.api.machine.server.spi.SnapshotDao; import org.eclipse.che.api.workspace.server.event.StackPersistedEvent; import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl; import org.eclipse.che.api.workspace.server.model.impl.stack.StackComponentImpl; import org.eclipse.che.api.workspace.server.model.impl.stack.StackImpl; import org.eclipse.che.api.workspace.server.model.impl.stack.StackSourceImpl; import org.eclipse.che.api.workspace.server.spi.StackDao; import org.eclipse.che.api.workspace.server.stack.image.StackIcon; import org.eclipse.che.commons.test.tck.TckModuleFactory; import org.eclipse.che.commons.test.tck.repository.TckRepository; import org.eclipse.che.commons.test.tck.repository.TckRepositoryException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.util.Collections; import java.util.HashSet; import java.util.List; import static java.util.Arrays.asList; import static org.eclipse.che.api.workspace.server.spi.tck.WorkspaceDaoTest.createWorkspaceConfig; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Tests {@link SnapshotDao} contract. * * @author Yevhenii Voevodin */ @Guice(moduleFactory = TckModuleFactory.class) @Test(suiteName = StackDaoTest.SUITE_NAME) public class StackDaoTest { public static final String SUITE_NAME = "StackDaoTck"; private static final int STACKS_SIZE = 5; private StackImpl[] stacks; @Inject private TckRepository<StackImpl> stackRepo; @Inject private StackDao stackDao; @Inject private EventService eventService; @BeforeMethod private void createStacks() throws TckRepositoryException { stacks = new StackImpl[STACKS_SIZE]; for (int i = 0; i < STACKS_SIZE; i++) { stacks[i] = createStack("stack-" + i, "name-" + i); } stackRepo.createAll(asList(stacks)); } @AfterMethod private void removeStacks() throws TckRepositoryException { stackRepo.removeAll(); } @Test public void shouldGetById() throws Exception { final StackImpl stack = stacks[0]; assertEquals(stackDao.getById(stack.getId()), stack); } @Test(expectedExceptions = NotFoundException.class) public void shouldThrowNotFoundExceptionWhenGettingNonExistingStack() throws Exception { stackDao.getById("non-existing-stack"); } @Test(expectedExceptions = NullPointerException.class) public void shouldThrowNpeWhenGettingStackByNullKey() throws Exception { stackDao.getById(null); } @Test(dependsOnMethods = "shouldGetById") public void shouldCreateStack() throws Exception { final StackImpl stack = createStack("new-stack", "new-stack-name"); stackDao.create(stack); assertEquals(stackDao.getById(stack.getId()), stack); } @Test(expectedExceptions = ConflictException.class) public void shouldThrowConflictExceptionWhenCreatingStackWithIdThatAlreadyExists() throws Exception { final StackImpl stack = createStack(stacks[0].getId(), "new-name"); stackDao.create(stack); } @Test(expectedExceptions = ConflictException.class) public void shouldThrowConflictExceptionWhenCreatingStackWithNameThatAlreadyExists() throws Exception { final StackImpl stack = createStack("new-stack-id", stacks[0].getName()); stackDao.create(stack); } @Test(expectedExceptions = NullPointerException.class) public void shouldThrowNpeWhenCreatingNullStack() throws Exception { stackDao.create(null); } @Test(expectedExceptions = NotFoundException.class, dependsOnMethods = "shouldThrowNotFoundExceptionWhenGettingNonExistingStack") public void shouldRemoveStack() throws Exception { final StackImpl stack = stacks[0]; stackDao.remove(stack.getId()); // Should throw an exception stackDao.getById(stack.getId()); } @Test public void shouldNotThrowAnyExceptionWhenRemovingNonExistingStack() throws Exception { stackDao.remove("non-existing"); } @Test(expectedExceptions = NullPointerException.class) public void shouldThrowNpeWhenRemovingNull() throws Exception { stackDao.remove(null); } @Test(dependsOnMethods = "shouldGetById") public void shouldUpdateStack() throws Exception { final StackImpl stack = stacks[0]; stack.setName("new-name"); stack.setCreator("new-creator"); stack.setDescription("new-description"); stack.setScope("new-scope"); stack.getTags().clear(); stack.getTags().add("new-tag"); // Remove an existing component stack.getComponents().remove(1); // Add a new component stack.getComponents().add(new StackComponentImpl("component3", "component3-version")); // Update an existing component final StackComponentImpl component = stack.getComponents().get(0); component.setName("new-name"); component.setVersion("new-version"); // Updating source final StackSourceImpl source = stack.getSource(); source.setType("new-type"); source.setOrigin("new-source"); // Set a new icon stack.setStackIcon(new StackIcon("new-name", "new-media", "new-data".getBytes())); stackDao.update(stack); assertEquals(stackDao.getById(stack.getId()), new StackImpl(stack)); } @Test(expectedExceptions = ConflictException.class) public void shouldNotUpdateStackIfNewNameIsReserved() throws Exception { final StackImpl stack = stacks[0]; stack.setName(stacks[1].getName()); stackDao.update(stack); } @Test(expectedExceptions = NotFoundException.class) public void shouldThrowNotFoundExceptionWhenUpdatingNonExistingStack() throws Exception { stackDao.update(createStack("new-stack", "new-stack-name")); } @Test(expectedExceptions = NullPointerException.class) public void shouldThrowNpeWhenUpdatingNullStack() throws Exception { stackDao.update(null); } @Test(dependsOnMethods = "shouldUpdateStack") public void shouldFindStacksWithSpecifiedTags() throws Exception { stacks[0].getTags().addAll(asList("search-tag1", "search-tag2")); stacks[1].getTags().addAll(asList("search-tag1", "non-search-tag")); stacks[2].getTags().addAll(asList("non-search-tag", "search-tag2")); stacks[3].getTags().addAll(asList("search-tag1", "search-tag2", "another-tag")); updateAll(); final List<StackImpl> found = stackDao.searchStacks(null, asList("search-tag1", "search-tag2"), 0, 0); found.forEach(s -> Collections.sort(s.getTags()));
[ " for (StackImpl stack : stacks) {" ]
498
lcc
java
null
1dba3395659d0bbbbc35a3da100e582c60c44de0cdd4c2e8
package org.tanaguru.service; import junit.framework.TestCase; import org.tanaguru.crawler.CrawlerFactory; import org.tanaguru.entity.audit.Audit; import org.tanaguru.entity.audit.AuditImpl; import org.tanaguru.entity.parameterization.*; import org.tanaguru.entity.service.parameterization.ParameterDataService; import org.tanaguru.factory.TanaguruCrawlerControllerFactory; import org.tanaguru.service.mock.MockParameterDataService; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; public class TanaguruCrawlerServiceImplTest extends TestCase { private static final String FULL_SITE_CRAWL_URL_KEY = "full-site-crawl-url"; private static final String ROBOTS_RESTRICTED_CRAWL_URL_KEY = "robots-restricted-crawl-url"; private static final String SITES_URL_BUNDLE_NAME = "sites-url"; private static final String PAGE_NAME_LEVEL1 = "page-1.html"; private static final String PAGE_NAME_LEVEL2 = "page-2.html"; private static final String FORBIDDEN_PAGE_NAME = "page-access-forbidden-for-robots.html"; private final ResourceBundle bundle = ResourceBundle.getBundle(SITES_URL_BUNDLE_NAME); private CrawlerService crawlerService; private CrawlerFactory crawlerFactory; private ParameterDataService mockParameterDataService; public TanaguruCrawlerServiceImplTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); mockParameterDataService = new MockParameterDataService(); crawlerFactory = new TanaguruCrawlerControllerFactory(); crawlerService = new TanaguruCrawlerServiceImpl(); crawlerService.setCrawlerFactory(crawlerFactory); crawlerService.setParameterDataService(mockParameterDataService); crawlerFactory.setOutputDir("/tmp/"); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * * @param siteUrl * @param depth * @param exclusionRegex * @param inlusionRegex * @param maxDuration * @param maxDocuments * @param proxyHost * @param proxyPort * @return */ private List<String> initialiseAndLaunchCrawl( String siteUrl, int depth, String exclusionRegex, String inclusionRegex, long maxDuration, int maxDocuments) { Audit audit = new AuditImpl(); audit.setParameterSet(setCrawlParameters(String.valueOf(depth),exclusionRegex, inclusionRegex, String.valueOf(maxDuration), String.valueOf(maxDocuments))); return crawlerService.getUrlListByCrawlingFromUrl(audit, siteUrl); } public void testCrawl_SiteWithDepthLevel0Option() { System.out.println("crawl_full_site_With_Depth_Level0_Option"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 0, "", "", 86400L, 10000); assertEquals(1, contentList.size()); assertTrue(contentList.contains(siteUrl)); } public void testCrawl_SiteWithDepthLevel1Option() { System.out.println("crawl_full_site_With_Depth_Level1_Option"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 1, "", "", 86400L, 10000); assertEquals(3, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertTrue(contentList.contains(siteUrl + FORBIDDEN_PAGE_NAME)); } public void testCrawl_SiteWithRegexpExclusionOption() { System.out.println("crawl_full_site_With_Regexp_Exclusion_Option"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 4, ".html", "", 86400L, 10000); assertEquals(1, contentList.size()); assertTrue(contentList.contains(siteUrl)); } public void testCrawl_SiteWithRegexpInclusionOption() { System.out.println("crawl_full_site_With_Regexp_Inclusion_Option"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY)+"page-1.html"; List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 2, "", "page-", 86400L, 10000); assertEquals(3, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(bundle.getString(FULL_SITE_CRAWL_URL_KEY) + PAGE_NAME_LEVEL2)); assertTrue(contentList.contains(bundle.getString(FULL_SITE_CRAWL_URL_KEY) + FORBIDDEN_PAGE_NAME)); } public void testCrawl_SiteWithRegexpInclusionOption2() { System.out.println("crawl_full_site_With_Regexp_Inclusion_Option 2"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY)+"page-1.html"; List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 2, "", "page-\\d", 86400L, 10); assertEquals(2, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(bundle.getString(FULL_SITE_CRAWL_URL_KEY) + PAGE_NAME_LEVEL2)); } public void testCrawl_SiteWithRegexpInclusionOption3() { System.out.println("crawl_full_site_With_Regexp_Inclusion_Option 3"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 2, "", "page-\\d", 86400L, 10); assertEquals(3, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL2)); } public void testCrawl_SiteWithRegexpExclusionOption2() { System.out.println("crawl_full_site_With_Regexp_Exclusion_Option2"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 4, "robot", "", 86400L, 10000); assertEquals(3, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL2)); } public void testCrawl_SiteWithRegexpExclusionOption3() { System.out.println("crawl_full_site_With_Regexp_Exclusion_Option3"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 4, "robot;page-2", "", 86400L, 10000); assertEquals(2, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); } /** * * Test the crawl of a site without robots.txt file */ public void testCrawl_Site() { System.out.println("crawl_full_site"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 3, "", "", 86400L, 10000); assertEquals(4, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL2)); assertTrue(contentList.contains(siteUrl + FORBIDDEN_PAGE_NAME)); } /** * Test the crawl of a page */ public void testCrawl_Page() { System.out.println("crawl_page"); String siteUrl = bundle.getString(FULL_SITE_CRAWL_URL_KEY); Audit audit = new AuditImpl(); audit.setParameterSet(setCrawlParameters("3", "", "", "", "")); List<String> contentList = crawlerService.getUrlListByCrawlingFromUrl(audit, siteUrl); assertEquals(1, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertFalse(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertFalse(contentList.contains(siteUrl + PAGE_NAME_LEVEL2)); assertFalse(contentList.contains(siteUrl + FORBIDDEN_PAGE_NAME)); } /** * Test the crawl of a site with robots.txt file */ public void testCrawl_Site_With_Robots() { System.out.println("crawl_site_with_robots"); String siteUrl = bundle.getString(ROBOTS_RESTRICTED_CRAWL_URL_KEY); List<String> contentList = initialiseAndLaunchCrawl(siteUrl, 3, "", "", 86400L, 10000); assertEquals(3, contentList.size()); assertTrue(contentList.contains(siteUrl)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL1)); assertTrue(contentList.contains(siteUrl + PAGE_NAME_LEVEL2)); assertFalse(contentList.contains(siteUrl + FORBIDDEN_PAGE_NAME)); } /** * * @param depth * @param exclusionRegexp * @param inclusionRegexp * @param maxDuration * @param maxDocuments * @param proxyHost * @param proxyPort * @return The set of Parameters regarding options set as argument */ private Set<Parameter> setCrawlParameters( String depth, String exclusionRegexp, String inclusionRegexp, String maxDuration, String maxDocuments) { Set<Parameter> crawlParameters = new HashSet<>(); ParameterFamily pf = new ParameterFamilyImpl(); pf.setParameterFamilyCode("CRAWLER"); //DEPTH
[ " ParameterElement ped = new ParameterElementImpl();" ]
593
lcc
java
null
bac49e73188f1e4ebc882afd8cd6cc4798333341297fb191
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Loyc; using Loyc.Collections; using S = Loyc.Syntax.CodeSymbols; namespace Loyc.Syntax { /// <summary>Standard extension methods for <see cref="LNode"/>.</summary> public static class LNodeExt { #region Trivia management public static VList<LNode> GetTrivia(this LNode node) { return GetTrivia(node.Attrs); } public static VList<LNode> GetTrivia(this VList<LNode> attrs) { var trivia = VList<LNode>.Empty; foreach (var a in attrs) if (a.IsTrivia) trivia.Add(a); return trivia; } /// <summary>Gets all trailing trivia attached to the specified node.</summary> public static VList<LNode> GetTrailingTrivia(this LNode node) { return GetTrailingTrivia(node.Attrs); } /// <summary>Gets all trailing trivia attached to the specified node.</summary> /// <remarks>Trailing trivia is represented by a call to #trivia_trailing in /// a node's attribute list; each argument to #trivia_trailing represents one /// piece of trivia. If the attribute list has multiple calls to /// #trivia_trailing, this method combines those lists into a single list.</remarks> public static VList<LNode> GetTrailingTrivia(this VList<LNode> attrs) { var trivia = VList<LNode>.Empty; foreach (var a in attrs) if (a.Calls(S.TriviaTrailing)) trivia.AddRange(a.Args); return trivia; } /// <summary>Removes a node's trailing trivia and adds a new list of trailing trivia.</summary> public static LNode WithTrailingTrivia(this LNode node, VList<LNode> trivia) { return node.WithAttrs(WithTrailingTrivia(node.Attrs, trivia)); } /// <summary>Removes all existing trailing trivia from an attribute list and adds a new list of trailing trivia.</summary> /// <remarks>This method has a side-effect of recreating the #trivia_trailing /// node, if there is one, at the end of the attribute list. If <c>trivia</c> /// is empty then all calls to #trivia_trailing are removed.</remarks> public static VList<LNode> WithTrailingTrivia(this VList<LNode> attrs, VList<LNode> trivia) { var attrs2 = WithoutTrailingTrivia(attrs); if (trivia.IsEmpty) return attrs2; return attrs2.Add(LNode.Call(S.TriviaTrailing, trivia)); } /// <summary>Gets a new list with any #trivia_trailing attributes removed.</summary> public static VList<LNode> WithoutTrailingTrivia(this VList<LNode> attrs) { return attrs.Transform((int i, ref LNode attr) => attr.Calls(S.TriviaTrailing) ? XfAction.Drop : XfAction.Keep); } /// <summary>Gets a new list with any #trivia_trailing attributes removed. Those trivia are returned in an `out` parameter.</summary> public static VList<LNode> WithoutTrailingTrivia(this VList<LNode> attrs, out VList<LNode> trailingTrivia) { var trailingTrivia2 = VList<LNode>.Empty; attrs = attrs.Transform((int i, ref LNode attr) => { if (attr.Calls(S.TriviaTrailing)) { trailingTrivia2.AddRange(attr.Args); return XfAction.Drop; } return XfAction.Keep; }); trailingTrivia = trailingTrivia2; // cannot use `out` parameter within lambda method return attrs; } /// <summary>Adds additional trailing trivia to a node.</summary> public static LNode PlusTrailingTrivia(this LNode node, VList<LNode> trivia) { return node.WithAttrs(PlusTrailingTrivia(node.Attrs, trivia)); } /// <summary>Adds additional trailing trivia to a node.</summary> public static LNode PlusTrailingTrivia(this LNode node, LNode trivia) { return node.WithAttrs(PlusTrailingTrivia(node.Attrs, trivia)); } /// <summary>Adds additional trailing trivia to an attribute list. Has no effect if <c>trivia</c> is empty.</summary> /// <remarks> /// Trailing trivia is represented by a call to #trivia_trailing in a node's /// attribute list; each argument to #trivia_trailing represents one piece of /// trivia. /// <para/> /// In the current design, this method has a side-effect of recreating the #trivia_trailing /// node at the end of the attribute list, and if there are multiple #trivia_trailing /// lists, consolidating them into a single list, but only if the specified <c>trivia</c> /// list is not empty.</remarks> public static VList<LNode> PlusTrailingTrivia(this VList<LNode> attrs, VList<LNode> trivia) { if (trivia.IsEmpty) return attrs; VList<LNode> oldTrivia; attrs = WithoutTrailingTrivia(attrs, out oldTrivia); return attrs.Add(LNode.Call(S.TriviaTrailing, oldTrivia.AddRange(trivia))); } /// <summary>Adds additional trailing trivia to an attribute list.</summary> public static VList<LNode> PlusTrailingTrivia(this VList<LNode> attrs, LNode trivia) { VList<LNode> oldTrivia; attrs = WithoutTrailingTrivia(attrs, out oldTrivia); return attrs.Add(LNode.Call(S.TriviaTrailing, oldTrivia.Add(trivia))); } #endregion /// <summary>Interprets a node as a list by returning <c>block.Args</c> if /// <c>block.Calls(listIdentifier)</c>, otherwise returning a one-item list /// of nodes with <c>block</c> as the only item.</summary> public static VList<LNode> AsList(this LNode block, Symbol listIdentifier) { return block.Calls(listIdentifier) ? block.Args : new VList<LNode>(block); } /// <summary>Converts a list of LNodes to a single LNode by using the list /// as the argument list in a call to the specified identifier, or, if the /// list contains a single item, by returning that single item.</summary> /// <param name="listIdentifier">Target of the node that is created if <c>list</c> /// does not contain exactly one item. Typical values include "'{}" and "#splice".</param> /// <remarks>This is the reverse of the operation performed by <see cref="AsList(LNode,Symbol)"/>.</remarks> public static LNode AsLNode(this VList<LNode> list, Symbol listIdentifier) { if (list.Count == 1) return list[0]; else { var r = SourceRange.Nowhere; if (list.Count != 0) { r = list[0].Range; r = new SourceRange(r.Source, r.StartIndex, list.Last.Range.EndIndex - r.StartIndex); } return LNode.Call(listIdentifier, list, r); } } public static VList<LNode> WithSpliced(this VList<LNode> list, int index, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) return list.InsertRange(index, node.Args); else return list.Insert(index, node); } public static VList<LNode> WithSpliced(this VList<LNode> list, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) return list.AddRange(node.Args); else return list.Add(node); } public static void SpliceInsert(this WList<LNode> list, int index, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) list.InsertRange(index, node.Args); else list.Insert(index, node); } public static void SpliceAdd(this WList<LNode> list, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) list.AddRange(node.Args); else list.Add(node); } public static LNode AttrNamed(this LNode self, Symbol name) { return self.Attrs.NodeNamed(name); } public static LNode WithoutAttrNamed(this LNode self, Symbol name) { LNode _; return WithoutAttrNamed(self, name, out _); } public static VList<LNode> Without(this VList<LNode> list, LNode node) { int i = list.Count; foreach (var item in list.ToFVList()) { i--; if (item == node) { Debug.Assert(list[i] == node); return list.RemoveAt(i); } } return list; } public static LNode WithoutAttr(this LNode self, LNode node) { return self.WithAttrs(self.Attrs.Without(node)); } public static LNode WithoutAttrNamed(this LNode self, Symbol name, out LNode removedAttr) { var a = self.Attrs.WithoutNodeNamed(name, out removedAttr); if (removedAttr != null) return self.WithAttrs(a); else return self; } public static VList<LNode> WithoutNodeNamed(this VList<LNode> a, Symbol name) { LNode _; return WithoutNodeNamed(a, name, out _); } public static VList<LNode> WithoutNodeNamed(this VList<LNode> list, Symbol name, out LNode removedNode) { removedNode = null; for (int i = 0, c = list.Count; i < c; i++) if (list[i].Name == name) { removedNode = list[i]; return list.RemoveAt(i); } return list; } public static LNode ArgNamed(this LNode self, Symbol name) { return self.Args.NodeNamed(name); } public static int IndexWithName(this VList<LNode> self, Symbol name, int resultIfNotFound = -1) { int i = 0; foreach (LNode node in self) if (node.Name == name) return i; else i++; return resultIfNotFound; } public static LNode NodeNamed(this VList<LNode> self, Symbol name) { foreach (LNode node in self) if (node.Name == name) return node; return null; } #region Parentheses management public static bool IsParenthesizedExpr(this LNode node) { return node.AttrNamed(CodeSymbols.TriviaInParens) != null; } /// <summary>Returns the same node with a parentheses attribute added.</summary> public static LNode InParens(this LNode node) { return node.PlusAttrBefore(LNode.Id(CodeSymbols.TriviaInParens)); } /// <summary>Returns the same node with a parentheses attribute added.</summary> /// <remarks>The node's range is changed to the provided <see cref="SourceRange"/>.</remarks> public static LNode InParens(this LNode node, SourceRange range) { return node.WithRange(range).PlusAttrBefore(LNode.Id(CodeSymbols.TriviaInParens)); } /// <summary>Returns the same node with a parentheses attribute added.</summary> public static LNode InParens(this LNode node, ISourceFile file, int startIndex, int endIndex) { return InParens(node, new SourceRange(file, startIndex, endIndex - startIndex)); } /// <summary>Removes a single pair of parentheses, if the node has a /// #trivia_inParens attribute. Returns the same node when no parens are /// present.</summary> public static LNode WithoutOuterParens(this LNode self) { LNode parens; self = WithoutAttrNamed(self, S.TriviaInParens, out parens); // Restore original node range if (parens != null && self.Range.Contains(parens.Range)) return self.WithRange(parens.Range); return self; } #endregion #region MatchesPattern() and helper methods // Used by replace() macro static LNodeFactory F = new LNodeFactory(new EmptySourceFile("LNodeExt.cs")); /// <summary>Determines whether one Loyc tree "matches" another. This is /// different from a simple equality test in that (1) trivia atributes do /// not have to match, and (2) the pattern can contain placeholders represented /// by calls to $ (the substitution operator) with an identifier as a parameter. /// Placeholders match any subtree, and are saved to the <c>captures</c> map. /// </summary> /// <param name="candidate">A node that you want to compare with a 'pattern'.</param> /// <param name="pattern">A syntax tree that may contain placeholders. A /// placeholder is a call to the $ operator with one parameter, which must /// be either (A) a simple identifier, or (B) the ".." operator with a simple /// identifier as its single parameter. Otherwise, the $ operator is treated /// literally as something that must exist in <c>candidate</c>). The subtree /// in <c>candidate</c> corresponding to the placeholder is saved in /// <c>captures</c>.</param> /// <param name="captures">A table that maps placeholder names from /// <c>pattern</c> to subtrees in <c>candidate</c>. You can set your map to /// null and a map will be created for you if necessary. If you already have /// a map, you should clear it before calling this method.</param> /// <param name="unmatchedAttrs">On return, a list of trivia attributes in /// <c>candidate</c> that were not present in <c>pattern</c>.</param> /// <returns>true if <c>pattern</c> matches <c>candidate</c>, false otherwise.</returns> /// <remarks> /// Attributes in patterns are not yet supported. /// <para/> /// This method supports multi-part captures, which are matched to /// placeholders whose identifier either (A) has a #params attribute or /// (B) has the unary ".." operator applied to it (for example, if /// the placeholder is called p, this is written as <c>$(params p)</c> in /// EC#.) A placeholder that looks like this can match multiple arguments or /// multiple statements in the <c>candidate</c> (or <i>no</i> arguments, or /// no statements), and will become a #splice(...) node in <c>captures</c> /// if it matches multiple items. Multi-part captures are often useful for /// getting lists of statements before and after some required element, /// e.g. <c>{ $(params before); MatchThis($something); $(params after); }</c> /// <para/> /// If the same placeholder appears twice then the two matching items are /// combined into a single output node (calling #splice). /// <para/> /// If matching is unsuccessful, <c>captures</c> and <c>unmatchedAttrs</c> /// may contain irrelevant information gathered during the attempt to match. /// <para/> /// In EC#, the quote(...) macro can be used to create the LNode object for /// a pattern. /// </remarks> public static bool MatchesPattern(this LNode candidate, LNode pattern, ref MMap<Symbol, LNode> captures, out VList<LNode> unmatchedAttrs) { // [$capture] (...) if (!AttributesMatch(candidate, pattern, ref captures, out unmatchedAttrs)) return false; // $capture or $(..capture) LNode sub = GetCaptureIdentifier(pattern); if (sub != null) { captures = captures ?? new MMap<Symbol, LNode>(); AddCapture(captures, sub.Name, candidate); unmatchedAttrs = VList<LNode>.Empty; // The attrs (if any) were captured return true; } var kind = candidate.Kind; if (kind != pattern.Kind) return false;
[ "\t\t\tif (kind == LNodeKind.Id && candidate.Name != pattern.Name)" ]
1,713
lcc
csharp
null
a330393b411f537b7da68d95f8343c7628953903c26432d2
using EloBuddy; namespace KoreanZed { using LeagueSharp; using LeagueSharp.Common; using System.Linq; using System; using System.Collections.Generic; using KoreanZed.Enumerators; using KoreanZed.QueueActions; using SharpDX; class ZedShadows { private readonly ZedMenu zedMenu; private readonly ZedSpell q; private readonly ZedSpell w; private readonly ZedSpell e; private readonly ZedEnergyChecker energy; public bool CanCast { get { int currentShadows = GetShadows().Count(); return ((!ObjectManager.Player.HasBuff("zedwhandler") && w.IsReady() && Game.Time > lastTimeCast + 0.3F && Game.Time > buffTime + 1F) && w.IsReady() && w.Instance.ToggleState == 0 && !ObjectManager.Player.HasBuff("zedwhandler") && ((ObjectManager.Player.HasBuff("zedr2") && currentShadows == 1) || currentShadows == 0)); } } public bool CanSwitch { get { return !CanCast && w.Instance.ToggleState != 0 && w.IsReady() && !ObjectManager.Get<Obj_AI_Turret>() .Any(ob => ob.Distance(Instance.Position) < 775F && ob.IsEnemy && !ob.IsDead); } } public Obj_AI_Base Instance { get { Obj_AI_Base shadow = GetShadows().FirstOrDefault(); if (shadow != null) { return shadow; } else { return ObjectManager.Player; } } } private float lastTimeCast; private float buffTime; public ZedShadows(ZedMenu menu, ZedSpells spells, ZedEnergyChecker energy) { zedMenu = menu; q = spells.Q; w = spells.W; e = spells.E; this.energy = energy; Game.OnUpdate += Game_OnUpdate; } private void Game_OnUpdate(EventArgs args) { if (ObjectManager.Player.HasBuff("zedwhandler")) { buffTime = Game.Time; } } public void Cast(Vector3 position) { if (CanCast) { w.Cast(position); lastTimeCast = Game.Time; } } public void Cast(AIHeroClient target) { if (target == null) { return; } Cast(target.Position); } public void Switch() { if (CanSwitch) { w.Cast(); } } public List<Obj_AI_Base> GetShadows() { List<Obj_AI_Base> resultList = new List<Obj_AI_Base>(); foreach ( Obj_AI_Base objAiBase in ObjectManager.Get<Obj_AI_Base>().Where(obj => obj.BaseSkinName.ToLowerInvariant().Contains("shadow") && !obj.IsDead)) { resultList.Add(objAiBase); } return resultList; } public void Combo() { List<Obj_AI_Base> shadows = GetShadows(); if (!shadows.Any() || (!q.UseOnCombo && !e.UseOnCombo) || (!q.IsReady() && !e.IsReady())) { return; } foreach (Obj_AI_Base objAiBase in shadows) { if (((q.UseOnCombo && !q.IsReady()) || !q.UseOnCombo) && ((e.UseOnCombo && !e.IsReady()) || !e.UseOnCombo)) { break; } if (q.UseOnCombo && q.IsReady()) { AIHeroClient target = TargetSelector.GetTarget( q.Range, q.DamageType, true, null, objAiBase.Position); if (target != null) { PredictionInput predictionInput = new PredictionInput(); predictionInput.Range = q.Range; predictionInput.RangeCheckFrom = objAiBase.Position; predictionInput.From = objAiBase.Position; predictionInput.Delay = q.Delay; predictionInput.Speed = q.Speed; predictionInput.Unit = target; predictionInput.Type = SkillshotType.SkillshotLine; predictionInput.Collision = false; PredictionOutput predictionOutput = Prediction.GetPrediction(predictionInput); if (predictionOutput.Hitchance >= HitChance.Medium) { q.Cast(predictionOutput.CastPosition); } } } if (e.UseOnCombo && e.IsReady()) { AIHeroClient target = TargetSelector.GetTarget(e.Range, e.DamageType, true, null, objAiBase.Position); if (target != null) { e.Cast(); } } } } public void Harass() { List<Obj_AI_Base> shadows = GetShadows(); if (!shadows.Any() || (!q.UseOnHarass && !e.UseOnHarass) || (!q.IsReady() && !e.IsReady())) { return; } List<AIHeroClient> blackList = zedMenu.GetBlockList(BlockListType.Harass); foreach (Obj_AI_Base objAiBase in shadows) { if (((q.UseOnHarass && !q.IsReady()) || !q.UseOnHarass) && ((e.UseOnHarass && !e.IsReady()) || !e.UseOnHarass)) { break; } if (q.UseOnHarass && q.IsReady()) { AIHeroClient target = TargetSelector.GetTarget( q.Range, q.DamageType, true, blackList, objAiBase.Position); if (target != null) { PredictionInput predictionInput = new PredictionInput(); predictionInput.Range = q.Range; predictionInput.RangeCheckFrom = objAiBase.Position; predictionInput.From = objAiBase.Position; predictionInput.Delay = q.Delay; predictionInput.Speed = q.Speed; predictionInput.Unit = target; predictionInput.Type = SkillshotType.SkillshotLine; predictionInput.Collision = false; PredictionOutput predictionOutput = Prediction.GetPrediction(predictionInput); if (predictionOutput.Hitchance >= HitChance.Medium) { q.Cast(predictionOutput.CastPosition); } } } if (e.UseOnHarass && e.IsReady()) { AIHeroClient target = TargetSelector.GetTarget(e.Range, e.DamageType, true, blackList, objAiBase.Position); if (target != null) { e.Cast(); } } } } public void LaneClear(ActionQueue actionQueue, ActionQueueList laneClearQueue) { Obj_AI_Base shadow = GetShadows().FirstOrDefault(); if (!energy.ReadyToLaneClear || shadow == null) { return; } if (e.UseOnLaneClear && e.IsReady()) { int extendedWillHit = MinionManager.GetMinions(shadow.Position, e.Range).Count(); int shortenWillHit = MinionManager.GetMinions(e.Range).Count; int param = zedMenu.GetParamSlider("koreanzed.laneclearmenu.useeif"); if (extendedWillHit >= param || shortenWillHit >= param) { actionQueue.EnqueueAction( laneClearQueue, () => true, () => e.Cast(), () => !e.IsReady()); return; } } if (q.UseOnLaneClear && q.IsReady()) { int extendedWillHit = 0; Vector3 extendedFarmLocation = Vector3.Zero; foreach (Obj_AI_Base objAiBase in MinionManager.GetMinions(shadow.Position, q.Range)) { var colisionList = q.GetCollision( shadow.Position.To2D(), new List<Vector2>() { objAiBase.Position.To2D() }, w.Delay);
[ " if (colisionList.Count > extendedWillHit)" ]
603
lcc
csharp
null
72337b5e2ebcaf24dc3e9b1e0609516992166e68a738bdea
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.pci.forms.gpcontracts; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } public static class ctnContractDetailsContainer extends ContainerBridge { private static final long serialVersionUID = 1L; public static class qmbGPSelectedComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.GpLiteWithNameVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.GpLiteWithNameVo value) { return super.control.removeRow(value); } public ims.core.vo.GpLiteWithNameVo getValue() { return (ims.core.vo.GpLiteWithNameVo)super.control.getValue(); } public void setValue(ims.core.vo.GpLiteWithNameVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 16, 50, 75, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Contract ID:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 16, 18, 61, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "GP Name:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 512, 18, 119, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Contract Start Date:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 512, 50, 112, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Contract End Date:", new Integer(1), null, new Integer(0)})); // TextBox Controls RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 96, 48, 392, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), new Integer(startTabIndex.intValue() + 8), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.TRUE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // Date Controls RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 640, 48, 176, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), new Integer(startTabIndex.intValue() + 10), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null})); RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 640, 16, 176, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), new Integer(startTabIndex.intValue() + 9), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.TRUE, null})); // Query ComboBox Controls RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 96, 16, 392, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_qmbGPSelectedTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), new Integer(startTabIndex.intValue() + 7), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.TRUE, new Integer(3), null, Boolean.TRUE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbGPSelectedTemp); qmbGPSelectedComboBox qmbGPSelected = (qmbGPSelectedComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbGPSelectedComboBox.class, m_qmbGPSelectedTemp); super.addComboBox(qmbGPSelected); } protected void setCollapsed(boolean value) { super.container.setCollapsed(value); } //protected boolean isCollapsed() //{ //return super.container.isCollapsed(); //} protected void setCaption(String value) { super.container.setCaption(value); } public TextBox txtContractID() { return (TextBox)super.getControl(4); } public DateControl dteEndDate() { return (DateControl)super.getControl(5); } public DateControl dteStartDate() { return (DateControl)super.getControl(6); } public qmbGPSelectedComboBox qmbGPSelected() { return (qmbGPSelectedComboBox)super.getComboBox(0); } } public static class qmbGPSearchComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.GpLiteWithNameVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.GpLiteWithNameVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.GpLiteWithNameVo value) { return super.control.removeRow(value); } public ims.core.vo.GpLiteWithNameVo getValue() { return (ims.core.vo.GpLiteWithNameVo)super.control.getValue(); } public void setValue(ims.core.vo.GpLiteWithNameVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class grdResultGridRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdResultGridRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setColGPReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isColGPReadOnly() { return super.row.isReadOnly(0); } public void showColGPOpened() { super.row.showOpened(0); } public String getColGP() { return (String)super.row.get(0); } public void setColGP(String value) { super.row.set(0, value); } public void setCellColGPTooltip(String value) { super.row.setTooltip(0, value); } public void setColContractIDReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean isColContractIDReadOnly() { return super.row.isReadOnly(1); } public void showColContractIDOpened() { super.row.showOpened(1); } public String getColContractID() { return (String)super.row.get(1); } public void setColContractID(String value) { super.row.set(1, value); } public void setCellColContractIDTooltip(String value) { super.row.setTooltip(1, value); } public void setColStartDateReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean isColStartDateReadOnly() { return super.row.isReadOnly(2); } public void showColStartDateOpened() { super.row.showOpened(2); } public String getColStartDate() { return (String)super.row.get(2); } public void setColStartDate(String value) { super.row.set(2, value); } public void setCellColStartDateTooltip(String value) { super.row.setTooltip(2, value); } public void setColEndDateReadOnly(boolean value) { super.row.setReadOnly(3, value); } public boolean isColEndDateReadOnly() { return super.row.isReadOnly(3); } public void showColEndDateOpened() { super.row.showOpened(3); } public String getColEndDate() { return (String)super.row.get(3); } public void setColEndDate(String value) { super.row.set(3, value); } public void setCellColEndDateTooltip(String value) { super.row.setTooltip(3, value); } public ims.pci.vo.GpContractVo getValue() { return (ims.pci.vo.GpContractVo)super.row.getValue(); } public void setValue(ims.pci.vo.GpContractVo value) { super.row.setValue(value); } } public static class grdResultGridRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdResultGridRowCollection(GridRowCollection collection) { super(collection); } public grdResultGridRow get(int index) { return new grdResultGridRow(super.collection.get(index)); } public grdResultGridRow newRow() { return new grdResultGridRow(super.collection.newRow()); } public grdResultGridRow newRow(boolean autoSelect) { return new grdResultGridRow(super.collection.newRow(autoSelect)); } public grdResultGridRow newRowAt(int index) { return new grdResultGridRow(super.collection.newRowAt(index)); } public grdResultGridRow newRowAt(int index, boolean autoSelect) { return new grdResultGridRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdResultGridGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } public ims.pci.vo.GpContractVoCollection getValues() { ims.pci.vo.GpContractVoCollection listOfValues = new ims.pci.vo.GpContractVoCollection(); for(int x = 0; x < this.getRows().size(); x++) { listOfValues.add(this.getRows().get(x).getValue()); } return listOfValues; } public ims.pci.vo.GpContractVo getValue() { return (ims.pci.vo.GpContractVo)super.grid.getValue(); } public void setValue(ims.pci.vo.GpContractVo value) { super.grid.setValue(value); } public grdResultGridRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdResultGridRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdResultGridRowCollection getRows() { return new grdResultGridRowCollection(super.grid.getRows()); } public grdResultGridRow getRowByValue(ims.pci.vo.GpContractVo value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdResultGridRow(row); } public void setColGPHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getColGPHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setColContractIDHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getColContractIDHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setColStartDateHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getColStartDateHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public void setColEndDateHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(3, value); } public String getColEndDateHeaderTooltip() { return super.grid.getColumnHeaderTooltip(3); } } private void validateContext(ims.framework.Context context) { if(context == null) return; } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); this.globalContext = new GlobalContext(context); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class)); super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class)); super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false)); super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier)); // Context Menus
[ "\t\tcontextMenus = new ContextMenus();" ]
1,735
lcc
java
null
caf4ee2315e7782e651f443c2b635e258cb5c7aea3ede55c
""" Install Python and Node prerequisites. """ import hashlib import os import re import subprocess import sys from distutils import sysconfig from paver.easy import BuildFailure, sh, task from .utils.envs import Env from .utils.timer import timed PREREQS_STATE_DIR = os.getenv('PREREQ_CACHE_DIR', Env.REPO_ROOT / '.prereqs_cache') NO_PREREQ_MESSAGE = "NO_PREREQ_INSTALL is set, not installing prereqs" NO_PYTHON_UNINSTALL_MESSAGE = 'NO_PYTHON_UNINSTALL is set. No attempts will be made to uninstall old Python libs.' COVERAGE_REQ_FILE = 'requirements/edx/coverage.txt' # If you make any changes to this list you also need to make # a corresponding change to circle.yml, which is how the python # prerequisites are installed for builds on circleci.com if 'TOXENV' in os.environ: PYTHON_REQ_FILES = ['requirements/edx/testing.txt'] else: PYTHON_REQ_FILES = ['requirements/edx/development.txt'] # Developers can have private requirements, for local copies of github repos, # or favorite debugging tools, etc. PRIVATE_REQS = 'requirements/private.txt' if os.path.exists(PRIVATE_REQS): PYTHON_REQ_FILES.append(PRIVATE_REQS) def str2bool(s): s = str(s) return s.lower() in ('yes', 'true', 't', '1') def no_prereq_install(): """ Determine if NO_PREREQ_INSTALL should be truthy or falsy. """ return str2bool(os.environ.get('NO_PREREQ_INSTALL', 'False')) def no_python_uninstall(): """ Determine if we should run the uninstall_python_packages task. """ return str2bool(os.environ.get('NO_PYTHON_UNINSTALL', 'False')) def create_prereqs_cache_dir(): """Create the directory for storing the hashes, if it doesn't exist already.""" try: os.makedirs(PREREQS_STATE_DIR) except OSError: if not os.path.isdir(PREREQS_STATE_DIR): raise def compute_fingerprint(path_list): """ Hash the contents of all the files and directories in `path_list`. Returns the hex digest. """ hasher = hashlib.sha1() for path_item in path_list: # For directories, create a hash based on the modification times # of first-level subdirectories if os.path.isdir(path_item): for dirname in sorted(os.listdir(path_item)): path_name = os.path.join(path_item, dirname) if os.path.isdir(path_name): hasher.update(str(os.stat(path_name).st_mtime).encode('utf-8')) # For files, hash the contents of the file if os.path.isfile(path_item): with open(path_item, "rb") as file_handle: hasher.update(file_handle.read()) return hasher.hexdigest() def prereq_cache(cache_name, paths, install_func): """ Conditionally execute `install_func()` only if the files/directories specified by `paths` have changed. If the code executes successfully (no exceptions are thrown), the cache is updated with the new hash. """ # Retrieve the old hash cache_filename = cache_name.replace(" ", "_") cache_file_path = os.path.join(PREREQS_STATE_DIR, "{}.sha1".format(cache_filename)) old_hash = None if os.path.isfile(cache_file_path): with open(cache_file_path, "r") as cache_file: old_hash = cache_file.read() # Compare the old hash to the new hash # If they do not match (either the cache hasn't been created, or the files have changed), # then execute the code within the block. new_hash = compute_fingerprint(paths) if new_hash != old_hash: install_func() # Update the cache with the new hash # If the code executed within the context fails (throws an exception), # then this step won't get executed. create_prereqs_cache_dir() with open(cache_file_path, "wb") as cache_file: # Since the pip requirement files are modified during the install # process, we need to store the hash generated AFTER the installation post_install_hash = compute_fingerprint(paths) cache_file.write(post_install_hash.encode('utf-8')) else: print('{cache} unchanged, skipping...'.format(cache=cache_name)) def node_prereqs_installation(): """ Configures npm and installs Node prerequisites """ # NPM installs hang sporadically. Log the installation process so that we # determine if any packages are chronic offenders. shard_str = os.getenv('SHARD', None) if shard_str: npm_log_file_path = '{}/npm-install.{}.log'.format(Env.GEN_LOG_DIR, shard_str) else: npm_log_file_path = '{}/npm-install.log'.format(Env.GEN_LOG_DIR) npm_log_file = open(npm_log_file_path, 'wb') npm_command = 'npm install --verbose'.split() # The implementation of Paver's `sh` function returns before the forked # actually returns. Using a Popen object so that we can ensure that # the forked process has returned proc = subprocess.Popen(npm_command, stderr=npm_log_file) retcode = proc.wait() if retcode == 1: # Error handling around a race condition that produces "cb() never called" error. This # evinces itself as `cb_error_text` and it ought to disappear when we upgrade # npm to 3 or higher. TODO: clean this up when we do that. print("npm install error detected. Retrying...") proc = subprocess.Popen(npm_command, stderr=npm_log_file) retcode = proc.wait() if retcode == 1: raise Exception("npm install failed: See {}".format(npm_log_file_path)) print("Successfully installed NPM packages. Log found at {}".format( npm_log_file_path )) def python_prereqs_installation(): """ Installs Python prerequisites """ for req_file in PYTHON_REQ_FILES: pip_install_req_file(req_file) def pip_install_req_file(req_file): """Pip install the requirements file.""" pip_cmd = 'pip install -q --disable-pip-version-check --exists-action w' sh("{pip_cmd} -r {req_file}".format(pip_cmd=pip_cmd, req_file=req_file)) @task @timed def install_node_prereqs(): """ Installs Node prerequisites """ if no_prereq_install(): print(NO_PREREQ_MESSAGE) return prereq_cache("Node prereqs", ["package.json"], node_prereqs_installation) # To add a package to the uninstall list, just add it to this list! No need # to touch any other part of this file. PACKAGES_TO_UNINSTALL = [ "MySQL-python", # Because mysqlclient shares the same directory name "South", # Because it interferes with Django 1.8 migrations. "edxval", # Because it was bork-installed somehow. "django-storages", "django-oauth2-provider", # Because now it's called edx-django-oauth2-provider. "edx-oauth2-provider", # Because it moved from github to pypi "enum34", # Because enum34 is not needed in python>3.4 "i18n-tools", # Because now it's called edx-i18n-tools "moto", # Because we no longer use it and it conflicts with recent jsondiff versions "python-saml", # Because python3-saml shares the same directory name "pdfminer", # Replaced by pdfminer.six, which shares the same directory name "pytest-faulthandler", # Because it was bundled into pytest "djangorestframework-jwt", # Because now its called drf-jwt. ] @task @timed def uninstall_python_packages(): """ Uninstall Python packages that need explicit uninstallation. Some Python packages that we no longer want need to be explicitly uninstalled, notably, South. Some other packages were once installed in ways that were resistant to being upgraded, like edxval. Also uninstall them. """ if no_python_uninstall(): print(NO_PYTHON_UNINSTALL_MESSAGE) return # So that we don't constantly uninstall things, use a hash of the packages # to be uninstalled. Check it, and skip this if we're up to date. hasher = hashlib.sha1() hasher.update(repr(PACKAGES_TO_UNINSTALL).encode('utf-8')) expected_version = hasher.hexdigest() state_file_path = os.path.join(PREREQS_STATE_DIR, "Python_uninstall.sha1") create_prereqs_cache_dir() if os.path.isfile(state_file_path): with open(state_file_path) as state_file: version = state_file.read() if version == expected_version: print('Python uninstalls unchanged, skipping...') return # Run pip to find the packages we need to get rid of. Believe it or not, # edx-val is installed in a way that it is present twice, so we have a loop # to really really get rid of it. for _ in range(3): uninstalled = False frozen = sh("pip freeze", capture=True) for package_name in PACKAGES_TO_UNINSTALL: if package_in_frozen(package_name, frozen): # Uninstall the pacakge sh("pip uninstall --disable-pip-version-check -y {}".format(package_name)) uninstalled = True if not uninstalled: break else: # We tried three times and didn't manage to get rid of the pests. print("Couldn't uninstall unwanted Python packages!") return # Write our version. with open(state_file_path, "wb") as state_file: state_file.write(expected_version.encode('utf-8')) def package_in_frozen(package_name, frozen_output): """Is this package in the output of 'pip freeze'?""" # Look for either: # # PACKAGE-NAME== # # or: # # blah_blah#egg=package_name-version # pattern = r"(?mi)^{pkg}==|#egg={pkg_under}-".format( pkg=re.escape(package_name), pkg_under=re.escape(package_name.replace("-", "_")), )
[ " return bool(re.search(pattern, frozen_output))" ]
1,046
lcc
python
null
cfdc68693b8867678092d17fdb043cc34839f37798d88a62
# -*- coding: utf-8 -*- """ Test for the pseudo-form implementation (odoo.tests.common.Form), which should basically be a server-side implementation of form views (though probably not complete) intended for properly validating business "view" flows (onchanges, readonly, required, ...) and make it easier to generate sensible & coherent business objects. """ from operator import itemgetter from odoo.tests.common import TransactionCase, Form class TestBasic(TransactionCase): def test_defaults(self): """ Checks that we can load a default form view and perform trivial default_get & onchanges & computations """ f = Form(self.env['test_testing_utilities.a']) self.assertEqual(f.id, False, "check that our record is not in db (yet)") self.assertEqual(f.f2, 42) self.assertEqual(f.f3, 21) self.assertEqual(f.f4, 42) f.f1 = 4 self.assertEqual(f.f2, 42) self.assertEqual(f.f3, 21) self.assertEqual(f.f4, 10) f.f2 = 8 self.assertEqual(f.f3, 4) self.assertEqual(f.f4, 2) r = f.save() self.assertEqual( (r.f1, r.f2, r.f3, r.f4), (4, 8, 4, 2), ) def test_required(self): f = Form(self.env['test_testing_utilities.a']) # f1 no default & no value => should fail with self.assertRaisesRegexp(AssertionError, 'f1 is a required field'): f.save() # set f1 and unset f2 => should work f.f1 = 1 f.f2 = False r = f.save() self.assertEqual( (r.f1, r.f2, r.f3, r.f4), (1, 0, 0, 0) ) def test_readonly(self): """ Checks that fields with readonly modifiers (marked as readonly or computed w/o set) raise an error when set. """ f = Form(self.env['test_testing_utilities.readonly']) with self.assertRaises(AssertionError): f.f1 = 5 with self.assertRaises(AssertionError): f.f2 = 42 def test_attrs(self): """ Checks that attrs/modifiers with non-normalized domains work """ f = Form(self.env['test_testing_utilities.a'], view='test_testing_utilities.non_normalized_attrs') # not readonly yet, should work f.f2 = 5 # make f2 readonly f.f1 = 63 f.f3 = 5 with self.assertRaises(AssertionError): f.f2 = 6 class TestM2O(TransactionCase): def test_default_and_onchange(self): """ Checks defaults & onchanges impacting m2o fields """ Sub = self.env['test_testing_utilities.m2o'] a = Sub.create({'name': "A"}) b = Sub.create({'name': "B"}) f = Form(self.env['test_testing_utilities.d']) self.assertEqual( f.f, a, "The default value for the m2o should be the first Sub record" ) f.f2 = "B" self.assertEqual( f.f, b, "The new m2o value should match the second field by name" ) f.save() def test_set(self): """ Checks that we get/set recordsets for m2o & that set correctly triggers onchange """ r1 = self.env['test_testing_utilities.m2o'].create({'name': "A"}) r2 = self.env['test_testing_utilities.m2o'].create({'name': "B"}) f = Form(self.env['test_testing_utilities.c']) # check that basic manipulations work f.f2 = r1 self.assertEqual(f.f2, r1) self.assertEqual(f.name, 'A') f.f2 = r2 self.assertEqual(f.name, 'B') # can't set an int to an m2o field with self.assertRaises(AssertionError): f.f2 = r1.id self.assertEqual(f.f2, r2) self.assertEqual(f.name, 'B') # can't set a record of the wrong model temp = self.env['test_testing_utilities.readonly'].create({}) with self.assertRaises(AssertionError): f.f2 = temp self.assertEqual(f.f2, r2) self.assertEqual(f.name, 'B') r = f.save() self.assertEqual(r.f2, r2) class TestM2M(TransactionCase): def test_add(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) r = f.save() self.assertEqual( r.m2m, r1 | r2 ) def test_remove_by_index(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) f.m2m.remove(index=0) r = f.save() self.assertEqual( r.m2m, r2 ) def test_remove_by_id(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) f.m2m.remove(id=r1.id) r = f.save() self.assertEqual( r.m2m, r2 ) def test_on_m2m_change(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) self.assertEqual(f.count, 0) f.m2m.add(Sub.create({'name': 'a'})) self.assertEqual(f.count, 1) f.m2m.add(Sub.create({'name': 'a'})) f.m2m.add(Sub.create({'name': 'a'})) f.m2m.add(Sub.create({'name': 'a'})) self.assertEqual(f.count, 4) f.m2m.remove(index=0) f.m2m.remove(index=0) f.m2m.remove(index=0) self.assertEqual(f.count, 1) def test_m2m_changed(self): Sub = self.env['test_testing_utilities.sub2'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) c = Sub.create({'name': 'c'}) d = Sub.create({'name': 'd'}) f = Form(self.env['test_testing_utilities.f']) # check default_get self.assertEqual(f.m2m[:], a | b) f.m2o = c self.assertEqual(f.m2m[:], a | b | c) f.m2o = d self.assertEqual(f.m2m[:], a | b | c | d) def test_m2m_readonly(self): Sub = self.env['test_testing_utilities.sub3'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) r = self.env['test_testing_utilities.g'].create({ 'm2m': [(6, 0, a.ids)] }) f = Form(r) with self.assertRaises(AssertionError): f.m2m.add(b) with self.assertRaises(AssertionError): f.m2m.remove(id=a.id) f.save() self.assertEqual(r.m2m, a) get = itemgetter('name', 'value', 'v') class TestO2M(TransactionCase): def test_basic_alterations(self): """ Tests that the o2m proxy allows adding, removing and editing o2m records """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent') f.subs.new().save() f.subs.new().save() f.subs.new().save() f.subs.remove(index=0) r = f.save() self.assertEqual( [get(s) for s in r.subs], [("2", 2, 2), ("2", 2, 2)] ) with Form(r, view='test_testing_utilities.o2m_parent') as f: with f.subs.new() as sub: sub.value = 5 f.subs.new().save() with f.subs.edit(index=2) as sub: self.assertEqual(sub.v, 5) f.subs.remove(index=0) self.assertEqual( [get(s) for s in r.subs], [("2", 2, 2), ("5", 5, 5), ("2", 2, 2)] ) with Form(r, view='test_testing_utilities.o2m_parent') as f, \ f.subs.edit(index=0) as sub,\ self.assertRaises(AssertionError): sub.name = "whop whop" def test_o2m_editable_list(self): """ Tests the o2m proxy when the list view is editable rather than delegating to a separate form view """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent_ed') with f.subs.new() as s: s.value = 1 with f.subs.new() as s: s.value = 3 with f.subs.new() as s: s.value = 7 r = f.save() self.assertEqual(r.v, 12) self.assertEqual( [get(s) for s in r.subs], [('1', 1, 1), ('3', 3, 3), ('7', 7, 7)] ) def test_o2m_inline(self): """ Tests the o2m proxy when the list and form views are provided inline rather than fetched separately """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent_inline') with f.subs.new() as s: s.value = 42 r = f.save() self.assertEqual( [get(s) for s in r.subs], [("0", 42, 0)], "should not have set v (and thus not name)" ) def test_o2m_default(self): """ Tests that default_get can return defaults for the o2m """ f = Form(self.env['test_testing_utilities.default']) with f.subs.edit(index=0) as s: self.assertEqual(s.v, 5) self.assertEqual(s.value, False) r = f.save() self.assertEqual( [get(s) for s in r.subs], [("5", 2, 5)] ) def test_o2m_inner_default(self): """ Tests that creating an o2m record will get defaults for it """ f = Form(self.env['test_testing_utilities.default']) with f.subs.new() as s: self.assertEqual(s.value, 2) self.assertEqual(s.v, 2, "should have onchanged value to v") def test_o2m_onchange_parent(self): """ Tests that changing o2m content triggers onchange in the parent """ f = Form(self.env['test_testing_utilities.parent']) self.assertEqual(f.value, 1, "value should have its default") self.assertEqual(f.v, 1, "v should be equal to value") f.subs.new().save() self.assertEqual(f.v, 3, "should be sum of value & children v") def test_o2m_onchange_inner(self): """ Tests that editing a field of an o2m record triggers onchange in the o2m record and its parent """ f = Form(self.env['test_testing_utilities.parent']) # only apply the onchange on edition end (?) with f.subs.new() as sub: sub.value = 6 self.assertEqual(sub.v, 6) self.assertEqual(f.v, 1) self.assertEqual(f.v, 7) def test_o2m_parent_content(self): """ Tests that when editing a field of an o2m the data sent contains the parent data """ f = Form(self.env['test_testing_utilities.parent']) # only apply the onchange on edition end (?) with f.subs.new() as sub: sub.has_parent = True self.assertEqual(sub.has_parent, True) self.assertEqual(sub.value, 1) self.assertEqual(sub.v, 1) def test_m2o_readonly(self): r = self.env['test_testing_utilities.parent'].create({
[ " 'subs': [(0, 0, {})]" ]
1,031
lcc
python
null
2bdd8408d0651a7c4efb3a83615391556c9a2af978875365
from sympy import ( Abs, And, binomial, Catalan, cos, Derivative, E, Eq, exp, EulerGamma, factorial, Function, harmonic, I, Integral, KroneckerDelta, log, nan, Ne, Or, oo, pi, Piecewise, Product, product, Rational, S, simplify, sin, sqrt, Sum, summation, Symbol, symbols, sympify, zeta, gamma, Le, Indexed, Idx, IndexedBase, prod) from sympy.abc import a, b, c, d, f, k, m, x, y, z from sympy.concrete.summations import telescopic from sympy.utilities.pytest import XFAIL, raises from sympy import simplify from sympy.matrices import Matrix from sympy.core.mod import Mod from sympy.core.compatibility import range n = Symbol('n', integer=True) def test_karr_convention(): # Test the Karr summation convention that we want to hold. # See his paper "Summation in Finite Terms" for a detailed # reasoning why we really want exactly this definition. # The convention is described on page 309 and essentially # in section 1.4, definition 3: # # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \sum_{m <= i < n} f(i) = 0 for m = n # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n # # It is important to note that he defines all sums with # the upper limit being *exclusive*. # In contrast, sympy and the usual mathematical notation has: # # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b) # # with the upper limit *inclusive*. So translating between # the two we find that: # # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # sum and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True) # A simple example with a concrete summand and symbolic limits. # The normal sum: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Sum(i**2, (i, a, b)).doit() # The reversed sum: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Sum(i**2, (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Sum(i**2, (i, a, b)).doit() assert Sz == 0 # Another example this time with an unspecified summand and # numeric limits. (We can not do both tests in the same example.) f = Function("f") # The normal sum with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Sum(f(i), (i, a, b)).doit() # The reversed sum with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Sum(f(i), (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Sum(f(i), (i, a, b)).doit() assert Sz == 0 e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True)) s = Sum(e, (i, 0, 11)) assert s.n(3) == s.doit().n(3) def test_karr_proposition_2a(): # Test Karr, page 309, proposition 2, part a i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) def test_the_sum(m, n): # g g = i**3 + 2*i**2 - 3*i # f = Delta g f = simplify(g.subs(i, i+1) - g) # The sum a = m b = n - 1 S = Sum(f, (i, a, b)).doit() # Test if Sum_{m <= i < n} f(i) = g(n) - g(m) assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0 # m < n test_the_sum(u, u+v) # m = n test_the_sum(u, u ) # m > n test_the_sum(u+v, u ) def test_karr_proposition_2b(): # Test Karr, page 309, proposition 2, part b i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) w = Symbol("w", integer=True) def test_the_sum(l, n, m): # Summand s = i**3 # First sum a = l b = n - 1 S1 = Sum(s, (i, a, b)).doit() # Second sum a = l b = m - 1 S2 = Sum(s, (i, a, b)).doit() # Third sum a = m b = n - 1 S3 = Sum(s, (i, a, b)).doit() # Test if S1 = S2 + S3 as required assert S1 - (S2 + S3) == 0 # l < m < n test_the_sum(u, u+v, u+v+w) # l < m = n test_the_sum(u, u+v, u+v ) # l < m > n test_the_sum(u, u+v+w, v ) # l = m < n test_the_sum(u, u, u+v ) # l = m = n test_the_sum(u, u, u ) # l = m > n test_the_sum(u+v, u+v, u ) # l > m < n test_the_sum(u+v, u, u+w ) # l > m = n test_the_sum(u+v, u, u ) # l > m > n test_the_sum(u+v+w, u+v, u ) def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a*x lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 3 and s2.doit() == 0 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 2*x + 1 and s2.doit() == 0 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1) assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2) assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum) assert summation(k, (k, 0, oo)) == oo def test_polynomial_sums(): assert summation(n**2, (n, 3, 8)) == 199 assert summation(n, (n, a, b)) == \ ((a + b)*(b - a + 1)/2).expand() assert summation(n**2, (n, 1, b)) == \ ((2*b**3 + 3*b**2 + b)/6).expand() assert summation(n**3, (n, 1, b)) == \ ((b**4 + 2*b**3 + b**2)/4).expand() assert summation(n**6, (n, 1, b)) == \ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand() def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(Rational(1, 2)**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) == oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) == -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - S(4)/3 assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S(1)/2 assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True)) # issue 8251: assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) == oo #issue 9908: assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2)) #issue 11642: result = Sum(0.5**n, (n, 1, oo)).doit() assert result == 1 assert result.is_Float result = Sum(0.25**n, (n, 1, oo)).doit() assert result == S(1)/3 assert result.is_Float result = Sum(0.99999**n, (n, 1, oo)).doit() assert result == 99999 assert result.is_Float result = Sum(Rational(1, 2)**n, (n, 1, oo)).doit() assert result == 1 assert not result.is_Float result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit() assert result == S(3)/2 assert not result.is_Float assert Sum(1.0**n, (n, 1, oo)).doit() == oo assert Sum(2.43**n, (n, 1, oo)).doit() == oo # Issue 13979: i, k, q = symbols('i k q', integer=True) result = summation( exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1) ) assert result.simplify() == Piecewise( (1, Eq(exp(2*I*pi*(-k + q)/n), 1)), (0, True) ) def test_harmonic_sums(): assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n)) assert summation(1/k, (k, 1, n)) == harmonic(n) assert summation(n/k, (k, 1, n)) == n*harmonic(n) assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4) def test_composite_sums(): f = Rational(1, 2)*(7 - 6*n + Rational(1, 7)*n**3) s = summation(f, (n, a, b)) assert not isinstance(s, Sum) A = 0 for i in range(-3, 5): A += f.subs(n, i) B = s.subs(a, -3).subs(b, 4) assert A == B def test_hypergeometric_sums(): assert summation( binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n def test_other_sums(): f = m**2 + m*exp(m) g = 3*exp(S(3)/2)/2 + exp(S(1)/2)/2 - exp(-S(1)/2)/2 - 3*exp(-S(3)/2)/2 + 5 assert summation(f, (m, -S(3)/2, S(3)/2)).expand() == g assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10) fac = factorial def NS(e, n=15, **options): return str(sympify(e).evalf(n, **options)) def test_evalf_fast_series(): # Euler transformed series for sqrt(1+x) assert NS(Sum( fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100) # Some series for exp(1) estr = NS(E, 100) assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr pistr = NS(pi, 100) # Ramanujan series for pi assert NS(9801/sqrt(8)/Sum(fac( 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr assert NS(1/Sum( binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr # Machin's formula for pi assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) - 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr # Apery's constant astr = NS(zeta(3), 100) P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \ n + 12463 assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac( n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 / fac(2*n + 1)**5, (n, 0, oo)), 100) == astr def test_evalf_fast_series_issue_4021(): # Catalan's constant assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3* fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \ NS(Catalan, 100) astr = NS(zeta(3), 100) assert NS(5*Sum( (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1) **3 / fac(3*n), (n, 1, oo))/4, 100) == astr def test_evalf_slow_series(): assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15) assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50) assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15) assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100) assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50) def test_euler_maclaurin(): # Exact polynomial sums with E-M def check_exact(f, a, b, m, n): A = Sum(f, (k, a, b)) s, e = A.euler_maclaurin(m, n) assert (e == 0) and (s.expand() == A.doit()) check_exact(k**4, a, b, 0, 2) check_exact(k**4 + 2*k, a, b, 1, 2) check_exact(k**4 + k**2, a, b, 1, 5) check_exact(k**5, 2, 6, 1, 2) check_exact(k**5, 2, 6, 1, 3) assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0) # Not exact assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0 # Numerical test for m, n in [(2, 4), (2, 20), (10, 20), (18, 20)]: A = Sum(1/k**3, (k, 1, oo)) s, e = A.euler_maclaurin(m, n) assert abs((s - zeta(3)).evalf()) < e.evalf() def test_evalf_euler_maclaurin(): assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266' assert NS(Sum(1/k**k, (k, 1, oo)), 50) == '1.2912859970626635404072825905956005414986193682745' assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15) assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50) assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844' assert NS(Sum(log(k)/k**2, (k, 1, oo)), 50) == '0.93754825431584375370257409456786497789786028861483' assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008' assert NS(Sum(1/k, (k, 1000000, 2000000)), 50) == '0.69314793056000780941723211364567656807940638436025' def test_evalf_symbolic(): f, g = symbols('f g', cls=Function) # issue 6328 expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3)) assert expr.evalf() == expr def test_evalf_issue_3273(): assert Sum(0, (k, 1, oo)).evalf() == 0 def test_simple_products(): assert Product(S.NaN, (x, 1, 3)) is S.NaN assert product(S.NaN, (x, 1, 3)) is S.NaN assert Product(x, (n, a, a)).doit() == x assert Product(x, (x, a, a)).doit() == a assert Product(x, (y, 1, a)).doit() == x**a lo, hi = 1, 2 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == 2 assert s2.doit() == 1 lo, hi = x, x + 1 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) s3 = 1 / Product(n, (n, hi + 1, lo - 1)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == x*(x + 1) assert s2.doit() == 1 assert s3.doit() == x*(x + 1) assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \ (y**2 + 1)*(y**2 + 3) assert product(2, (n, a, b)) == 2**(b - a + 1) assert product(n, (n, 1, b)) == factorial(b) assert product(n**3, (n, 1, b)) == factorial(b)**3 assert product(3**(2 + n), (n, a, b)) \ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2) assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2) assert isinstance(product(cos(n), (n, x, x + S.Half)), Product) # If Product managed to evaluate this one, it most likely got it wrong! assert isinstance(Product(n**n, (n, 1, b)), Product) def test_rational_products(): assert simplify(product(1 + 1/n, (n, a, b))) == (1 + b)/a assert simplify(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a) assert simplify(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1)) assert simplify(product(n/(n + 1)/(n + 2), (n, a, b))) == \ a*gamma(a + 2)/(b + 1)/gamma(b + 3) assert simplify(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2)) def test_wallis_product(): # Wallis product, given in two different forms to ensure that Product # can factor simple rational expressions A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b)) B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b)) R = pi*gamma(b + 1)**2/(2*gamma(b + S(1)/2)*gamma(b + S(3)/2)) assert simplify(A.doit()) == R assert simplify(B.doit()) == R # This one should eventually also be doable (Euler's product formula for sin) # assert Product(1+x/n**2, (n, 1, b)) == ... def test_telescopic_sums(): #checks also input 2 of comment 1 issue 4127 assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n) f = Function("f") assert Sum( f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m) assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3) # dummy variable shouldn't matter assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \ telescopic(1/k, -k/(1 + k), (k, n - 1, n)) assert Sum(1/x/(x - 1), (x, a, b)).doit() == -((a - b - 1)/(b*(a - 1))) def test_sum_reconstruct(): s = Sum(n**2, (n, -1, 1)) assert s == Sum(*s.args) raises(ValueError, lambda: Sum(x, x)) raises(ValueError, lambda: Sum(x, (x, 1))) def test_limit_subs(): for F in (Sum, Product, Integral): assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2) assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \ F(a, (a, c, 4)) assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1)) def test_function_subs(): f = Function("f") S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) assert S.subs(f(x),x) == S raises(ValueError, lambda: S.subs(f(y),x+y) ) S = Sum(x*log(y),(x,0,oo),(y,0,oo)) assert S.subs(log(y),y) == S f = Symbol('f') S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) def test_equality(): # if this fails remove special handling below raises(ValueError, lambda: Sum(x, x)) r = symbols('x', real=True) for F in (Sum, Product, Integral): try: assert F(x, x) != F(y, y) assert F(x, (x, 1, 2)) != F(x, x) assert F(x, (x, x)) != F(x, x) # or else they print the same assert F(1, x) != F(1, y) except ValueError: pass assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) assert F(1, (x, 1, x)) != F(1, (y, 1, x)) assert F(1, (x, 1, x)) != F(1, (y, 1, y)) # issue 5265 assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a)) def test_Sum_doit(): assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \ 3*Integral(a**2) assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2) # test nested sum evaluation s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n)) assert 0 == (s.doit() - n*(n+1)*(n-1)).factor() assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == Piecewise((1, And(-oo < n, n < oo)), (0, True)) assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == Piecewise((x, And(-oo < n, n < oo)), (0, True)) assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3 assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \ 3 * Piecewise((1, And(S(1) <= k, k <= 3)), (0, True)) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \ f(1) + f(2) + f(3) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \ Sum(Piecewise((f(n), And(Le(0, n), n < oo)), (0, True)), (n, 1, oo)) l = Symbol('l', integer=True, positive=True) assert Sum(f(l) * Sum(KroneckerDelta(m, l), (m, 0, oo)), (l, 1, oo)).doit() == \ Sum(f(l), (l, 1, oo)) # issue 2597 nmax = symbols('N', integer=True, positive=True) pw = Piecewise((1, And(S(1) <= n, n <= nmax)), (0, True)) assert Sum(pw, (n, 1, nmax)).doit() == Sum(pw, (n, 1, nmax)) q, s = symbols('q, s') assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1), (Sum(n**(-2*s), (n, 1, oo)), True)) assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1), (Sum((n + 1)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise( (zeta(s, q), And(q > 0, s > 1)), (Sum((n + q)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise( (zeta(s, 2*q), And(2*q > 0, s > 1)), (Sum((n + q)**(-s), (n, q, oo)), True)) assert summation(1/n**2, (n, 1, oo)) == zeta(2) assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo)) def test_Product_doit(): assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9 assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \ 6*Integral(a**2)**3 assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3 def test_Sum_interface(): assert isinstance(Sum(0, (n, 0, 2)), Sum) assert Sum(nan, (n, 0, 2)) is nan assert Sum(nan, (n, 0, oo)) is nan assert Sum(0, (n, 0, 2)).doit() == 0 assert isinstance(Sum(0, (n, 0, oo)), Sum) assert Sum(0, (n, 0, oo)).doit() == 0 raises(ValueError, lambda: Sum(1)) raises(ValueError, lambda: summation(1)) def test_eval_diff(): assert Sum(x, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2)) e = Sum(x*y, (x, 1, a)) assert e.diff(a) == Derivative(e, a) assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24 def test_hypersum(): from sympy import sin assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == -S(9)/8 + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m def test_issue_4170(): assert summation(1/factorial(k), (k, 0, oo)) == E def test_is_commutative(): from sympy.physics.secondquant import NO, F, Fd m = Symbol('m', commutative=False) for f in (Sum, Product, Integral): assert f(z, (z, 1, 1)).is_commutative is True assert f(z*y, (z, 1, 6)).is_commutative is True assert f(m*x, (x, 1, 2)).is_commutative is False assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False def test_is_zero(): for func in [Sum, Product]: assert func(0, (x, 1, 1)).is_zero is True assert func(x, (x, 1, 1)).is_zero is None def test_is_number(): # is number should not rely on evaluation or assumptions, # it should be equivalent to `not foo.free_symbols` assert Sum(1, (x, 1, 1)).is_number is True assert Sum(1, (x, 1, x)).is_number is False assert Sum(0, (x, y, z)).is_number is False assert Sum(x, (y, 1, 2)).is_number is False assert Sum(x, (y, 1, 1)).is_number is False assert Sum(x, (x, 1, 2)).is_number is True assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Product(2, (x, 1, 1)).is_number is True assert Product(2, (x, 1, y)).is_number is False assert Product(0, (x, y, z)).is_number is False assert Product(1, (x, y, z)).is_number is False assert Product(x, (y, 1, x)).is_number is False assert Product(x, (y, 1, 2)).is_number is False assert Product(x, (y, 1, 1)).is_number is False assert Product(x, (x, 1, 2)).is_number is True def test_free_symbols(): for func in [Sum, Product]: assert func(1, (x, 1, 2)).free_symbols == set() assert func(0, (x, 1, y)).free_symbols == {y} assert func(2, (x, 1, y)).free_symbols == {y} assert func(x, (x, 1, 2)).free_symbols == set() assert func(x, (x, 1, y)).free_symbols == {y} assert func(x, (y, 1, y)).free_symbols == {x, y} assert func(x, (y, 1, 2)).free_symbols == {x} assert func(x, (y, 1, 1)).free_symbols == {x} assert func(x, (y, 1, z)).free_symbols == {x, z} assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set() assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z} assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y} assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z} assert Sum(1, (x, 1, y)).free_symbols == {y} # free_symbols answers whether the object *as written* has free symbols, # not whether the evaluated expression has free symbols assert Product(1, (x, 1, y)).free_symbols == {y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Sum(A*B**n, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_issue_4171(): assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) == oo assert summation(2*k + 1, (k, 0, oo)) == oo def test_issue_6273(): assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == 1 def test_issue_6274(): assert Sum(x, (x, 1, 0)).doit() == 0 assert NS(Sum(x, (x, 1, 0))) == '0' assert Sum(n, (n, 10, 5)).doit() == -30 assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000' def test_simplify(): y, t, v = symbols('y, t, v') assert simplify(Sum(x*y, (x, n, m), (y, a, k)) + \ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k)) assert simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \ Sum(x, (x, n, a)) assert simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \ Sum(x, (x, n, a)) assert simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \ Sum(x, (x, n, a)) + Sum(1, (x, n, k)) assert simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6)) assert simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \ Sum(x*(3*x + 1), (x, a, b)) assert simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \ 4 * y * Sum(z, (z, n, k))) + 1 == \ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1 assert simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \ 1 + Sum(x, (x, a, c)) assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \ simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c))) assert simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b)) assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596 assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596 assert simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \ (Sum(x, (x, a, b)) / 3) assert simplify(Sum(Function('f')(x) * y * z, (x, a, b)) / (y * z)) \ == Sum(Function('f')(x), (x, a, b)) assert simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0 assert simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b))) assert simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \ c * (y + 1) * Sum(x, (x, a, b)) assert simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum(x, (x, a, b), (y, a, b)) assert simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b)) assert simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b)) assert simplify(Sum(Sum(d * t, (x, a, b - 1)) + \ Sum(d * t, (x, b, c)), (t, a, b))) == \ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b)) def test_change_index():
[ " b, v = symbols('b, v', integer = True)" ]
4,519
lcc
python
null
77bc1815b31202f2c431f0bd2c1ea65d6386dcbf74514e10
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_WWW : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); UnityEngine.WWW o; if(argc==2){ System.String a1; checkType(l,2,out a1); o=new UnityEngine.WWW(a1); pushValue(l,true); pushValue(l,o); return 2; } else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.WWWForm))){ System.String a1; checkType(l,2,out a1); UnityEngine.WWWForm a2; checkType(l,3,out a2); o=new UnityEngine.WWW(a1,a2); pushValue(l,true); pushValue(l,o); return 2; } else if(matchType(l,argc,2,typeof(string),typeof(System.Byte[]))){ System.String a1; checkType(l,2,out a1); System.Byte[] a2; checkArray(l,3,out a2); o=new UnityEngine.WWW(a1,a2); pushValue(l,true); pushValue(l,o); return 2; } else if(argc==4){ System.String a1; checkType(l,2,out a1); System.Byte[] a2; checkArray(l,3,out a2); System.Collections.Generic.Dictionary<System.String,System.String> a3; checkType(l,4,out a3); o=new UnityEngine.WWW(a1,a2,a3); pushValue(l,true); pushValue(l,o); return 2; } return error(l,"New object failed."); } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Dispose(IntPtr l) { try { UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); self.Dispose(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int InitWWW(IntPtr l) { try { UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.String a1; checkType(l,2,out a1); System.Byte[] a2; checkArray(l,3,out a2); System.String[] a3; checkArray(l,4,out a3); self.InitWWW(a1,a2,a3); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetAudioClip(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==2){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); var ret=self.GetAudioClip(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); System.Boolean a2; checkType(l,3,out a2); var ret=self.GetAudioClip(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); System.Boolean a2; checkType(l,3,out a2); UnityEngine.AudioType a3; checkEnum(l,4,out a3); var ret=self.GetAudioClip(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetAudioClipCompressed(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==1){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); var ret=self.GetAudioClipCompressed(); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==2){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); var ret=self.GetAudioClipCompressed(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==3){ UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); System.Boolean a1; checkType(l,2,out a1); UnityEngine.AudioType a2; checkEnum(l,3,out a2); var ret=self.GetAudioClipCompressed(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int LoadImageIntoTexture(IntPtr l) { try { UnityEngine.WWW self=(UnityEngine.WWW)checkSelf(l); UnityEngine.Texture2D a1; checkType(l,2,out a1); self.LoadImageIntoTexture(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int EscapeURL_s(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==1){ System.String a1; checkType(l,1,out a1); var ret=UnityEngine.WWW.EscapeURL(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==2){ System.String a1; checkType(l,1,out a1); System.Text.Encoding a2; checkType(l,2,out a2); var ret=UnityEngine.WWW.EscapeURL(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int UnEscapeURL_s(IntPtr l) { try {
[ "\t\t\tint argc = LuaDLL.lua_gettop(l);" ]
427
lcc
csharp
null
124c1846577ae2e5fcc64e558a68b1f71e80770b1c6f377f
using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Collections.Specialized { #if !NETFX_CORE public class NotifyCollectionChangedEventArgs : EventArgs { #region " Attributes " private NotifyCollectionChangedAction _notifyAction; private IList _newItemList; private int _newStartingIndex; private IList _oldItemList; private int _oldStartingIndex; #endregion #region " Constructors " public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Reset) { throw new ArgumentException("Wrong Action For Ctor", "action"); } this.InitializeAdd(action, null, -1); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove)) && (action != NotifyCollectionChangedAction.Reset)) { throw new ArgumentException("Must Be Reset Add Or Remove Action For Ctor", "action"); } if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) { throw new ArgumentException("Reset Action Requires Null Item", "action"); } this.InitializeAdd(action, null, -1); } else { if (changedItems == null) { throw new ArgumentNullException("changed Items"); } this.InitializeAddOrRemove(action, changedItems, -1); } } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, Object changedItem) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove)) && (action != NotifyCollectionChangedAction.Reset)) { throw new ArgumentException("Must Be Reset Add Or Remove Action For Ctor", "action"); } if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) { throw new ArgumentException("Reset Action Requires Null Item", "action"); } this.InitializeAdd(action, null, -1); } else { this.InitializeAddOrRemove(action, new object[] { changedItem }, -1); } } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException("Wrong Action For Ctor", "action"); } if (newItems == null) { throw new ArgumentNullException("new Items"); } if (oldItems == null) { throw new ArgumentNullException("old Items"); } this.InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove)) && (action != NotifyCollectionChangedAction.Reset)) { throw new ArgumentException("Must Be Reset Add Or Remove Action For Ctor", "action"); } if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) { throw new ArgumentException("Reset Action Requires Null Item", "action"); } if (startingIndex != -1) { throw new ArgumentException("Reset Action Requires Index Minus 1", "action"); } this.InitializeAdd(action, null, -1); } else { if (changedItems == null) { throw new ArgumentNullException("changed Items"); } if (startingIndex < -1) { throw new ArgumentException("Index Cannot Be Negative", "startingIndex"); } this.InitializeAddOrRemove(action, changedItems, startingIndex); } } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, Object changedItem, int index) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove)) && (action != NotifyCollectionChangedAction.Reset)) { throw new ArgumentException("Must Be Reset Add Or Remove Action For Ctor", "action"); } if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) { throw new ArgumentException("Reset Action Requires Null Item", "action"); } if (index != -1) { throw new ArgumentException("Reset Action Requires Index Minus 1", "action"); } this.InitializeAdd(action, null, -1); } else { this.InitializeAddOrRemove(action, new object[] { changedItem }, index); } } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, Object newItem, Object oldItem) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException("Wrong Action For Ctor", "action"); } this.InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, -1, -1); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException("Wrong Action For Ctor", "action"); } if (newItems == null) { throw new ArgumentNullException("new Items"); } if (oldItems == null) { throw new ArgumentNullException("old Items"); } this.InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Move) { throw new ArgumentException("Wrong Action For Ctor", "action"); } if (index < 0) { throw new ArgumentException("Index Cannot Be Negative", "index"); } this.InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, Object changedItem, int index, int oldIndex) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Move) { throw new ArgumentException("Wrong Action For Ctor", "action"); } if (index < 0) { throw new ArgumentException("Index Cannot Be Negative", "index"); } object[] newItems = new object[] { changedItem }; this.InitializeMoveOrReplace(action, newItems, newItems, index, oldIndex); } public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, Object newItem, Object oldItem, int index) { this._newStartingIndex = -1; this._oldStartingIndex = -1; if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException("Wrong Action For Ctor", "action"); } this.InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, index, index); } #endregion #region " Methods " private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { this._notifyAction = action; this._newItemList = (newItems == null) ? null : ArrayList.ReadOnly(newItems); this._newStartingIndex = newStartingIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) {
[ " this.InitializeAdd(action, changedItems, startingIndex);" ]
756
lcc
csharp
null
b64722de0a50cd03fec807399570eeb10ac2b39da7a8d5e3
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.Calendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; import javax.xml.validation.Schema; import javax.xml.validation.TypeInfoProvider; import javax.xml.validation.Validator; import javax.xml.validation.ValidatorHandler; import org.eclipse.persistence.internal.oxm.record.XMLEventReaderInputSource; import org.eclipse.persistence.internal.oxm.record.XMLEventReaderReader; import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderInputSource; import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.XMLMarshaller; import org.eclipse.persistence.oxm.XMLRoot; import org.eclipse.persistence.oxm.XMLUnmarshaller; import org.eclipse.persistence.oxm.XMLUnmarshallerHandler; import org.eclipse.persistence.platform.xml.SAXDocumentBuilder; import org.eclipse.persistence.sessions.Project; import org.eclipse.persistence.testing.oxm.OXTestCase; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; public abstract class XMLMappingTestCases extends OXTestCase { protected Document controlDocument; protected Document writeControlDocument; protected XMLMarshaller xmlMarshaller; protected XMLUnmarshaller xmlUnmarshaller; protected XMLContext xmlContext; public String resourceName; protected DocumentBuilder parser; protected Project project; protected String controlDocumentLocation; protected String writeControlDocumentLocation; protected boolean expectsMarshalException; private boolean shouldRemoveEmptyTextNodesFromControlDoc = true; public XMLMappingTestCases(String name) throws Exception { super(name); setupParser(); } public boolean isUnmarshalTest() { return true; } public void setupControlDocs() throws Exception{ if(this.controlDocumentLocation != null) { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(controlDocumentLocation); resourceName = controlDocumentLocation; controlDocument = parser.parse(inputStream); if (shouldRemoveEmptyTextNodesFromControlDoc()) { removeEmptyTextNodes(controlDocument); } inputStream.close(); } if(this.writeControlDocumentLocation != null) { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(writeControlDocumentLocation); writeControlDocument = parser.parse(inputStream); if (shouldRemoveEmptyTextNodesFromControlDoc()) { removeEmptyTextNodes(writeControlDocument); } inputStream.close(); } } public void setUp() throws Exception { setupParser(); setupControlDocs(); xmlContext = getXMLContext(project); xmlMarshaller = createMarshaller(); xmlUnmarshaller = xmlContext.createUnmarshaller(); } protected XMLMarshaller createMarshaller() { XMLMarshaller xmlMarshaller = xmlContext.createMarshaller(); xmlMarshaller.setFormattedOutput(false); return xmlMarshaller; } public void tearDown() { parser = null; xmlContext = null; xmlMarshaller = null; xmlUnmarshaller = null; controlDocument = null; controlDocumentLocation = null; } protected void setupParser() { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringElementContentWhitespace(true); parser = builderFactory.newDocumentBuilder(); } catch (Exception e) { e.printStackTrace(); fail("An exception occurred during setup"); } } protected void setSession(String sessionName) { xmlContext = getXMLContext(sessionName); xmlMarshaller = xmlContext.createMarshaller(); xmlMarshaller.setFormattedOutput(false); xmlUnmarshaller = xmlContext.createUnmarshaller(); } protected void setProject(Project project) { this.project = project; } protected Document getControlDocument() { return controlDocument; } /** * Override this function to implement different read/write control documents. * @return * @throws Exception */ protected Document getWriteControlDocument() throws Exception { if(writeControlDocument != null){ return writeControlDocument; } return getControlDocument(); } protected void setControlDocument(String xmlResource) throws Exception { this.controlDocumentLocation = xmlResource; } /** * Provide an alternative write version of the control document when rountrip is not enabled. * If this function is not called and getWriteControlDocument() is not overridden then the write and read control documents are the same. * @param xmlResource * @throws Exception */ protected void setWriteControlDocument(String xmlResource) throws Exception { writeControlDocumentLocation = xmlResource; } abstract protected Object getControlObject(); /* * Returns the object to be used in a comparison on a read * This will typically be the same object used to write */ public Object getReadControlObject() { return getControlObject(); } /* * Returns the object to be written to XML which will be compared * to the control document. */ public Object getWriteControlObject() { return getControlObject(); } public void testXMLToObjectFromInputStream() throws Exception { if(isUnmarshalTest()) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); Object testObject = xmlUnmarshaller.unmarshal(instream); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromNode() throws Exception { if(isUnmarshalTest()) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); Node node = parser.parse(instream); Object testObject = xmlUnmarshaller.unmarshal(node); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromXMLStreamReader() throws Exception { if(isUnmarshalTest() && null != XML_INPUT_FACTORY) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); XMLStreamReader xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(instream); XMLStreamReaderReader staxReader = new XMLStreamReaderReader(); staxReader.setErrorHandler(xmlUnmarshaller.getErrorHandler()); XMLStreamReaderInputSource inputSource = new XMLStreamReaderInputSource(xmlStreamReader); Object testObject = xmlUnmarshaller.unmarshal(staxReader, inputSource); instream.close(); xmlToObjectTest(testObject); } } public void testXMLToObjectFromXMLEventReader() throws Exception { if(isUnmarshalTest() && null != XML_INPUT_FACTORY) { InputStream instream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream(resourceName); XMLEventReader xmlEventReader = XML_INPUT_FACTORY.createXMLEventReader(instream); XMLEventReaderReader staxReader = new XMLEventReaderReader(); staxReader.setErrorHandler(xmlUnmarshaller.getErrorHandler()); XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(xmlEventReader); Object testObject = xmlUnmarshaller.unmarshal(staxReader, inputSource); instream.close(); xmlToObjectTest(testObject); } } public void xmlToObjectTest(Object testObject) throws Exception { log("\n**xmlToObjectTest**"); log("Expected:"); Object controlObject = getReadControlObject(); if(null == controlObject) { log((String) null); } else { log(controlObject.toString()); } log("Actual:"); if(null == testObject) { log((String) null); } else { log(testObject.toString()); } if ((getReadControlObject() instanceof XMLRoot) && (testObject instanceof XMLRoot)) { XMLRoot controlObj = (XMLRoot)getReadControlObject(); XMLRoot testObj = (XMLRoot)testObject; compareXMLRootObjects(controlObj, testObj); } else { assertEquals(getReadControlObject(), testObject); } } public static void compareXMLRootObjects(XMLRoot controlObj, XMLRoot testObj) { assertEquals(controlObj.getLocalName(), testObj.getLocalName()); assertEquals(controlObj.getNamespaceURI(), testObj.getNamespaceURI()); if (null != controlObj.getObject() && null != testObj.getObject() && controlObj.getObject() instanceof java.util.Calendar && testObj.getObject() instanceof java.util.Calendar) { assertTrue(((Calendar)controlObj.getObject()).getTimeInMillis() == ((Calendar)testObj.getObject()).getTimeInMillis()); } else { assertEquals(controlObj.getObject(), testObj.getObject()); } assertEquals(controlObj.getSchemaType(), testObj.getSchemaType()); } public void objectToXMLDocumentTest(Document testDocument) throws Exception { log("**objectToXMLDocumentTest**"); log("Expected:"); log(getWriteControlDocument()); log("\nActual:"); log(testDocument); assertXMLIdentical(getWriteControlDocument(), testDocument); } public void testObjectToXMLDocument() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); Document testDocument; try { testDocument = xmlMarshaller.objectToXML(objectToWrite); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); objectToXMLDocumentTest(testDocument); } public void testObjectToXMLStringWriter() throws Exception { StringWriter writer = new StringWriter(); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); try { xmlMarshaller.marshal(objectToWrite, writer); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } public void testValidatingMarshal() throws Exception { StringWriter writer = new StringWriter(); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); XMLMarshaller validatingMarshaller = createMarshaller(); validatingMarshaller.setSchema(FakeSchema.INSTANCE); try { validatingMarshaller.marshal(objectToWrite, writer); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } StringReader reader = new StringReader(writer.toString()); InputSource inputSource = new InputSource(reader); Document testDocument = parser.parse(inputSource); writer.close(); reader.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToOutputStream() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { xmlMarshaller.marshal(objectToWrite, stream); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); InputStream is = new ByteArrayInputStream(stream.toByteArray()); Document testDocument = parser.parse(is); stream.close(); is.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToOutputStreamASCIIEncoding() throws Exception { Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { xmlMarshaller.setEncoding("US-ASCII"); xmlMarshaller.marshal(objectToWrite, stream); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } int sizeAfter = getNamespaceResolverSize(desc); assertEquals(sizeBefore, sizeAfter); InputStream is = new ByteArrayInputStream(stream.toByteArray()); Document testDocument = parser.parse(is); stream.close(); is.close(); objectToXMLDocumentTest(testDocument); } public void testObjectToXMLStreamWriter() throws Exception { if(XML_OUTPUT_FACTORY != null && staxResultClass != null) { StringWriter writer = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(factory.IS_REPAIRING_NAMESPACES, new Boolean(false)); XMLStreamWriter streamWriter= factory.createXMLStreamWriter(writer); Object objectToWrite = getWriteControlObject(); XMLDescriptor desc = null; if (objectToWrite instanceof XMLRoot) { XMLRoot xmlRoot = (XMLRoot) objectToWrite; if(null != xmlRoot.getObject()) { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(((XMLRoot)objectToWrite).getObject().getClass()); } } else { desc = (XMLDescriptor)xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass()); } int sizeBefore = getNamespaceResolverSize(desc); Result result = (Result)PrivilegedAccessHelper.invokeConstructor(staxResultStreamWriterConstructor, new Object[]{streamWriter}); try { xmlMarshaller.marshal(objectToWrite, result); } catch(Exception e) { assertMarshalException(e); return; } if(expectsMarshalException){ fail("An exception should have occurred but didn't."); return; } streamWriter.flush();
[ " int sizeAfter = getNamespaceResolverSize(desc);" ]
1,329
lcc
java
null
8a2fd200c0170fc660f3939cf1ac96106dc7e05cbcd739ea
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CmsData.QueryBuilder; using UtilityExtensions; namespace CmsData { public class QueryParser { private readonly QueryLexer lexer; private readonly string text; public QueryParser(string s) { text = s; lexer = new QueryLexer(s); } private string PositionLine => lexer.Line.HasValue() ? $"{lexer.Line.Insert(lexer.Position, "^")}" : ""; private Token Token => lexer.Token; private void NextToken(params TokenType[] args) { if (lexer.Next() == false) Token.Type = TokenType.RParen; if (args.Contains(Token.Type)) return; if (Token.Type == TokenType.String && !Token.Text.HasValue()) // allow empty string for Int return; if (Token.Type == TokenType.Name && args.Contains(TokenType.Int) && Token.Text.Equal("true")) { Token.Text = "1[True]"; Token.Type = TokenType.Int; return; } throw new QueryParserException($@"Expected {string.Join(",", args.Select(aa => aa.ToString()))} {PositionLine} "); } private void NextToken(string text) { lexer.Next(); if (Token.Text != text) throw new QueryParserException($"Expected {text}"); } private void ParseCondition(Condition p = null) { var allClauses = p == null ? new Dictionary<Guid, Condition>() : p.AllConditions; Guid? parentGuid = null; if (p != null) parentGuid = p.Id; var c = new Condition { ParentId = parentGuid, Id = Guid.NewGuid(), AllConditions = allClauses }; p?.AllConditions.Add(c.Id, c); switch (Token.Type) { case TokenType.LParen: c.ConditionName = "Group"; ParseConditions(c); return; case TokenType.Name: c.ConditionName = Token.Text; break; case TokenType.Func: c.ConditionName = Token.Text; NextToken(TokenType.LParen); do ParseParam(c); while (Token.Type == TokenType.Comma); if (Token.Type != TokenType.RParen) throw new QueryParserException("missing ) on function parameters"); break; } NextToken(TokenType.Op); // get operator var op = Token; if (op.Text.Contains("IN")) { NextToken(TokenType.LParen); var expect = c.FieldInfo.Type == FieldType.CodeStr ? TokenType.String : TokenType.Int; var inlist = new List<string>(); do { NextToken(expect, TokenType.RParen); if (Token.Type == TokenType.RParen) continue; inlist.Add(Token2Csv()); NextToken(TokenType.Comma, TokenType.RParen); } while (Token.Type == TokenType.Comma); var s = string.Join(";", expect == TokenType.Int ? inlist.Where(vv => vv.HasValue()) : inlist); c.SetComparisonType(op.Text.StartsWith("NOT") ? CompareType.NotOneOf : CompareType.OneOf); SetRightSideOneOf(c, s); } else { NextToken(TokenType.String, TokenType.Int, TokenType.Num); if (Token.Type == TokenType.String && c.Compare2.ValueType() == "text") switch (op.Text) { case "=": if (Token.Text.StartsWith("*") && Token.Text.EndsWith("*")) c.SetComparisonType(CompareType.Contains); else if (Token.Text.StartsWith("*")) c.SetComparisonType(CompareType.EndsWith); else if (Token.Text.EndsWith("*")) c.SetComparisonType(CompareType.StartsWith); else c.SetComparisonType(CompareType.Equal); Token.Text = Token.Text.Trim('*'); break; case "<>": if (Token.Text.StartsWith("*") && Token.Text.EndsWith("*")) c.SetComparisonType(CompareType.DoesNotContain); else if (Token.Text.StartsWith("*")) c.SetComparisonType(CompareType.DoesNotEndWith); else if (Token.Text.EndsWith("*")) c.SetComparisonType(CompareType.DoesNotStartWith); else c.SetComparisonType(CompareType.NotEqual); Token.Text = Token.Text.Trim('*'); break; case ">": c.SetComparisonType(CompareType.After); break; case "<": c.SetComparisonType(CompareType.Before); break; case ">=": c.SetComparisonType(CompareType.AfterOrSame); break; case "<=": c.SetComparisonType(CompareType.BeforeOrSame); break; } else switch (op.Text) { case "=": c.SetComparisonType(CompareType.Equal); break; case "<>": c.SetComparisonType(CompareType.NotEqual); break; case ">": c.SetComparisonType(CompareType.Greater); break; case "<": c.SetComparisonType(CompareType.Less); break; case ">=": c.SetComparisonType(CompareType.GreaterEqual); break; case "<=": c.SetComparisonType(CompareType.LessEqual); break; } SetRightSide(c); } } public Condition ParseConditions(Condition g) { NextToken(TokenType.Name, TokenType.Func, TokenType.Not, TokenType.LParen); if (Token.Type == TokenType.Not) { g.SetComparisonType(CompareType.AllFalse); NextToken(TokenType.Name, TokenType.Func, TokenType.LParen); } while (Token.Type != TokenType.RParen) { ParseCondition(g); if (Token.Type == TokenType.RParen) { if (!g.Comparison.HasValue()) g.SetComparisonType(CompareType.AllTrue); NextToken(TokenType.And, TokenType.Or, TokenType.RParen, TokenType.AndNot); return g; } SetComparisionType(g); NextToken(TokenType.Name, TokenType.Func, TokenType.LParen); } throw new QueryParserException("missing ) in Group"); } private void SetComparisionType(Condition g) { CheckAndOrNotConsistency(g); if (!g.Comparison.HasValue()) switch (Token.Type) { case TokenType.And: g.SetComparisonType(CompareType.AllTrue); break; case TokenType.Or: g.SetComparisonType(CompareType.AnyTrue); break; case TokenType.AndNot: g.SetComparisonType(CompareType.AllFalse); break; } } private void CheckAndOrNotConsistency(Condition g) { if (!g.Comparison.HasValue()) return; if (g.ComparisonType == CompareType.AllFalse && Token.Type != TokenType.AndNot) throw new QueryParserException("Expected AND NOT in AllFalse group"); if (g.ComparisonType == CompareType.AllTrue && Token.Type != TokenType.And) throw new QueryParserException("Expected AND in AllTrue group"); if (g.ComparisonType == CompareType.AnyTrue && Token.Type != TokenType.Or) throw new QueryParserException("Expected OR in AnyTrue group"); } private void SetRightSide(Condition c, StringBuilder sb = null) { var s = sb?.ToString() ?? Token.Text; if (c.Compare2 == null) c.TextValue = null; else switch (c.Compare2.ValueType()) { case "text": c.TextValue = s.Replace("''", "'"); if (!c.TextValue.HasValue()) c.TextValue = null; break; case "number": c.TextValue = s.Replace("''", "'"); break; case "idtext": case "idvalue": c.CodeIdValue = Token2Csv(); break; case "date": c.DateValue = s.ToDate(); break; } NextToken(TokenType.And, TokenType.Or, TokenType.AndNot, TokenType.RParen); } private void SetRightSideOneOf(Condition c, string s = null) { c.CodeIdValue = s ?? Token.Text; NextToken(TokenType.And, TokenType.Or, TokenType.AndNot, TokenType.RParen); } private void ParseParam(Condition c) { NextToken(TokenType.Name, TokenType.RParen); if (Token.Type == TokenType.RParen) return; var param = ParamEnum(Token.Text); NextToken("="); NextToken(TokenType.String, TokenType.Int); switch (param) { case Param.Program: c.Program = Token2Csv(); break; case Param.Division: c.Division = Token2Csv(); break; case Param.Organization: c.Organization = Token2Csv(); break; case Param.Schedule: c.Schedule = Token2Csv(); break; case Param.OrgName: c.OrgName = Token2Csv(); break; case Param.OrgStatus: c.OrgStatus = Token2Csv(); break; case Param.StartDate: c.StartDate = Token.Text.ToDate(); break; case Param.EndDate: c.EndDate = Token.Text.ToDate(); break; case Param.Quarters: c.Quarters = Token.Text.Replace("''", "'"); break; case Param.Age: c.Age = Token.Text.ToInt2(); break; case Param.Days: c.Days = Token.Text.ToInt(); break; case Param.Ministry: c.Ministry = Token2Csv(); break; case Param.OnlineReg: c.OnlineReg = Token2Csv(); break; case Param.OrgType2: c.OrgType2 = Token2Csv().ToInt(); break; case Param.Campus:
[ " c.Campus = Token2Csv();" ]
714
lcc
csharp
null
c6257bab33edefa6c3e6aa0a9b46d09d5375b9c450a0c307
// // System.Drawing.Icon.cs // // Authors: // Gary Barnett (gary.barnett.mono@gmail.com) // Dennis Hayes (dennish@Raytek.com) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // Sanjay Gupta (gsanjay@novell.com) // Peter Dennis Bartok (pbartok@novell.com) // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2002 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004-2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.ComponentModel; using System.Drawing.Imaging; using System.IO; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Security.Permissions; namespace System.Drawing { #if !NET_2_0 [ComVisible (false)] #endif [Serializable] #if !MONOTOUCH [Editor ("System.Drawing.Design.IconEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))] #endif [TypeConverter(typeof(IconConverter))] public sealed class Icon : MarshalByRefObject, ISerializable, ICloneable, IDisposable { [StructLayout(LayoutKind.Sequential)] internal struct IconDirEntry { internal byte width; // Width of icon internal byte height; // Height of icon internal byte colorCount; // colors in icon internal byte reserved; // Reserved internal ushort planes; // Color Planes internal ushort bitCount; // Bits per pixel internal uint bytesInRes; // bytes in resource internal uint imageOffset; // position in file internal bool ignore; // for unsupported images (vista 256 png) }; [StructLayout(LayoutKind.Sequential)] internal struct IconDir { internal ushort idReserved; // Reserved internal ushort idType; // resource type (1 for icons) internal ushort idCount; // how many images? internal IconDirEntry [] idEntries; // the entries for each image }; [StructLayout(LayoutKind.Sequential)] internal struct BitmapInfoHeader { internal uint biSize; internal int biWidth; internal int biHeight; internal ushort biPlanes; internal ushort biBitCount; internal uint biCompression; internal uint biSizeImage; internal int biXPelsPerMeter; internal int biYPelsPerMeter; internal uint biClrUsed; internal uint biClrImportant; }; [StructLayout(LayoutKind.Sequential)] // added baseclass for non bmp image format support internal abstract class ImageData { }; [StructLayout(LayoutKind.Sequential)] internal class IconImage : ImageData { internal BitmapInfoHeader iconHeader; //image header internal uint [] iconColors; //colors table internal byte [] iconXOR; // bits for XOR mask internal byte [] iconAND; //bits for AND mask }; [StructLayout(LayoutKind.Sequential)] internal class IconDump : ImageData { internal byte [] data; }; private Size iconSize; private IntPtr handle = IntPtr.Zero; private IconDir iconDir; private ushort id; private ImageData [] imageData; private bool undisposable; private bool disposed; private Bitmap bitmap; private Icon () { } #if !MONOTOUCH private Icon (IntPtr handle) { this.handle = handle; bitmap = Bitmap.FromHicon (handle); iconSize = new Size (bitmap.Width, bitmap.Height); if (GDIPlus.RunningOnUnix ()) { bitmap = Bitmap.FromHicon (handle); iconSize = new Size (bitmap.Width, bitmap.Height); // FIXME: we need to convert the bitmap into an icon } else { IconInfo ii; GDIPlus.GetIconInfo (handle, out ii); if (!ii.IsIcon) throw new NotImplementedException (Locale.GetText ("Handle doesn't represent an ICON.")); // If this structure defines an icon, the hot spot is always in the center of the icon iconSize = new Size (ii.xHotspot * 2, ii.yHotspot * 2); bitmap = (Bitmap) Image.FromHbitmap (ii.hbmColor); } undisposable = true; } #endif public Icon (Icon original, int width, int height) : this (original, new Size (width, height)) { } public Icon (Icon original, Size size) { if (original == null) throw new ArgumentException ("original"); iconSize = size; iconDir = original.iconDir; int count = iconDir.idCount; if (count > 0) { imageData = original.imageData; id = UInt16.MaxValue; for (ushort i=0; i < count; i++) { IconDirEntry ide = iconDir.idEntries [i]; if (((ide.height == size.Height) || (ide.width == size.Width)) && !ide.ignore) { id = i; break; } } // if a perfect match isn't found we look for the biggest icon *smaller* than specified if (id == UInt16.MaxValue) { int requested = Math.Min (size.Height, size.Width); // previously best set to 1st image, as this might not be smallest changed loop to check all IconDirEntry? best = null; for (ushort i=0; i < count; i++) { IconDirEntry ide = iconDir.idEntries [i]; if (((ide.height < requested) || (ide.width < requested)) && !ide.ignore) { if (best == null) { best = ide; id = i; } else if ((ide.height > best.Value.height) || (ide.width > best.Value.width)) { best = ide; id = i; } } } } // last one, if nothing better can be found if (id == UInt16.MaxValue) { int i = count; while (id == UInt16.MaxValue && i > 0) { i--; if (!iconDir.idEntries [i].ignore) id = (ushort) i; } } if (id == UInt16.MaxValue) throw new ArgumentException ("Icon", "No valid icon image found"); iconSize.Height = iconDir.idEntries [id].height; iconSize.Width = iconDir.idEntries [id].width; } else { iconSize.Height = size.Height; iconSize.Width = size.Width; } if (original.bitmap != null) bitmap = (Bitmap) original.bitmap.Clone (); } public Icon (Stream stream) : this (stream, 32, 32) { } public Icon (Stream stream, int width, int height) { InitFromStreamWithSize (stream, width, height); } public Icon (string fileName) { using (FileStream fs = File.OpenRead (fileName)) { InitFromStreamWithSize (fs, 32, 32); } } public Icon (Type type, string resource) { if (resource == null) throw new ArgumentException ("resource"); using (Stream s = type.Assembly.GetManifestResourceStream (type, resource)) { if (s == null) { string msg = Locale.GetText ("Resource '{0}' was not found.", resource); throw new FileNotFoundException (msg); } InitFromStreamWithSize (s, 32, 32); // 32x32 is default } } private Icon (SerializationInfo info, StreamingContext context) { MemoryStream dataStream = null; int width=0; int height=0; foreach (SerializationEntry serEnum in info) { if (String.Compare(serEnum.Name, "IconData", true) == 0) { dataStream = new MemoryStream ((byte []) serEnum.Value); } if (String.Compare(serEnum.Name, "IconSize", true) == 0) { Size iconSize = (Size) serEnum.Value; width = iconSize.Width; height = iconSize.Height; } } if (dataStream != null) { dataStream.Seek (0, SeekOrigin.Begin); InitFromStreamWithSize (dataStream, width, height); } } internal Icon (string resourceName, bool undisposable) { using (Stream s = typeof (Icon).Assembly.GetManifestResourceStream (resourceName)) { if (s == null) { string msg = Locale.GetText ("Resource '{0}' was not found.", resourceName); throw new FileNotFoundException (msg); } InitFromStreamWithSize (s, 32, 32); // 32x32 is default } this.undisposable = true; } void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { MemoryStream ms = new MemoryStream (); Save (ms); si.AddValue ("IconSize", this.Size, typeof (Size)); si.AddValue ("IconData", ms.ToArray ()); } #if NET_2_0 public Icon (Stream stream, Size size) : this (stream, size.Width, size.Height) { } public Icon (string fileName, int width, int height) { using (FileStream fs = File.OpenRead (fileName)) { InitFromStreamWithSize (fs, width, height); } } public Icon (string fileName, Size size) { using (FileStream fs = File.OpenRead (fileName)) { InitFromStreamWithSize (fs, size.Width, size.Height); } } [MonoLimitation ("The same icon, SystemIcons.WinLogo, is returned for all file types.")] public static Icon ExtractAssociatedIcon (string filePath) { if (String.IsNullOrEmpty (filePath)) throw new ArgumentException (Locale.GetText ("Null or empty path."), "filePath"); if (!File.Exists (filePath)) throw new FileNotFoundException (Locale.GetText ("Couldn't find specified file."), filePath); return SystemIcons.WinLogo; } #endif public void Dispose () { // SystemIcons requires this if (undisposable) return; if (!disposed) { #if !MONOTOUCH if (GDIPlus.RunningOnWindows () && (handle != IntPtr.Zero)) { GDIPlus.DestroyIcon (handle); handle = IntPtr.Zero; } #endif if (bitmap != null) { bitmap.Dispose (); bitmap = null; } GC.SuppressFinalize (this); } disposed = true; } public object Clone () { return new Icon (this, Size); } #if !MONOTOUCH [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)] public static Icon FromHandle (IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException ("handle"); return new Icon (handle); } #endif private void SaveIconImage (BinaryWriter writer, IconImage ii) { BitmapInfoHeader bih = ii.iconHeader; writer.Write (bih.biSize); writer.Write (bih.biWidth); writer.Write (bih.biHeight); writer.Write (bih.biPlanes); writer.Write (bih.biBitCount); writer.Write (bih.biCompression); writer.Write (bih.biSizeImage); writer.Write (bih.biXPelsPerMeter); writer.Write (bih.biYPelsPerMeter); writer.Write (bih.biClrUsed); writer.Write (bih.biClrImportant); //now write color table int colCount = ii.iconColors.Length; for (int j=0; j < colCount; j++) writer.Write (ii.iconColors [j]); //now write XOR Mask writer.Write (ii.iconXOR); //now write AND Mask writer.Write (ii.iconAND); } private void SaveIconDump (BinaryWriter writer, IconDump id) { writer.Write (id.data); } private void SaveIconDirEntry (BinaryWriter writer, IconDirEntry ide, uint offset) { writer.Write (ide.width); writer.Write (ide.height); writer.Write (ide.colorCount); writer.Write (ide.reserved); writer.Write (ide.planes); writer.Write (ide.bitCount); writer.Write (ide.bytesInRes); writer.Write ((offset == UInt32.MaxValue) ? ide.imageOffset : offset); } private void SaveAll (BinaryWriter writer) { writer.Write (iconDir.idReserved); writer.Write (iconDir.idType); ushort count = iconDir.idCount; writer.Write (count); for (int i=0; i < (int)count; i++) { SaveIconDirEntry (writer, iconDir.idEntries [i], UInt32.MaxValue); } for (int i=0; i < (int)count; i++) { //FIXME: HACK: 1 (out of the 8) vista type icons had additional bytes (value:0) //between images. This fixes the issue, but perhaps shouldnt include in production? while (writer.BaseStream.Length < iconDir.idEntries[i].imageOffset) writer.Write ((byte) 0); if (imageData [i] is IconDump) SaveIconDump (writer, (IconDump) imageData [i]); else SaveIconImage (writer, (IconImage) imageData [i]); } } // TODO: check image not ignored (presently this method doesnt seem to be called unless width/height // refer to image) private void SaveBestSingleIcon (BinaryWriter writer, int width, int height) { writer.Write (iconDir.idReserved); writer.Write (iconDir.idType); writer.Write ((ushort)1); // find best entry and save it int best = 0; int bitCount = 0; for (int i=0; i < iconDir.idCount; i++) { IconDirEntry ide = iconDir.idEntries [i]; if ((width == ide.width) && (height == ide.height)) { if (ide.bitCount >= bitCount) { bitCount = ide.bitCount; best = i; } } } SaveIconDirEntry (writer, iconDir.idEntries [best], 22); SaveIconImage (writer, (IconImage) imageData [best]); } private void SaveBitmapAsIcon (BinaryWriter writer) { writer.Write ((ushort)0); // idReserved must be 0 writer.Write ((ushort)1); // idType must be 1 writer.Write ((ushort)1); // only one icon // when transformed into a bitmap only a single image exists IconDirEntry ide = new IconDirEntry (); ide.width = (byte) bitmap.Width; ide.height = (byte) bitmap.Height; ide.colorCount = 0; // 32 bbp == 0, for palette size ide.reserved = 0; // always 0 ide.planes = 0; ide.bitCount = 32; ide.imageOffset = 22; // 22 is the first icon position (for single icon files) BitmapInfoHeader bih = new BitmapInfoHeader (); bih.biSize = (uint) Marshal.SizeOf (typeof (BitmapInfoHeader)); bih.biWidth = bitmap.Width; bih.biHeight = 2 * bitmap.Height; // include both XOR and AND images bih.biPlanes = 1; bih.biBitCount = 32; bih.biCompression = 0; bih.biSizeImage = 0; bih.biXPelsPerMeter = 0; bih.biYPelsPerMeter = 0; bih.biClrUsed = 0; bih.biClrImportant = 0; IconImage ii = new IconImage (); ii.iconHeader = bih; ii.iconColors = new uint [0]; // no palette int xor_size = (((bih.biBitCount * bitmap.Width + 31) & ~31) >> 3) * bitmap.Height; ii.iconXOR = new byte [xor_size]; int p = 0; for (int y = bitmap.Height - 1; y >=0; y--) { for (int x = 0; x < bitmap.Width; x++) { Color c = bitmap.GetPixel (x, y); ii.iconXOR [p++] = c.B; ii.iconXOR [p++] = c.G; ii.iconXOR [p++] = c.R; ii.iconXOR [p++] = c.A; } } int and_line_size = (((Width + 31) & ~31) >> 3); // must be a multiple of 4 bytes int and_size = and_line_size * bitmap.Height; ii.iconAND = new byte [and_size]; ide.bytesInRes = (uint) (bih.biSize + xor_size + and_size); SaveIconDirEntry (writer, ide, UInt32.MaxValue); SaveIconImage (writer, ii); } private void Save (Stream outputStream, int width, int height) { BinaryWriter writer = new BinaryWriter (outputStream); // if we have the icon information then save from this if (iconDir.idEntries != null) { if ((width == -1) && (height == -1)) SaveAll (writer); else SaveBestSingleIcon (writer, width, height); } else if (bitmap != null) { // if the icon was created from a bitmap then convert it SaveBitmapAsIcon (writer); } writer.Flush (); } public void Save (Stream outputStream) { if (outputStream == null) throw new NullReferenceException ("outputStream"); // save every icons available Save (outputStream, -1, -1); } #if !MONOTOUCH internal Bitmap BuildBitmapOnWin32 () { Bitmap bmp; if (imageData == null) return new Bitmap (32, 32); IconImage ii = (IconImage) imageData [id]; BitmapInfoHeader bih = ii.iconHeader; int biHeight = bih.biHeight / 2; int ncolors = (int)bih.biClrUsed; if ((ncolors == 0) && (bih.biBitCount < 24)) ncolors = (int)(1 << bih.biBitCount); switch (bih.biBitCount) { case 1: bmp = new Bitmap (bih.biWidth, biHeight, PixelFormat.Format1bppIndexed); break; case 4: bmp = new Bitmap (bih.biWidth, biHeight, PixelFormat.Format4bppIndexed); break; case 8: bmp = new Bitmap (bih.biWidth, biHeight, PixelFormat.Format8bppIndexed); break; case 24: bmp = new Bitmap (bih.biWidth, biHeight, PixelFormat.Format24bppRgb); break; case 32: bmp = new Bitmap (bih.biWidth, biHeight, PixelFormat.Format32bppArgb); break; default: string msg = Locale.GetText ("Unexpected number of bits: {0}", bih.biBitCount); throw new Exception (msg); } if (bih.biBitCount < 24) { ColorPalette pal = bmp.Palette; // Managed palette for (int i = 0; i < ii.iconColors.Length; i++) { pal.Entries[i] = Color.FromArgb ((int)ii.iconColors[i] | unchecked((int)0xff000000)); } bmp.Palette = pal; } int bytesPerLine = (int)((((bih.biWidth * bih.biBitCount) + 31) & ~31) >> 3); BitmapData bits = bmp.LockBits (new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); for (int y = 0; y < biHeight; y++) { Marshal.Copy (ii.iconXOR, bytesPerLine * y, (IntPtr)(bits.Scan0.ToInt64() + bits.Stride * (biHeight - 1 - y)), bytesPerLine); } bmp.UnlockBits (bits); bmp = new Bitmap (bmp); // This makes a 32bpp image out of an indexed one // Apply the mask to make properly transparent bytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3); for (int y = 0; y < biHeight; y++) { for (int x = 0; x < bih.biWidth / 8; x++) { for (int bit = 7; bit >= 0; bit--) { if (((ii.iconAND[y * bytesPerLine +x] >> bit) & 1) != 0) { bmp.SetPixel (x*8 + 7-bit, biHeight - y - 1, Color.Transparent); } } } } return bmp; } internal Bitmap GetInternalBitmap () { if (bitmap == null) { if (GDIPlus.RunningOnUnix ()) { // Mono's libgdiplus doesn't require to keep the stream alive when loading images using (MemoryStream ms = new MemoryStream ()) { // save the current icon Save (ms, Width, Height); ms.Position = 0; // libgdiplus can now decode icons bitmap = (Bitmap) Image.LoadFromStream (ms, false); } } else { // MS GDI+ ICO codec is more limited than the MS Icon class // so we can't, reliably, get bitmap using it. We need to do this the "slow" way bitmap = BuildBitmapOnWin32 (); } } return bitmap; } // note: all bitmaps are 32bits ARGB - no matter what the icon format (bitcount) was public Bitmap ToBitmap () { if (disposed) throw new ObjectDisposedException (Locale.GetText ("Icon instance was disposed.")); // note: we can't return the original image because // (a) we have no control over the bitmap instance we return (i.e. it could be disposed) // (b) the palette, flags won't match MS results. See MonoTests.System.Drawing.Imaging.IconCodecTest. // Image16 for the differences return new Bitmap (GetInternalBitmap ()); } #endif public override string ToString () { //is this correct, this is what returned by .Net return "<Icon>"; } #if !MONOTOUCH [Browsable (false)] public IntPtr Handle { get { // note: this handle doesn't survive the lifespan of the icon instance if (!disposed && (handle == IntPtr.Zero)) { if (GDIPlus.RunningOnUnix ()) { handle = GetInternalBitmap ().NativeObject; } else { // remember that this block executes only with MS GDI+ IconInfo ii = new IconInfo (); ii.IsIcon = true; ii.hbmColor = ToBitmap ().GetHbitmap (); ii.hbmMask = ii.hbmColor; handle = GDIPlus.CreateIconIndirect (ref ii); } } return handle; } } #endif [Browsable (false)] public int Height { get { return iconSize.Height; } } public Size Size { get { return iconSize; } } [Browsable (false)] public int Width { get { return iconSize.Width; } } ~Icon () { Dispose (); } private void InitFromStreamWithSize (Stream stream, int width, int height) { //read the icon header if (stream == null || stream.Length == 0) throw new System.ArgumentException ("The argument 'stream' must be a picture that can be used as a Icon", "stream"); BinaryReader reader = new BinaryReader (stream); //iconDir = new IconDir (); iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 throw new System.ArgumentException ("Invalid Argument", "stream"); iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 throw new System.ArgumentException ("Invalid Argument", "stream"); ushort dirEntryCount = reader.ReadUInt16(); imageData = new ImageData [dirEntryCount]; iconDir.idCount = dirEntryCount; iconDir.idEntries = new IconDirEntry [dirEntryCount]; bool sizeObtained = false; // now read in the IconDirEntry structures for (int i = 0; i < dirEntryCount; i++) { IconDirEntry ide; ide.width = reader.ReadByte (); ide.height = reader.ReadByte (); ide.colorCount = reader.ReadByte (); ide.reserved = reader.ReadByte (); ide.planes = reader.ReadUInt16 (); ide.bitCount = reader.ReadUInt16 (); ide.bytesInRes = reader.ReadUInt32 (); ide.imageOffset = reader.ReadUInt32 (); #if false Console.WriteLine ("Entry: {0}", i);
[ "Console.WriteLine (\"\\tide.width: {0}\", ide.width);" ]
2,756
lcc
csharp
null
7535856a01a07c6c689fb46424b279e43fe483d635ef3bbc
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package jdk.internal.org.objectweb.asm; /** * A label represents a position in the bytecode of a method. Labels are used * for jump, goto, and switch instructions, and for try catch blocks. A label * designates the <i>instruction</i> that is just after. Note however that * there can be other elements between a label and the instruction it * designates (such as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * Indicates if this label is only used for debug attributes. Such a label * is not the start of a basic block, the target of a jump instruction, or * an exception handler. It can be safely ignored in control flow graph * analysis algorithms (for optimization purposes). */ static final int DEBUG = 1; /** * Indicates if the position of this label is known. */ static final int RESOLVED = 2; /** * Indicates if this label has been updated, after instruction resizing. */ static final int RESIZED = 4; /** * Indicates if this basic block has been pushed in the basic block stack. * See {@link MethodWriter#visitMaxs visitMaxs}. */ static final int PUSHED = 8; /** * Indicates if this label is the target of a jump instruction, or the start * of an exception handler. */ static final int TARGET = 16; /** * Indicates if a stack map frame must be stored for this label. */ static final int STORE = 32; /** * Indicates if this label corresponds to a reachable basic block. */ static final int REACHABLE = 64; /** * Indicates if this basic block ends with a JSR instruction. */ static final int JSR = 128; /** * Indicates if this basic block ends with a RET instruction. */ static final int RET = 256; /** * Indicates if this basic block is the start of a subroutine. */ static final int SUBROUTINE = 512; /** * Indicates if this subroutine basic block has been visited by a * visitSubroutine(null, ...) call. */ static final int VISITED = 1024; /** * Indicates if this subroutine basic block has been visited by a * visitSubroutine(!null, ...) call. */ static final int VISITED2 = 2048; /** * Field used to associate user information to a label. Warning: this field * is used by the ASM tree package. In order to use it with the ASM tree * package you must override the {@link * jdk.internal.org.objectweb.asm.tree.MethodNode#getLabelNode} method. */ public Object info; /** * Flags that indicate the status of this label. * * @see #DEBUG * @see #RESOLVED * @see #RESIZED * @see #PUSHED * @see #TARGET * @see #STORE * @see #REACHABLE * @see #JSR * @see #RET */ int status; /** * The line number corresponding to this label, if known. */ int line; /** * The position of this label in the code, if known. */ int position; /** * Number of forward references to this label, times two. */ private int referenceCount; /** * Informations about forward references. Each forward reference is * described by two consecutive integers in this array: the first one is the * position of the first byte of the bytecode instruction that contains the * forward reference, while the second is the position of the first byte of * the forward reference itself. In fact the sign of the first integer * indicates if this reference uses 2 or 4 bytes, and its absolute value * gives the position of the bytecode instruction. This array is also used * as a bitset to store the subroutines to which a basic block belongs. This * information is needed in {@linked MethodWriter#visitMaxs}, after all * forward references have been resolved. Hence the same array can be used * for both purposes without problems. */ private int[] srcAndRefPositions; // ------------------------------------------------------------------------ /* * Fields for the control flow and data flow graph analysis algorithms (used * to compute the maximum stack size or the stack map frames). A control * flow graph contains one node per "basic block", and one edge per "jump" * from one basic block to another. Each node (i.e., each basic block) is * represented by the Label object that corresponds to the first instruction * of this basic block. Each node also stores the list of its successors in * the graph, as a linked list of Edge objects. * * The control flow analysis algorithms used to compute the maximum stack * size or the stack map frames are similar and use two steps. The first * step, during the visit of each instruction, builds information about the * state of the local variables and the operand stack at the end of each * basic block, called the "output frame", <i>relatively</i> to the frame * state at the beginning of the basic block, which is called the "input * frame", and which is <i>unknown</i> during this step. The second step, * in {@link MethodWriter#visitMaxs}, is a fix point algorithm that * computes information about the input frame of each basic block, from the * input state of the first basic block (known from the method signature), * and by the using the previously computed relative output frames. * * The algorithm used to compute the maximum stack size only computes the * relative output and absolute input stack heights, while the algorithm * used to compute stack map frames computes relative output frames and * absolute input frames. */ /** * Start of the output stack relatively to the input stack. The exact * semantics of this field depends on the algorithm that is used. * * When only the maximum stack size is computed, this field is the number of * elements in the input stack. * * When the stack map frames are completely computed, this field is the * offset of the first output stack element relatively to the top of the * input stack. This offset is always negative or null. A null offset means * that the output stack must be appended to the input stack. A -n offset * means that the first n output stack elements must replace the top n input * stack elements, and that the other elements must be appended to the input * stack. */ int inputStackTop; /** * Maximum height reached by the output stack, relatively to the top of the * input stack. This maximum is always positive or null. */ int outputStackMax; /** * Information about the input and output stack map frames of this basic * block. This field is only used when {@link ClassWriter#COMPUTE_FRAMES} * option is used. */ Frame frame; /** * The successor of this label, in the order they are visited. This linked * list does not include labels used for debug info only. If * {@link ClassWriter#COMPUTE_FRAMES} option is used then, in addition, it * does not contain successive labels that denote the same bytecode position * (in this case only the first label appears in this list). */ Label successor; /** * The successors of this node in the control flow graph. These successors * are stored in a linked list of {@link Edge Edge} objects, linked to each * other by their {@link Edge#next} field. */ Edge successors; /** * The next basic block in the basic block stack. This stack is used in the * main loop of the fix point algorithm used in the second step of the * control flow analysis algorithms. It is also used in * {@link #visitSubroutine} to avoid using a recursive method. * * @see MethodWriter#visitMaxs */ Label next; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new label. */ public Label() { } // ------------------------------------------------------------------------ // Methods to compute offsets and to manage forward references // ------------------------------------------------------------------------ /** * Returns the offset corresponding to this label. This offset is computed * from the start of the method's bytecode. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @return the offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((status & RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return position; } /** * Puts a reference to this label in the bytecode of a method. If the * position of the label is known, the offset is computed and written * directly. Otherwise, a null offset is written and a new forward reference * is declared for this label. * * @param owner the code writer that calls this method. * @param out the bytecode of the method. * @param source the position of first byte of the bytecode instruction that * contains this label. * @param wideOffset <tt>true</tt> if the reference must be stored in 4 * bytes, or <tt>false</tt> if it must be stored with 2 bytes. * @throws IllegalArgumentException if this label has not been created by * the given code writer. */ void put( final MethodWriter owner, final ByteVector out, final int source, final boolean wideOffset) { if ((status & RESOLVED) == 0) { if (wideOffset) { addReference(-1 - source, out.length); out.putInt(-1); } else { addReference(source, out.length); out.putShort(-1); } } else { if (wideOffset) { out.putInt(position - source); } else { out.putShort(position - source); } } } /** * Adds a forward reference to this label. This method must be called only * for a true forward reference, i.e. only if this label is not resolved * yet. For backward references, the offset of the reference can be, and * must be, computed and stored directly. * * @param sourcePosition the position of the referencing instruction. This * position will be used to compute the offset of this forward * reference. * @param referencePosition the position where the offset for this forward * reference must be stored. */ private void addReference( final int sourcePosition, final int referencePosition) { if (srcAndRefPositions == null) { srcAndRefPositions = new int[6]; } if (referenceCount >= srcAndRefPositions.length) { int[] a = new int[srcAndRefPositions.length + 6]; System.arraycopy(srcAndRefPositions, 0, a, 0, srcAndRefPositions.length); srcAndRefPositions = a; } srcAndRefPositions[referenceCount++] = sourcePosition; srcAndRefPositions[referenceCount++] = referencePosition; } /** * Resolves all forward references to this label. This method must be called * when this label is added to the bytecode of the method, i.e. when its * position becomes known. This method fills in the blanks that where left * in the bytecode by each forward reference previously added to this label. * * @param owner the code writer that calls this method. * @param position the position of this label in the bytecode. * @param data the bytecode of the method. * @return <tt>true</tt> if a blank that was left for this label was to * small to store the offset. In such a case the corresponding jump * instruction is replaced with a pseudo instruction (using unused * opcodes) using an unsigned two bytes offset. These pseudo * instructions will need to be replaced with true instructions with * wider offsets (4 bytes instead of 2). This is done in * {@link MethodWriter#resizeInstructions}. * @throws IllegalArgumentException if this label has already been resolved, * or if it has not been created by the given code writer. */ boolean resolve( final MethodWriter owner, final int position, final byte[] data) { boolean needUpdate = false; this.status |= RESOLVED; this.position = position; int i = 0; while (i < referenceCount) { int source = srcAndRefPositions[i++]; int reference = srcAndRefPositions[i++]; int offset; if (source >= 0) { offset = position - source; if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) { /* * changes the opcode of the jump instruction, in order to * be able to find it later (see resizeInstructions in * MethodWriter). These temporary opcodes are similar to * jump instruction opcodes, except that the 2 bytes offset * is unsigned (and can therefore represent values from 0 to * 65535, which is sufficient since the size of a method is * limited to 65535 bytes). */ int opcode = data[reference - 1] & 0xFF; if (opcode <= Opcodes.JSR) { // changes IFEQ ... JSR to opcodes 202 to 217 data[reference - 1] = (byte) (opcode + 49); } else { // changes IFNULL and IFNONNULL to opcodes 218 and 219 data[reference - 1] = (byte) (opcode + 20); } needUpdate = true; } data[reference++] = (byte) (offset >>> 8); data[reference] = (byte) offset; } else { offset = position + source + 1; data[reference++] = (byte) (offset >>> 24); data[reference++] = (byte) (offset >>> 16); data[reference++] = (byte) (offset >>> 8); data[reference] = (byte) offset; } } return needUpdate; } /** * Returns the first label of the series to which this label belongs. For an * isolated label or for the first label in a series of successive labels, * this method returns the label itself. For other labels it returns the * first label of the series. * * @return the first label of the series to which this label belongs. */ Label getFirst() { return !ClassReader.FRAMES || frame == null ? this : frame.owner; } // ------------------------------------------------------------------------ // Methods related to subroutines // ------------------------------------------------------------------------ /** * Returns true is this basic block belongs to the given subroutine. * * @param id a subroutine id. * @return true is this basic block belongs to the given subroutine. */ boolean inSubroutine(final long id) { if ((status & Label.VISITED) != 0) { return (srcAndRefPositions[(int) (id >>> 32)] & (int) id) != 0; } return false; } /** * Returns true if this basic block and the given one belong to a common * subroutine. * * @param block another basic block. * @return true if this basic block and the given one belong to a common * subroutine. */ boolean inSameSubroutine(final Label block) { if ((status & VISITED) == 0 || (block.status & VISITED) == 0) { return false; } for (int i = 0; i < srcAndRefPositions.length; ++i) { if ((srcAndRefPositions[i] & block.srcAndRefPositions[i]) != 0) { return true; } } return false; } /** * Marks this basic block as belonging to the given subroutine. * * @param id a subroutine id. * @param nbSubroutines the total number of subroutines in the method. */ void addToSubroutine(final long id, final int nbSubroutines) { if ((status & VISITED) == 0) { status |= VISITED; srcAndRefPositions = new int[(nbSubroutines - 1) / 32 + 1]; } srcAndRefPositions[(int) (id >>> 32)] |= (int) id; } /** * Finds the basic blocks that belong to a given subroutine, and marks these * blocks as belonging to this subroutine. This method follows the control * flow graph to find all the blocks that are reachable from the current * block WITHOUT following any JSR target. * * @param JSR a JSR block that jumps to this subroutine. If this JSR is not * null it is added to the successor of the RET blocks found in the * subroutine. * @param id the id of this subroutine. * @param nbSubroutines the total number of subroutines in the method. */ void visitSubroutine(final Label JSR, final long id, final int nbSubroutines) { // user managed stack of labels, to avoid using a recursive method // (recursivity can lead to stack overflow with very large methods) Label stack = this; while (stack != null) { // removes a label l from the stack Label l = stack; stack = l.next; l.next = null; if (JSR != null) {
[ " if ((l.status & VISITED2) != 0) {" ]
3,107
lcc
java
null
ccd61a72c442c4312744465333f1834fbb9aa1fdbd7f909c
#if CSHotFix using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using CSHotFix.CLR.TypeSystem; using CSHotFix.CLR.Method; using CSHotFix.Runtime.Enviorment; using CSHotFix.Runtime.Intepreter; using CSHotFix.Runtime.Stack; using CSHotFix.Reflection; using CSHotFix.CLR.Utils; using System.Linq; namespace CSHotFix.Runtime.Generated { unsafe class UnityEngine_Ray_Binding { public static void Register(CSHotFix.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityEngine.Ray); args = new Type[]{}; method = type.GetMethod("get_origin", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_origin_0); args = new Type[]{typeof(UnityEngine.Vector3)}; method = type.GetMethod("set_origin", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_origin_1); args = new Type[]{}; method = type.GetMethod("get_direction", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_direction_2); args = new Type[]{typeof(UnityEngine.Vector3)}; method = type.GetMethod("set_direction", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_direction_3); args = new Type[]{typeof(System.Single)}; method = type.GetMethod("GetPoint", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetPoint_4); args = new Type[]{}; method = type.GetMethod("ToString", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToString_5); args = new Type[]{typeof(System.String)}; method = type.GetMethod("ToString", flag, null, args, null); app.RegisterCLRMethodRedirection(method, ToString_6); app.RegisterCLRMemberwiseClone(type, PerformMemberwiseClone); app.RegisterCLRCreateDefaultInstance(type, () => new UnityEngine.Ray()); app.RegisterCLRCreateArrayInstance(type, s => new UnityEngine.Ray[s]); args = new Type[]{typeof(UnityEngine.Vector3), typeof(UnityEngine.Vector3)}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static void WriteBackInstance(CSHotFix.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref UnityEngine.Ray instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityEngine.Ray[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* get_origin_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.Ray instance_of_this_method = (UnityEngine.Ray)typeof(UnityEngine.Ray).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.origin; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* set_origin_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.Vector3 @value = (UnityEngine.Vector3)typeof(UnityEngine.Vector3).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.Ray instance_of_this_method = (UnityEngine.Ray)typeof(UnityEngine.Ray).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.origin = value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* get_direction_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.Ray instance_of_this_method = (UnityEngine.Ray)typeof(UnityEngine.Ray).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.direction; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* set_direction_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.Vector3 @value = (UnityEngine.Vector3)typeof(UnityEngine.Vector3).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.Ray instance_of_this_method = (UnityEngine.Ray)typeof(UnityEngine.Ray).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.direction = value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* GetPoint_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Single @distance = *(float*)&ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.Ray instance_of_this_method = (UnityEngine.Ray)typeof(UnityEngine.Ray).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.GetPoint(@distance); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* ToString_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1);
[ " ptr_of_this_method = ILIntepreter.Minus(__esp, 1);" ]
599
lcc
csharp
null
f0c18c81b769fb90470c8df8bae97ef061380d5b8dcb9b40
package de.tudresden.slr.ui.chart.settings.pages; import org.eclipse.birt.chart.model.attribute.LineStyle; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Text; import de.tudresden.slr.ui.chart.settings.PieChartConfiguration; import de.tudresden.slr.ui.chart.settings.parts.BlockSettings; import de.tudresden.slr.ui.chart.settings.parts.GeneralSettings; import de.tudresden.slr.ui.chart.settings.parts.SeriesSettings; public class GeneralPagePie extends Composite implements SelectionListener, MouseListener, Pages{ private Label labelShowColor, labelShowColor2, lblExplosion; private Text text; private Combo comboTitleSize, comboBlockOutline; private Button btnUnderline, btnBolt, btnItalic, btnShowLables; private Scale explosion; private GeneralSettings settingsGeneral = PieChartConfiguration.get().getGeneralSettings(); private BlockSettings settingsBlock = PieChartConfiguration.get().getBlockSettings(); private SeriesSettings settingsSeries = PieChartConfiguration.get().getSeriesSettings(); private Label lblLabelPosition; private Combo comboLabelPosition; public GeneralPagePie(Composite parent, int style) { super(parent, SWT.NONE); FillLayout fillLayout = new FillLayout(SWT.VERTICAL); fillLayout.marginWidth = 5; fillLayout.marginHeight = 5; setLayout(fillLayout); Group grpTitleSettings = new Group(this, SWT.NONE); grpTitleSettings.setText("Title Settings"); grpTitleSettings.setLayout(new GridLayout(2, false)); Label lblSetTitle = new Label(grpTitleSettings, SWT.NONE); lblSetTitle.setText("Chart Title"); text = new Text(grpTitleSettings, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblFontSize = new Label(grpTitleSettings, SWT.NONE); lblFontSize.setText("Title Font Size"); comboTitleSize = new Combo(grpTitleSettings, SWT.READ_ONLY); comboTitleSize.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); comboTitleSize.add("12"); comboTitleSize.add("14"); comboTitleSize.add("16"); comboTitleSize.add("18"); comboTitleSize.add("20"); comboTitleSize.add("22"); comboTitleSize.add("24"); comboTitleSize.add("26"); comboTitleSize.add("28"); comboTitleSize.add("36"); comboTitleSize.add("48"); comboTitleSize.add("72"); comboTitleSize.select(0); Label lblColor = new Label(grpTitleSettings, SWT.NONE); GridData gd_lblColor = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblColor.widthHint = 150; lblColor.setLayoutData(gd_lblColor); lblColor.setText("Title Color"); labelShowColor = new Label(grpTitleSettings, SWT.BORDER); GridData gd_labelShowColor = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_labelShowColor.widthHint = 100; labelShowColor.setLayoutData(gd_labelShowColor); labelShowColor.setBackground(new Color(parent.getShell().getDisplay(), new RGB(255,255,255))); Label lblFont = new Label(grpTitleSettings, SWT.NONE); lblFont.setText("Font"); Composite composite = new Composite(grpTitleSettings, SWT.NONE); composite.setLayout(new GridLayout(3, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); btnUnderline = new Button(composite, SWT.CHECK); btnUnderline.setText("Underline"); btnItalic = new Button(composite, SWT.CHECK); btnItalic.setText("Italic"); btnBolt = new Button(composite, SWT.CHECK); btnBolt.setText("Bolt"); labelShowColor.addMouseListener(this); Group grpBlockSettings = new Group(this, SWT.NONE); grpBlockSettings.setText("Block Settings"); grpBlockSettings.setLayout(new GridLayout(2, false)); Label lblNewLabel = new Label(grpBlockSettings, SWT.NONE); GridData gd_lblNewLabel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel.widthHint = 150; lblNewLabel.setLayoutData(gd_lblNewLabel); lblNewLabel.setText("Block Outline Style"); comboBlockOutline = new Combo(grpBlockSettings, SWT.READ_ONLY); comboBlockOutline.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); comboBlockOutline.add("None"); comboBlockOutline.add("Dotted"); comboBlockOutline.add("Dash-Dotted"); comboBlockOutline.add("Dashed"); comboBlockOutline.add("Solid"); comboBlockOutline.select(0); Label lblColor_1 = new Label(grpBlockSettings, SWT.NONE); lblColor_1.setText("Block Color"); labelShowColor2 = new Label(grpBlockSettings, SWT.BORDER); GridData gd_labelShowColor2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_labelShowColor2.widthHint = 100; labelShowColor2.setLayoutData(gd_labelShowColor2); labelShowColor2.setText(" "); labelShowColor2.setBackground(PageSupport.getColor(parent, 0)); Label lblLables = new Label(grpBlockSettings, SWT.NONE); lblLables.setText("Pie Labels"); btnShowLables = new Button(grpBlockSettings, SWT.CHECK); btnShowLables.setText("Show Labels"); lblExplosion = new Label(grpBlockSettings, SWT.NONE); GridData gd_lblExplosion = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_lblExplosion.widthHint = 106; lblExplosion.setLayoutData(gd_lblExplosion); lblExplosion.setText("Pie Explosion"); explosion = new Scale(grpBlockSettings, SWT.NONE); explosion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); explosion.setPageIncrement(1); explosion.setMaximum(20); lblLabelPosition = new Label(grpBlockSettings, SWT.NONE); lblLabelPosition.setText("Label Position"); comboLabelPosition = new Combo(grpBlockSettings, SWT.READ_ONLY); comboLabelPosition.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); comboLabelPosition.addSelectionListener(this); comboLabelPosition.add("Inside"); comboLabelPosition.add("Outside"); explosion.addSelectionListener(this); labelShowColor2.addMouseListener(this); loadSettings(); } @Override public void mouseUp(MouseEvent e) { if(e.getSource() == labelShowColor) { RGB rgb = PageSupport.openAndGetColor(this.getParent(), labelShowColor); } if(e.getSource() == labelShowColor2) { RGB rgb = PageSupport.openAndGetColor(this.getParent(), labelShowColor2); } } @Override public void saveSettings() { settingsGeneral.setChartTitle(getTitle()); settingsGeneral.setChartTitleColor(getTitleColor()); settingsGeneral.setChartTitleSize(getTitleSize()); settingsGeneral.setChartTitleBold(getBolt()); settingsGeneral.setChartTitleItalic(getItalic()); settingsGeneral.setChartTitleUnderline(getUnterline()); settingsSeries.setSeriesExplosion(getExplosion()); settingsSeries.setSeriesLabelPosition(getPosition()); settingsGeneral.setChartShowLabels(isChartShowLabels());// settingsBlock.setBlockBackgroundRGB(getBlockColor()); if(getBlockOutline() == null) settingsBlock.setBlockShowOutline(false); else { settingsBlock.setBlockShowOutline(true); settingsBlock.setBlockOutlineStyle(getBlockOutline()); } } @Override public void loadSettings() { setTitle(settingsGeneral.getChartTitle()); setTitleColor(settingsGeneral.getChartTitleColor()); setTitleSize(settingsGeneral.getChartTitleSize()); setBolt(settingsGeneral.isChartTitleBold()); setItalic(settingsGeneral.isChartTitleItalic()); setUnterline(settingsGeneral.isChartTitleUnderline()); setBlockColor(settingsBlock.getBlockBackgroundRGB()); setExplosion(settingsSeries.getSeriesExplosion()); setPosition(settingsSeries.getSeriesLabelPosition()); setChartShowLabels(settingsGeneral.isChartShowLabels());// if(settingsBlock.isBlockShowOutline()) setBlockOutline(settingsBlock.getBlockOutlineStyle()); else setBlockOutline(null); } private boolean getBolt() {return btnBolt.getSelection();} private void setBolt(boolean value) {btnBolt.setSelection(value);} private boolean getItalic() {return btnItalic.getSelection();} private void setItalic(boolean value) {btnItalic.setSelection(value);} private boolean getUnterline() {return btnUnderline.getSelection();} private void setUnterline(boolean value) {btnUnderline.setSelection(value);} private String getTitle() {return text.getText();} public void setTitle(String title) {text.setText(title);} private int getTitleSize() {return Integer.valueOf(comboTitleSize.getItem(comboTitleSize.getSelectionIndex()));} private void setTitleSize(int size) {comboTitleSize.select(PageSupport.setFontSize(size));} private LineStyle getBlockOutline() {return PageSupport.getLineStyle(comboBlockOutline.getSelectionIndex());} private void setBlockOutline(LineStyle lineStyle) {comboBlockOutline.select((PageSupport.setLineStyle(lineStyle)));} private RGB getTitleColor() {return labelShowColor.getBackground().getRGB();} private void setTitleColor(RGB rgb) {labelShowColor.setBackground(new Color(this.getDisplay(), rgb));} private RGB getBlockColor() {return labelShowColor2.getBackground().getRGB();} private void setBlockColor(RGB rgb) {labelShowColor2.setBackground(new Color(this.getDisplay(), rgb));} private boolean isChartShowLabels() {return btnShowLables.getSelection();} private void setChartShowLabels(boolean value) {btnShowLables.setSelection(value);} private int getExplosion() {return explosion.getSelection();} private void setExplosion(int explosion) {this.explosion.setSelection(explosion); lblExplosion.setText("Pie Explosion: " + String.valueOf(this.explosion.getSelection()));} private void setPosition(Position position) {
[ "\t\t\tif(position == Position.INSIDE_LITERAL) {" ]
620
lcc
java
null
6cd281e781038f9d58715d430ef4da8a82ec9cd5572bd6bb
import Util import time import unittest import tAnimator import selectBrowser from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By # Tests of Animator Settings functionality class tAnimatorSettings(tAnimator.tAnimator): def setUp(self): browser = selectBrowser._getBrowser() Util.setUp( self, browser ) # Test that we can add the add/remove Animator buttons to the toolbar if they are # not already there. Then test that we can check/uncheck them and have the corresponding # animator added/removed def test_animatorAddRemove(self): driver = self.driver browser = selectBrowser._getBrowser() timeout = selectBrowser._getSleep() # Wait for the image window to be present (ensures browser is fully loaded) imageWindow = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.widgets.Window.DisplayWindowImage']"))) # Click on Animator window so its actions will be enabled animWindow = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.widgets.Window.DisplayWindowAnimation']"))) ActionChains(driver).click( animWindow ).perform() # Make sure the Animation window is enabled by clicking an element within the window channelText = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelIndexText"))) ActionChains(driver).click( channelText ).perform() # Right click the toolbar to bring up the context menu toolBar = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.widgets.Menu.ToolBar']"))) ActionChains(driver).context_click(toolBar).perform() # Click the customize item on the menu customizeButton = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Customize...']/.."))) ActionChains(driver).click( customizeButton ).perform() # First make sure animator is checked animateButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Animate']/preceding-sibling::div/div"))) styleAtt = animateButton.get_attribute( "style"); if not "checked.png" in styleAtt: print "Clicking animate to make buttons visible on tool bar" animateParent = animateButton.find_element_by_xpath( '..' ) driver.execute_script( "arguments[0].scrollIntoView(true);", animateParent) ActionChains(driver).click( animateParent ).perform() # Verify both the channel and image checkboxes are on the toolbar channelCheck = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Channel']/following-sibling::div[@class='qx-checkbox']"))) animateCheck = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[text()='Image']/following-sibling::div[@class='qx-checkbox']"))) # Uncheck both buttons channelChecked = self._isChecked( channelCheck ) print 'Channel checked', channelChecked if channelChecked: self._click( driver, channelCheck ) animateChecked = self._isChecked( animateCheck ) print 'Animate checked', animateChecked if animateChecked: self._click( driver, animateCheck ) time.sleep( timeout ) # Verify that the animation window has no animators. self._verifyAnimationCount( animWindow, 0) # Check the image animate button and verify that the image animator shows up self._click( driver, animateCheck ) imageAnimator = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.boundWidgets.Animator']/div/div[text()='Image']"))) time.sleep( timeout ) self._verifyAnimationCount( animWindow, 1) # Check the channel animator button and verify there are now two animators, one channel, one image. self._click( driver, channelCheck ) channelAnimator = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.boundWidgets.Animator']/div/div[text()='Channel']"))) time.sleep( timeout ) self._verifyAnimationCount( animWindow, 2 ) # Chrome gives an error trying to close the page; therefore, refresh the page before # closing the browser. This is required because otherwise memory is not freed. if browser == 2: # Refresh browser driver.refresh() time.sleep(2) # Test that the Channel Animator will update when the window image is switched def test_channelAnimatorChangeImage(self): driver = self.driver timeout = selectBrowser._getSleep() # Load two images # The images have different numbers of channels Util.load_image( self, driver, "Default") Util.load_image( self, driver, "m31_cropped.fits") # Show the Image Animator channelText = driver.find_element_by_id("ChannelIndexText") ActionChains(driver).click( channelText ).perform() animateToolBar = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='qx.ui.toolbar.MenuButton']/div[text()='Animate']"))) ActionChains(driver).click( animateToolBar ).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys( Keys.ENTER).perform() time.sleep( timeout ) # Go to the first image self._getFirstValue( driver, "Image") # Go to the last channel of the image self._getLastValue( driver, "Channel") # Get the last channel value of the first image firstImageChannelValue = self._getCurrentValue( driver, "Channel" ) # Go to the next image self._getNextValue( driver, "Image" ) # Go to the last channel of the image self._getLastValue( driver, "Channel") # Get the channel upper spin box value of the second image # Check that the upper spin box value updated # Get the channel upper spin box value of the first image secondImageChannelValue = self._getCurrentValue( driver, "Channel" ) self.assertNotEqual( int(secondImageChannelValue), int(firstImageChannelValue), "Channel value did not update after changing image in window") # Test that the Animator jump setting animates the first and last channel values # Under default settings, it takes roughly 2 seconds for the channel to change by 1 def test_animatorJump(self): driver = self.driver timeout = selectBrowser._getSleep() # Open a test image so we have something to animate Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "Default") # Record last channel value of the test image self._getLastValue( driver, "Channel" ) lastChannelValue = self._getCurrentValue( driver, "Channel" ) # Record the first channel value of the test image self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) print "Testing Channel Animator Jump Setting..." print "First channel value:", firstChannelValue, "Last channel value:", lastChannelValue # Open settings self._openSettings( driver ) # In settings, click the Jump radio button. Scroll into view if button is not visible jumpButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelJumpRadioButton"))) driver.execute_script( "arguments[0].scrollIntoView(true);", jumpButton) ActionChains(driver).click( jumpButton ).perform() # Click the channel tape deck increment button self._getNextValue( driver, "Channel" ) # Check that the channel is at the last channel value currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertEqual( int(lastChannelValue), int(currChannelValue), "Channel Animator did not jump to last channel value") # Click the channel tape deck increment button # Check that the current channel is at the first channel value self._getNextValue( driver, "Channel" ) currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertEqual( int(firstChannelValue), int(currChannelValue), "Channel Animator did not jump to first channel value") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) # Record the last image value self._getLastValue( driver, "Image" ) lastImageValue = self._getCurrentValue( driver, "Image" ) # Record the first image value self._getFirstValue( driver, "Image" ) firstImageValue = self._getCurrentValue( driver, "Image" ) print "Testing Image Animator Jump Setting..." print "First image value:", firstImageValue, "Last image value:", lastImageValue # In settings, click the Jump radio button. Scroll into view if button is not visible jumpButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ImageJumpRadioButton"))) driver.execute_script( "arguments[0].scrollIntoView(true);", jumpButton) ActionChains(driver).click( jumpButton ).perform() # Click the image increment button self._getNextValue( driver, "Image" ) # Check that the Animator is at the last image value currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image", currImageValue self.assertEqual( int(lastImageValue), int(currImageValue), "Image Animator did not jump to last image" ) # Click the image increment button again self._getNextValue( driver, "Image" ) currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image", currImageValue self.assertEqual( int(firstImageValue), int(currImageValue), "Image Animator did not jump to first image") # Test that the Animator wrap setting returns to the first channel value # after animating the last channel. Under default settings, it takes roughly 2 # seconds for the channel to change by 1 def test_channelAnimatorWrap(self): driver = self.driver timeout = selectBrowser._getSleep() # Open a test image so we have something to animate Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "Default") # Open settings self._openSettings( driver ) # Go to first channel value and record the first channel value of the test image self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) # Go to last channel value and record the last channel value of the test image self._getLastValue( driver, "Channel" ) lastChannelValue = self._getCurrentValue( driver, "Channel" ) print "Testing Channel Animator Wrap Setting..." print "First channel value:", firstChannelValue, "Last channel value:", lastChannelValue # In settings, click the Wrap radio button. Scroll into view if button is not visible wrapButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelWrapRadioButton"))) driver.execute_script( "arguments[0].scrollIntoView(true);", wrapButton) ActionChains(driver).click( wrapButton ).perform() # Go to the next vaid value self._getNextValue( driver, "Channel" ) # Check that the channel is at the first channel value currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertEqual( int(firstChannelValue), int(currChannelValue), "Channel Animator did not wrap to first channel value") # Click the channel tape deck increment button # Check that the current channel is at the first channel value self._getNextValue( driver, "Channel" ) currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertGreater( int(currChannelValue), int(firstChannelValue), "Channel did not increase after animating first channel value") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) # Record the first image value self._getFirstValue( driver, "Image" ) firstImageValue = self._getCurrentValue( driver, "Image" ) # Go to the last image and record the last image value self._getLastValue( driver, "Image" ) lastImageValue = self._getCurrentValue( driver, "Image" ) print "Testing Image Animator Wrap..." print "First image value:", firstImageValue, "Last image value:", lastImageValue # In settings, click the Wrap radio button. Scroll into view if button is not visible wrapButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ImageWrapRadioButton"))) driver.execute_script( "arguments[0].scrollIntoView(true);", wrapButton) ActionChains(driver).click( wrapButton ).perform() # Click the image increment button self._getNextValue( driver, "Image" ) # Check that the animator is at the first image value currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image", currImageValue self.assertEqual( int(firstImageValue), int(currImageValue), "Image Animator did not wrap to first image") # Click the image increment button again self._getNextValue( driver, "Image" ) currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image", currImageValue self.assertGreater( int(currImageValue), int(firstImageValue), "Image value did not increase after animating first image") # Test that the Animator reverse setting animates in the reverse direction after # reaching the last channel value. Under default settings, it takes roughly 4 seconds # for the channel to reverse direction from the last channel def test_channelAnimatorReverse(self): driver = self.driver timeout = selectBrowser._getSleep() # Open a test image so we have something to animate Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "aK.fits") Util.load_image( self, driver, "Default") # Open settings self._openSettings( driver ) # Go to last channel value and record the last channel value of the test image self._getLastValue( driver, "Channel" ) lastChannelValue = self._getCurrentValue( driver, "Channel" ) print "Testing Channel Animator Reverse Setting..." print "Last channel value:", lastChannelValue # In settings, click the Reverse radio button. Scroll into view if button is not visible reverseButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelReverseRadioButton"))) driver.execute_script( "arguments[0].scrollIntoView(true);", reverseButton) ActionChains(driver).click( reverseButton ).perform() time.sleep(2) # Click the forward animate button # Allow the image to animate for 4 seconds (takes 4 seconds to reverse direction) self._animateForward( driver, "Channel" ) time.sleep(4) # Check that the current channel value is less than the last channel value currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertGreater( int(lastChannelValue), int(currChannelValue), "Channel Animator did not reverse direction after animating last channel value") # Stop animation. Scroll into view if stop button cannot be seen stopButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelTapeDeckStopAnimation"))) driver.execute_script( "arguments[0].scrollIntoView(true);", stopButton) ActionChains(driver).click( stopButton ).perform() # Go to first channel value and record the first channel value of the test image self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) print "First channel value:", firstChannelValue # Click the forward animate button # Allow image to animate for 2 seconds self._animateForward( driver, "Channel") time.sleep(2) # Check that the channel value is at a higher value than the first channel value currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertGreater( int(currChannelValue), int(firstChannelValue), "Channel Animator did not increase channel after animating first channel value") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) # Go to the last image and record the last image value self._getLastValue( driver, "Image" ) lastImageValue = self._getCurrentValue( driver, "Image" ) print "Testing Image Animator Reverse Setting..." print "Last image value:", lastImageValue # In settings, click the Reverse radio button. Scroll into view if button is not visible reverseButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ImageTapeDeckReversePlay"))) driver.execute_script( "arguments[0].scrollIntoView(true);", reverseButton) ActionChains(driver).click( reverseButton ).perform() # Click the forward animate button # Allow the image to animate for 4 seconds (takes 4 seconds to reverse direction) self._animateForward( driver, "Image" ) time.sleep(4) # Check that the current image value is less than the last image value currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image", currImageValue self.assertGreater( int(lastImageValue), int(currImageValue), "Image Animator did not reverse direction after animating the last image") # Test that adjustment of Animator rate will speed up/slow down channel animation # Under default settings, it takes roughly 2 seconds for the channel to change by 1 def test_channelAnimatorChangeRate(self): driver = self.driver # Open a test image so we have something to animate Util.load_image( self, driver, "Default") # Open settings self._openSettings( driver ) # Go to first channel value and record the first channel value of the test image self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) print "Testing Channel Animator Rate Setting..." print "First channel value:", firstChannelValue print "Default Rate = 20, New Rate = 50" # Allow image to animate for 2 seconds self._animateForward( driver, "Channel" ) time.sleep(3) defaultRateValue = self._getCurrentValue( driver, "Channel" ) print "defaultRateValue", defaultRateValue # Stop animation. Scroll into view if the stop button cannot be seen self._stopAnimation( driver, "Channel") # Change the rate to 50 rateText = driver.find_element_by_xpath("//div[@id='ChannelRate']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", rateText) rateValue = Util._changeElementText(self, driver, rateText, 50) # Go to first channel value and animate for 2 seconds self._getFirstValue( driver, "Channel" ) self._animateForward( driver, "Channel" ) time.sleep(3) # The channel should be at a higher channel value than the default rate value newRateValue = self._getCurrentValue( driver, "Channel" ) print "newRateValue", newRateValue self.assertGreater( int(newRateValue), int(defaultRateValue), "Rate value did not increase speed of channel animation") # Test that the Channel Animator Rate does not exceed boundary values def test_animatorRateBoundary(self): driver = self.driver timeout = selectBrowser._getSleep() # Wait for the image window to be present (ensures browser is fully loaded) imageWindow = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.widgets.Window.DisplayWindowImage']"))) # Open settings self._openSettings( driver ) # Find and click on the rate text. Scroll into view if not visible rateText = driver.find_element_by_xpath( "//div[@id='ChannelRate']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", rateText) # Test that the animation rate does not exceed boundary values (1 to 100) # Test that the input of a negative value is not accepted rateValue = Util._changeElementText( self, driver, rateText, -32) self.assertGreaterEqual(int(rateValue), 0, "Rate value is negative") # Test that the input of a value over 100 is not accepted rateValue = Util._changeElementText( self, driver, rateText, 200) self.assertEqual(int(rateValue), 100, "Rate value is greater than 100") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) time.sleep(timeout) # Find and click on the rate text. Scroll into view if not visible rateText = driver.find_element_by_xpath( "//div[@id='ImageRate']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", rateText) # Test that the animation rate does not exceed boundary values (1 to 100) # Test that the input of a negative value is not accepted rateValue = Util._changeElementText( self, driver, rateText, -32) self.assertGreaterEqual(int(rateValue), 0, "Rate value is negative") # Test that the input of a value over 100 is not accepted rateValue = Util._changeElementText( self, driver, rateText, 200) self.assertEqual(int(rateValue), 100, "Rate value is greater than 100") # Test that the Channel Animator Step Increment does not exceed boundary values def test_animatorStepBoundary(self): driver = self.driver # Wait for the image window to be present (ensures browser is fully loaded) imageWindow = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//div[@qxclass='skel.widgets.Window.DisplayWindowImage']"))) # Open settings self._openSettings( driver ) # Find and click the step increment textbox stepIncrementText = driver.find_element_by_xpath( "//div[@id='ChannelStepIncrement']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", stepIncrementText) # Test that the animation rate does not exceed boundary values (1 to 100) # Test that the input of a negative value is not accepted stepValue = Util._changeElementText(self, driver, stepIncrementText, -50) self.assertGreaterEqual(int(stepValue), 0, "Step increment value is negative") # Test that the input of a value over 100 is not accepted stepValue = Util._changeElementText( self, driver, stepIncrementText, 200) self.assertEqual( int(stepValue), 100, "Step increment value is greater than 100") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) # Find and click the step increment textbox stepIncrementText = driver.find_element_by_xpath( "//div[@id='ImageStepIncrement']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", stepIncrementText) # Test that the animation rate does not exceed boundary values (1 to 100) # Test that the input of a negative value is not accepted stepValue = Util._changeElementText(self, driver, stepIncrementText, -50) self.assertGreaterEqual(int(stepValue), 0, "Step increment value is negative") # Test that the input of a value over 100 is not accepted stepValue = Util._changeElementText( self, driver, stepIncrementText, 200) self.assertEqual( int(stepValue), 100, "Step increment value is greater than 100") # Test that the Channel Animator can be set to different step increment values def test_channelAnimatorStepIncrement(self): driver = self.driver # Open a test image so we have something to animate Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "Default") # Open settings self._openSettings( driver ) # Find and click the step increment textbox stepIncrementText = driver.find_element_by_xpath( "//div[@id='ChannelStepIncrement']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", stepIncrementText) # Change the step increment spin box value to 2 stepValue = Util._changeElementText( self, driver, stepIncrementText, 2) # Go to first channel value and record the first channel value of the test image self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) print "Testing Channel Animator Step Increment Setting..." print "First channel value:", firstChannelValue print "Step Increment = 2" # Go to the next channel value self._getNextValue( driver, "Channel" ) # Check that the channel value increases by a step increment of 2 currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Current channel", currChannelValue self.assertEqual( int(currChannelValue), 2, "Channel Animator did not increase by a step increment of 2") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Open settings self._openSettings( driver ) # Find and click the step increment textbox stepIncrementText = driver.find_element_by_xpath( "//div[@id='ImageStepIncrement']/input") driver.execute_script( "arguments[0].scrollIntoView(true);", stepIncrementText) # Change the step increment spin box value to 2 stepValue = Util._changeElementText( self, driver, stepIncrementText, 2) # Record the first image value self._getFirstValue( driver, "Image" ) firstImageValue = self._getCurrentValue( driver, "Image" ) print "Testing Image Animator Step Increment Setting..." print "First image value:", firstImageValue print "Step Increment = 2" # Go to the next valid image self._getNextValue( driver, "Image" ) time.sleep(1) # Check that the image value increases by a step increment value of 2 currImageValue = self._getCurrentValue( driver, "Image" ) print "Current image:", currImageValue self.assertEqual( int(currImageValue), 2, "Image Animator did not increase by a step value of 2") # Test that the Channel Animator increases by one frame when the increase frame button is pressed def test_animatorIncreaseFrame(self): driver = self.driver timeout = selectBrowser._getSleep() # Open a test image so we have something to animate Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "Default") # Go to the first channel value and record the frame value self._getFirstValue( driver, "Channel" ) firstChannelValue = self._getCurrentValue( driver, "Channel" ) # Find the increment by one button on the Channel Animator Tape Deck and click it self._getNextValue( driver, "Channel" ) # Check that the channel text box value is now 1 currChannelValue = self._getCurrentValue( driver, "Channel") print "Check increase frame..." print "oldChannelValue= 0 newChannelValue=", currChannelValue self.assertEqual( int(currChannelValue), int(firstChannelValue)+1, "Failed to increment Channel Animator") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Record the first image value self._getFirstValue( driver, "Image" ) firstImageValue = self._getCurrentValue( driver, "Image" ) # Find the increment by one button on the Animator Tape Deck and click it self._getNextValue( driver, "Image" ) # Check that the image text box value is now 1 currImageValue = self._getCurrentValue( driver, "Image" ) print "Check increase image..." print "oldImageValue=", firstImageValue, "newImageValue=", currImageValue self.assertEqual( int(currImageValue), int(firstImageValue)+1, "Failed to increment the Image Animator") # Test that the Channel Animator decreases by one frame when the decrease frame button is pressed def test_animatorDecreaseFrame(self): driver = self.driver timeout = selectBrowser._getSleep() # Open a test image so we have something to animate Util.load_image( self, driver, "aH.fits") Util.load_image( self, driver, "aJ.fits") Util.load_image( self, driver, "Default") # Go to the last channel value and record the frame value self._getLastValue( driver, "Channel" ) lastChannelValue = self._getCurrentValue( driver, "Channel" ) # Find the decrement by one button on the Channel Animator Tape Deck and click it decrementButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ChannelTapeDeckDecrement"))) driver.execute_script( "arguments[0].scrollIntoView(true);", decrementButton) ActionChains(driver).click( decrementButton).perform() time.sleep( timeout ) # Check that the channel text box value is one less that the last frame value currChannelValue = self._getCurrentValue( driver, "Channel" ) print "Check decrease frame..." print "oldChannelValue=", lastChannelValue, "newChannelValue=",currChannelValue self.assertEqual( int(currChannelValue), int(lastChannelValue)-1, "Failed to decrement the Channel Animator") # Change the Channel Animator to an Image Animator self.channel_to_image_animator( driver ) # Record the first image value self._getLastValue( driver, "Image" ) lastImageValue = self._getCurrentValue( driver, "Image" ) # Find the decrement by one button on the Animator Tape Deck and click it decrementButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "ImageTapeDeckDecrement"))) driver.execute_script( "arguments[0].scrollIntoView(true);", decrementButton) ActionChains(driver).click( decrementButton).perform() time.sleep( timeout ) # Check that the image text box value is now 1
[ " currImageValue = self._getCurrentValue( driver, \"Image\")" ]
3,277
lcc
python
null
94c4df74ebdbcfad6ff07c35a32605e7d576c977242ba25c
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # Copyright (C) 2013-2014 science + computing ag # Author: Sebastian Deiss <sebastian.deiss@t-online.de> # # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ This module provides GSS-API / SSPI Key Exchange as defined in :rfc:`4462`. .. note:: Credential delegation is not supported in server mode. .. note:: `RFC 4462 Section 2.2 <https://tools.ietf.org/html/rfc4462.html#section-2.2>`_ says we are not required to implement GSS-API error messages. Thus, in many methods within this module, if an error occurs an exception will be thrown and the connection will be terminated. .. seealso:: :doc:`/api/ssh_gss` .. versionadded:: 1.15 """ import os from hashlib import sha1 from paramiko.common import DEBUG, max_byte, zero_byte from paramiko import util from paramiko.message import Message from paramiko.py3compat import byte_chr, byte_mask, byte_ord from paramiko.ssh_exception import SSHException MSG_KEXGSS_INIT, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_HOSTKEY,\ MSG_KEXGSS_ERROR = range(30, 35) MSG_KEXGSS_GROUPREQ, MSG_KEXGSS_GROUP = range(40, 42) c_MSG_KEXGSS_INIT, c_MSG_KEXGSS_CONTINUE, c_MSG_KEXGSS_COMPLETE,\ c_MSG_KEXGSS_HOSTKEY, c_MSG_KEXGSS_ERROR = [ byte_chr(c) for c in range(30, 35) ] c_MSG_KEXGSS_GROUPREQ, c_MSG_KEXGSS_GROUP = [ byte_chr(c) for c in range(40, 42) ] class KexGSSGroup1(object): """ GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange as defined in `RFC 4462 Section 2 <https://tools.ietf.org/html/rfc4462.html#section-2>`_ """ # draft-ietf-secsh-transport-09.txt, page 17 P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF # noqa G = 2 b7fffffffffffffff = byte_chr(0x7f) + max_byte * 7 # noqa b0000000000000000 = zero_byte * 8 # noqa NAME = "gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==" def __init__(self, transport): self.transport = transport self.kexgss = self.transport.kexgss_ctxt self.gss_host = None self.x = 0 self.e = 0 self.f = 0 def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. """ self._generate_x() if self.transport.server_mode: # compute f = g^x mod p, but don't send it yet self.f = pow(self.G, self.x, self.P) self.transport._expect_packet(MSG_KEXGSS_INIT) return # compute e = g^x mod p (where g=2), and send it self.e = pow(self.G, self.x, self.P) # Initialize GSS-API Key Exchange self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR) def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if self.transport.server_mode and (ptype == MSG_KEXGSS_INIT): return self._parse_kexgss_init(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_HOSTKEY): return self._parse_kexgss_hostkey(m) elif self.transport.server_mode and (ptype == MSG_KEXGSS_CONTINUE): return self._parse_kexgss_continue(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_COMPLETE): return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) raise SSHException('GSS KexGroup1 asked to handle packet type %d' % ptype) # ## internals... def _generate_x(self): """ generate an "x" (1 < x < q), where q is (p-1)/2. p is a 128-byte (1024-bit) number, where the first 64 bits are 1. therefore q can be approximated as a 2^1023. we drop the subset of potential x where the first 63 bits are 1, because some of those will be larger than q (but this is a tiny tiny subset of potential x). """ while 1: x_bytes = os.urandom(128) x_bytes = byte_mask(x_bytes[0], 0x7f) + x_bytes[1:] first = x_bytes[:8] if first not in (self.b7fffffffffffffff, self.b0000000000000000): break self.x = util.inflate_long(x_bytes) def _parse_kexgss_hostkey(self, m): """ Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message """ # client mode host_key = m.get_string() self.transport.host_key = host_key sig = m.get_string() self.transport._verify_key(host_key, sig) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE) def _parse_kexgss_continue(self, m): """ Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message """ if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token)) self.transport.send_message(m) self.transport._expect_packet( MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR ) else: pass def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ # client mode if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() if (self.f < 1) or (self.f > self.P - 1): raise SSHException('Server kex "f" is out of range') mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string() K = pow(self.f, self.x, self.P) # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add(self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init) hm.add_string(self.transport.host_key.__str__()) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(str(hm)).digest() self.transport._set_K_H(K, H) if srv_token is not None: self.kexgss.ssh_init_sec_context(target=self.gss_host, recv_token=srv_token) self.kexgss.ssh_check_mic(mic_token, H) else: self.kexgss.ssh_check_mic(mic_token, H) self.transport.gss_kex_used = True self.transport._activate_outbound() def _parse_kexgss_init(self, m): """ Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message """ # server mode client_token = m.get_string() self.e = m.get_mpint() if (self.e < 1) or (self.e > self.P - 1): raise SSHException('Client kex "e" is out of range') K = pow(self.e, self.x, self.P) self.transport.host_key = NullHostKey() key = self.transport.host_key.__str__() # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add(self.transport.remote_version, self.transport.local_version, self.transport.remote_kex_init, self.transport.local_kex_init) hm.add_string(key) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) srv_token = self.kexgss.ssh_accept_sec_context(self.gss_host, client_token) m = Message() if self.kexgss._gss_srv_ctxt_status: mic_token = self.kexgss.ssh_get_mic(self.transport.session_id, gss_kex=True) m.add_byte(c_MSG_KEXGSS_COMPLETE) m.add_mpint(self.f) m.add_string(mic_token) if srv_token is not None: m.add_boolean(True) m.add_string(srv_token) else: m.add_boolean(False) self.transport._send_message(m) self.transport.gss_kex_used = True self.transport._activate_outbound() else: m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(srv_token) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR) def _parse_kexgss_error(self, m): """ Parse the SSH2_MSG_KEXGSS_ERROR message (client mode). The server may send a GSS-API error message. if it does, we display the error by throwing an exception (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message :raise SSHException: Contains GSS-API major and minor status as well as the error message and the language tag of the message """ maj_status = m.get_int() min_status = m.get_int() err_msg = m.get_string() m.get_string() # we don't care about the language! raise SSHException("GSS-API Error:\nMajor Status: %s\nMinor Status: %s\ \nError Message: %s\n") % (str(maj_status), str(min_status), err_msg) class KexGSSGroup14(KexGSSGroup1): """ GSS-API / SSPI Authenticated Diffie-Hellman Group14 Key Exchange as defined in `RFC 4462 Section 2 <https://tools.ietf.org/html/rfc4462.html#section-2>`_ """ P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF # noqa G = 2 NAME = "gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==" class KexGSSGex(object): """ GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange as defined in `RFC 4462 Section 2 <https://tools.ietf.org/html/rfc4462.html#section-2>`_ """ NAME = "gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==" min_bits = 1024 max_bits = 8192 preferred_bits = 2048 def __init__(self, transport): self.transport = transport self.kexgss = self.transport.kexgss_ctxt self.gss_host = None self.p = None self.q = None self.g = None self.x = None self.e = None self.f = None self.old_style = False def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange """ if self.transport.server_mode: self.transport._expect_packet(MSG_KEXGSS_GROUPREQ) return # request a bit range: we accept (min_bits) to (max_bits), but prefer # (preferred_bits). according to the spec, we shouldn't pull the # minimum up above 1024. self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_GROUPREQ) m.add_int(self.min_bits) m.add_int(self.preferred_bits) m.add_int(self.max_bits) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_GROUP) def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if ptype == MSG_KEXGSS_GROUPREQ: return self._parse_kexgss_groupreq(m) elif ptype == MSG_KEXGSS_GROUP: return self._parse_kexgss_group(m) elif ptype == MSG_KEXGSS_INIT: return self._parse_kexgss_gex_init(m) elif ptype == MSG_KEXGSS_HOSTKEY: return self._parse_kexgss_hostkey(m) elif ptype == MSG_KEXGSS_CONTINUE: return self._parse_kexgss_continue(m) elif ptype == MSG_KEXGSS_COMPLETE: return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) raise SSHException('KexGex asked to handle packet type %d' % ptype) # ## internals... def _generate_x(self): # generate an "x" (1 < x < (p-1)/2). q = (self.p - 1) // 2 qnorm = util.deflate_long(q, 0) qhbyte = byte_ord(qnorm[0]) byte_count = len(qnorm) qmask = 0xff while not (qhbyte & 0x80): qhbyte <<= 1 qmask >>= 1 while True: x_bytes = os.urandom(byte_count) x_bytes = byte_mask(x_bytes[0], qmask) + x_bytes[1:] x = util.inflate_long(x_bytes, 1) if (x > 1) and (x < q): break self.x = x def _parse_kexgss_groupreq(self, m): """ Parse the SSH2_MSG_KEXGSS_GROUPREQ message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_GROUPREQ message """ minbits = m.get_int() preferredbits = m.get_int() maxbits = m.get_int() # smoosh the user's preferred size into our own limits if preferredbits > self.max_bits: preferredbits = self.max_bits if preferredbits < self.min_bits: preferredbits = self.min_bits # fix min/max if they're inconsistent. technically, we could just pout # and hang up, but there's no harm in giving them the benefit of the # doubt and just picking a bitsize for them. if minbits > preferredbits: minbits = preferredbits if maxbits < preferredbits: maxbits = preferredbits # now save a copy self.min_bits = minbits self.preferred_bits = preferredbits self.max_bits = maxbits # generate prime pack = self.transport._get_modulus_pack() if pack is None: raise SSHException( 'Can\'t do server-side gex with no modulus pack') self.transport._log( DEBUG, # noqa 'Picking p (%d <= %d <= %d bits)' % ( minbits, preferredbits, maxbits)) self.g, self.p = pack.get_modulus(minbits, preferredbits, maxbits) m = Message() m.add_byte(c_MSG_KEXGSS_GROUP) m.add_mpint(self.p) m.add_mpint(self.g) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_INIT) def _parse_kexgss_group(self, m): """ Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message """ self.p = m.get_mpint() self.g = m.get_mpint() # reject if p's bit length < 1024 or > 8192 bitlen = util.bit_length(self.p) if (bitlen < 1024) or (bitlen > 8192): raise SSHException( 'Server-generated gex p (don\'t ask) is out of range ' '(%d bits)' % bitlen) self.transport._log(DEBUG, 'Got server p (%d bits)' % bitlen) # noqa self._generate_x() # now compute e = g^x mod p self.e = pow(self.g, self.x, self.p) m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR) def _parse_kexgss_gex_init(self, m): """ Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_INIT message """ client_token = m.get_string() self.e = m.get_mpint() if (self.e < 1) or (self.e > self.p - 1): raise SSHException('Client kex "e" is out of range') self._generate_x() self.f = pow(self.g, self.x, self.p) K = pow(self.e, self.x, self.p) self.transport.host_key = NullHostKey() key = self.transport.host_key.__str__() # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) # noqa hm = Message() hm.add(self.transport.remote_version, self.transport.local_version, self.transport.remote_kex_init, self.transport.local_kex_init, key) hm.add_int(self.min_bits) hm.add_int(self.preferred_bits) hm.add_int(self.max_bits) hm.add_mpint(self.p) hm.add_mpint(self.g) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) srv_token = self.kexgss.ssh_accept_sec_context(self.gss_host, client_token) m = Message() if self.kexgss._gss_srv_ctxt_status: mic_token = self.kexgss.ssh_get_mic(self.transport.session_id, gss_kex=True) m.add_byte(c_MSG_KEXGSS_COMPLETE) m.add_mpint(self.f) m.add_string(mic_token) if srv_token is not None: m.add_boolean(True) m.add_string(srv_token) else: m.add_boolean(False) self.transport._send_message(m) self.transport.gss_kex_used = True self.transport._activate_outbound() else: m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(srv_token) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR) def _parse_kexgss_hostkey(self, m): """ Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message """ # client mode host_key = m.get_string() self.transport.host_key = host_key sig = m.get_string() self.transport._verify_key(host_key, sig) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE) def _parse_kexgss_continue(self, m): """ Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message """ if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host, recv_token=srv_token)) self.transport.send_message(m) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR) else: pass def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string()
[ " if (self.f < 1) or (self.f > self.p - 1):" ]
1,912
lcc
python
null
5aa80682c87ae812a93e6bb27ac638d91789e7695186311c
/* * SLD Editor - The Open Source Java SLD Editor * * Copyright (C) 2016, SCISYS UK Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sldeditor.extension.filesystem.database; import com.sldeditor.common.data.DatabaseConnection; import com.sldeditor.common.filesystem.FileSystemInterface; import com.sldeditor.datasource.extension.filesystem.node.FSTree; import com.sldeditor.datasource.extension.filesystem.node.FileSystemNodeManager; import com.sldeditor.datasource.extension.filesystem.node.database.DatabaseFeatureClassNode; import com.sldeditor.datasource.extension.filesystem.node.database.DatabaseNode; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /** * Class that handles the progress of reading databases for data sources. * * @author Robert Ward (SCISYS) */ public class DatabaseReadProgress implements DatabaseReadProgressInterface { /** Internal class to handle the state of the operation. */ class PopulateState { /** The feature class complete flag. */ private boolean featureClassComplete = false; /** Instantiates a new populate state. */ PopulateState() { startFeatureClasses(); } /** Sets the styles complete. */ public void setFeatureClassesComplete() { featureClassComplete = true; } /** * Checks if is complete. * * @return true, if is complete */ public boolean isComplete() { return featureClassComplete; } /** Start feature classes. */ public void startFeatureClasses() { featureClassComplete = false; } } /** The Constant PROGRESS_NODE_TITLE. */ private static final String PROGRESS_NODE_TITLE = "Progress"; /** The tree model. */ private DefaultTreeModel treeModel; /** The tree. */ private FSTree tree = null; /** The node map. */ private Map<DatabaseConnection, DatabaseNode> nodeMap = new HashMap<>(); /** The populate state map. */ private Map<DatabaseConnection, PopulateState> populateStateMap = new HashMap<>(); /** The feature class map. */ private Map<DatabaseConnection, List<String>> databaseFeatureClassMap = new HashMap<>(); /** The handler. */ private FileSystemInterface handler = null; /** The parse complete. */ private DatabaseParseCompleteInterface parseComplete = null; /** * Instantiates a new geo server read progress. * * @param handler the handler * @param parseComplete the parse complete */ public DatabaseReadProgress( FileSystemInterface handler, DatabaseParseCompleteInterface parseComplete) { this.handler = handler; this.parseComplete = parseComplete; } /** * Read feature classes complete. * * @param connection the connection * @param featureClassList the feature class list */ public void readFeatureClassesComplete( DatabaseConnection connection, List<String> featureClassList) { if (featureClassList == null) { return; } this.databaseFeatureClassMap.put(connection, featureClassList); // Update state PopulateState state = populateStateMap.get(connection); if (state != null) { state.setFeatureClassesComplete(); } checkPopulateComplete(connection); } /** * Check populate complete. * * @param connection the connection */ private void checkPopulateComplete(DatabaseConnection connection) { PopulateState state = populateStateMap.get(connection); if ((state != null) && state.isComplete()) { DatabaseNode databaseNode = nodeMap.get(connection); if (databaseNode != null) { removeNode(databaseNode, PROGRESS_NODE_TITLE); populateFeatureClasses(connection, databaseNode); if (treeModel != null) { // this notifies the listeners and changes the GUI treeModel.reload(databaseNode); } } parseComplete.populateComplete(connection, databaseFeatureClassMap.get(connection)); } } /** * Populate feature classes. * * @param connection the connection * @param databaseNode the database node */ private void populateFeatureClasses(DatabaseConnection connection, DatabaseNode databaseNode) { List<String> featureClassList = databaseFeatureClassMap.get(connection); for (String featureClass : featureClassList) { DatabaseFeatureClassNode fcNode = new DatabaseFeatureClassNode(this.handler, connection, featureClass); // It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode treeModel.insertNodeInto(fcNode, databaseNode, databaseNode.getChildCount()); } } /** * Removes the node. * * @param databaseNode the database node * @param nodeTitleToRemove the node title to remove */ public static void removeNode(DatabaseNode databaseNode, String nodeTitleToRemove) { if ((databaseNode != null) && (nodeTitleToRemove != null)) { for (int index = 0; index < databaseNode.getChildCount(); index++) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) databaseNode.getChildAt(index); String nodeName = (String) node.getUserObject(); if ((nodeName != null) && nodeName.startsWith(nodeTitleToRemove)) { databaseNode.remove(index); break; } } } } /* * (non-Javadoc) * * @see * com.sldeditor.extension.filesystem.database.DatabaseReadProgressInterface#startPopulating(com * .sldeditor.common.data.DatabaseConnection) */ @Override public void startPopulating(DatabaseConnection connection) { PopulateState state = populateStateMap.get(connection); if (state != null) { state.startFeatureClasses(); } } /** * Disconnect. * * @param connection the node */ public void disconnect(DatabaseConnection connection) { DatabaseNode node = nodeMap.get(connection); node.removeAllChildren(); if (treeModel != null) { treeModel.reload(node); } } /** * Sets the tree model. * * @param tree the tree * @param model the model */ public void setTreeModel(FSTree tree, DefaultTreeModel model) { this.tree = tree; this.treeModel = model; } /** * Adds the new connection node. * * @param connection the connection * @param node the node */ public void addNewConnectionNode(DatabaseConnection connection, DatabaseNode node) { nodeMap.put(connection, node); populateStateMap.put(connection, new PopulateState()); } /** * Refresh node. * * @param nodeToRefresh the node to refresh */ public void refreshNode(DefaultMutableTreeNode nodeToRefresh) { if (treeModel != null) { treeModel.reload(nodeToRefresh); } } /** * Delete connection. * * @param connection the connection */ public void deleteConnection(DatabaseConnection connection) { DatabaseNode node = nodeMap.get(connection); if (treeModel != null) { treeModel.removeNodeFromParent(node); } nodeMap.remove(connection); } /** * Update connection. * * @param originalConnectionDetails the original connection details * @param newConnectionDetails the new connection details */ public void updateConnection( DatabaseConnection originalConnectionDetails, DatabaseConnection newConnectionDetails) { if (newConnectionDetails != null) { DatabaseNode databaseNode = nodeMap.get(originalConnectionDetails); originalConnectionDetails.update(newConnectionDetails); if (databaseNode != null) { databaseNode.setUserObject(newConnectionDetails.getConnectionName()); refreshNode(databaseNode); setFolder(newConnectionDetails.getDatabaseTypeLabel(), newConnectionDetails, false); } } } /** * Sets the folder. * * @param overallNodeName the overall node name * @param connectionData the connection data * @param disableTreeSelection the disable tree selection */ public void setFolder( String overallNodeName, DatabaseConnection connectionData, boolean disableTreeSelection) { if (tree != null) {
[ " if (disableTreeSelection) {" ]
908
lcc
java
null
b607483b0c82f02c516bc92ffc69d9d3747ea0eaf71ca58a
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution, third party addon # Copyright (C) 2004-2015 Vertel AB (<http://vertel.se>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api, _ from openerp.exceptions import except_orm, Warning, RedirectWarning import logging _logger = logging.getLogger(__name__) class smart_salary_simulator_payslip(models.Model): _inherit = 'hr.payslip' def simulate_payslip(self, uid, salary, values): user = self.env['res.users'].browse(uid)[0] if user.employee_ids and user.employee_ids[0].contract_ids: employee = user.employee_ids[0] contract = employee.contract_ids[0] else: employee = self.env.ref('smart_salary_simulator_se.dummy_employee') contract = self.env.ref('smart_salary_simulator_se.smart_contract_swe') payslip = self.create({ 'struct_id': contract.struct_id.id, 'employee_id': employee.id, 'date_from': fields.Date.today(), 'date_to': fields.Date.today(), 'state': 'draft', 'contract_id': contract.id, 'input_line_ids': [ (0, _, { 'name': 'Salary Base', 'code': 'SALARY', 'contract_id': contract.id, 'amount': salary, }), #~ (0, _, { #~ 'name': 'Invoice VAT', #~ 'code': 'VAT', #~ 'contract_id': contract.id, #~ 'amount': values['vat'], #~ }), #~ (0, _, { #~ 'name': 'Smart Share', #~ 'code': 'SMARTSHARE', #~ 'contract_id': contract.id, #~ 'amount': values['smart_fee'], #~ }), #~ (0, _, { #~ 'name': 'Expenses', #~ 'code': 'EXPENSES', #~ 'contract_id': contract.id, #~ 'amount': values['expenses'], #~ }), #~ (0, _, { #~ 'name': 'Expenses VAT', #~ 'code': 'EXPVAT', #~ 'contract_id': contract.id, #~ 'amount': values['expenses'], #~ }), (0, _, { 'name': 'Year of Birth', 'code': 'YOB', 'contract_id': contract.id, 'amount': values['yob'], }), (0, _, { 'name': 'Current Year', 'code': 'YEAR', 'contract_id': contract.id, 'amount': fields.Date.from_string(fields.Date.today()).year, }), (0, _, { 'name': 'Musician', 'code': 'MUSICIAN', 'contract_id': contract.id, 'amount': 1 if values['musician'] == 'on' else 0, }), (0, _, { 'name': 'Withholding Tax Rate', 'code': 'WT', 'contract_id': contract.id, 'amount': values['tax'], }), ] }) result = payslip.simulate_sheet() payslip.unlink() return result def simulate_sheet(self): cr, uid, context = self.env.cr, self.env.uid, self.env.context ids = [] for record in self: ids.append(record.id) slip_line_pool = self.pool.get('hr.payslip.line') sequence_obj = self.pool.get('ir.sequence') for payslip in self.browse(ids): number = payslip.number or sequence_obj.get(cr, uid, 'salary.slip') #delete old payslip lines old_slipline_ids = slip_line_pool.search(cr, uid, [('slip_id', '=', payslip.id)], context=context) # old_slipline_ids if old_slipline_ids: slip_line_pool.unlink(cr, uid, old_slipline_ids, context=context) if payslip.contract_id: #set the list of contract for which the rules have to be applied contract_ids = [payslip.contract_id.id] else: #if we don't give the contract, then the rules to apply should be for all current contracts of the employee contract_ids = self.get_contract(cr, uid, payslip.employee_id, payslip.date_from, payslip.date_to, context=context) lines = [line for line in self.pool.get('hr.payslip').get_payslip_lines(cr, uid, contract_ids, payslip.id, context=context)] #self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context) lines.sort(key=lambda line: line['sequence']) return lines """ class smart_salary_simulator_payslip(models.TransientModel): _name = "smart_salary_simulator.payslip" _description = "Simulated payslip" _inherit = 'hr.payslip' def simulate_sheet(self): cr, uid, context = self.env.cr, self.env.uid, self.env.context #ids = [] #for record in self: # ids.append(record.id) slip_line_pool = self.env['hr.payslip.line'] sequence_obj = self.env['ir.sequence'] for payslip in self: #payslip.number = Reference (t.ex. SLIP/001) number = payslip.number or sequence_obj.get('salary.slip') #delete old payslip lines old_sliplines = slip_line_pool.search([('slip_id', '=', payslip.id)]) # old_slipline_ids for record in old_sliplines: slip_line_pool.unlink(cr, uid, [record.id], context=context) if payslip.contract_id: #set the list of contract for which the rules have to be applied contract_ids = [payslip.contract_id.id] else: #if we don't give the contract, then the rules to apply should be for all current contracts of the employee contract_ids = self.get_contract(payslip.employee_id, payslip.date_from, payslip.date_to) lines = [(0,0,line) for line in payslip.get_payslip_lines_sim(contract_ids)] #self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context) return lines @api.one def get_payslip_lines_sim(self, contract_ids): def _sum_salary_rule_category(localdict, category, amount): if category.parent_id: localdict = _sum_salary_rule_category(localdict, category.parent_id, amount) localdict['categories'].dict[category.code] = category.code in localdict['categories'].dict and localdict['categories'].dict[category.code] + amount or amount return localdict class BrowsableObject(object): def __init__(self, pool, cr, uid, employee_id, dict): self.pool = pool self.cr = cr self.uid = uid self.employee_id = employee_id self.dict = dict def __getattr__(self, attr): return attr in self.dict and self.dict.__getitem__(attr) or 0.0 class InputLine(BrowsableObject): """ """a class that will be used into the python code, mainly for usability purposes""" """ def sum(self, code, from_date, to_date=None): if to_date is None: to_date = datetime.now().strftime('%Y-%m-%d') result = 0.0 self.cr.execute("SELECT sum(amount) as sum\ FROM smart_salary_simulator_payslip as hp, hr_payslip_input as pi \ WHERE hp.employee_id = %s AND hp.state = 'done' \ AND hp.date_from >= %s AND hp.date_to <= %s AND hp.id = pi.payslip_id AND pi.code = %s", (self.employee_id, from_date, to_date, code)) res = self.cr.fetchone()[0] return res or 0.0 class WorkedDays(BrowsableObject): """ """a class that will be used into the python code, mainly for usability purposes""" """ def _sum(self, code, from_date, to_date=None): if to_date is None: to_date = datetime.now().strftime('%Y-%m-%d') result = 0.0 self.cr.execute("SELECT sum(number_of_days) as number_of_days, sum(number_of_hours) as number_of_hours\ FROM smart_salary_simulator_payslip as hp, hr_payslip_worked_days as pi \ WHERE hp.employee_id = %s AND hp.state = 'done'\ AND hp.date_from >= %s AND hp.date_to <= %s AND hp.id = pi.payslip_id AND pi.code = %s",
[ " (self.employee_id, from_date, to_date, code))" ]
836
lcc
python
null
7c44f14dfd55d7192d94587a0e3d0cb5b2dd53c6dd46b6f6
import os import sys import time import config import numpy as np from numpy import vectorize from scipy import interpolate, integrate from scipy import special from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline from scipy.ndimage.filters import gaussian_filter import pylab as pl from numba import double, float64, float32 from numba import jit import numba as nb import timeit #import fastcorr from CosmologyFunctions import CosmologyFunctions from mass_function import halo_bias_st, bias_mass_func_tinker, bias_mass_func_bocquet from convert_NFW_RadMass import MfracToMvir, MvirToMRfrac, MfracToMfrac, MvirTomMRfrac, MfracTomMFrac, dlnMdensitydlnMcritOR200, HuKravtsov from pressure_profiles import battaglia_profile_2d __author__ = ("Vinu Vikraman <vvinuv@gmail.com>") @jit(nopython=True) def Wk(zl, chil, zsarr, chisarr, Ns, constk): #zl = lens redshift #chil = comoving distant to lens #zsarr = redshift distribution of source #angsarr = angular diameter distance #Ns = Normalized redshift distribution of sources al = 1. / (1. + zl) Wk = constk * chil / al gw = 0.0 for i, N in enumerate(Ns): if chisarr[i] < chil: continue gw += ((chisarr[i] - chil) * N / chisarr[i]) gw *= (zsarr[1] - zsarr[0]) if gw <= 0: gw = 0. Wk = Wk * gw return Wk @jit(nopython=True) def integrate_halo(ell, lnzarr, chiarr, dVdzdOm, marr, mf, BDarr, rhobarr, rho_crit_arr, bias, Darr, pk, zsarr, chisarr, Ns, dlnz, dlnm, omega_b0, omega_m0, cosmo_h, constk, consty, input_mvir): ''' Eq. 3.1 Ma et al. ''' cl1h = 0.0 cl2h = 0.0 jj = 0 for i, lnzi in enumerate(lnzarr): zi = np.exp(lnzi) - 1. zp = 1. + zi #print zi, Wk(zi, chiarr[i], zsarr, angsarr, Ns, constk) kl_yl_multi = Wk(zi, chiarr[i], zsarr, chisarr, Ns, constk) * consty / chiarr[i] / chiarr[i] / rhobarr[i] mint = 0.0 mk2 = 0.0 my2 = 0.0 for mi in marr: kint = 0.0 yint = 0.0 if input_mvir: Mvir, Rvir, M200, R200, rho_s, Rs = MvirToMRfrac(mi, zi, BDarr[i], rho_crit_arr[i], cosmo_h, frac=200.0) else: Mvir, Rvir, M200, R200, rho_s, Rs = MfracToMvir(mi, zi, BDarr[i], rho_crit_arr[i], cosmo_h, frac=200.0) #Eq. 3.2 Ma et al rp = np.linspace(0, config.kRmax*Rvir, config.kRspace) for tr in rp: if tr == 0: continue kint += (tr * tr * np.sin(ell * tr / chiarr[i]) / (ell * tr / chiarr[i]) * rho_s / (tr/Rs) / (1. + tr/Rs)**2.) kint *= (4. * np.pi * (rp[1] - rp[0])) #Eq. 3.3 Ma et al xmax = config.yRmax * Rvir / Rs #Ma et al paper says that Eq. 3.3 convergence by r=5 rvir. xp = np.linspace(0, xmax, config.yRspace) ells = chiarr[i] / zp / Rs for x in xp: if x == 0: continue yint += (x * x * np.sin(ell * x / ells) / (ell * x / ells) * battaglia_profile_2d(x, 0., Rs, M200, R200, zi, rho_crit_arr[i], omega_b0, omega_m0, cosmo_h)) yint *= (4 * np.pi * Rs * (xp[1] - xp[0]) / ells / ells) mint += (dlnm * mf[jj] * kint * yint) mk2 += (dlnm * bias[jj] * mf[jj] * kint) my2 += (dlnm * bias[jj] * mf[jj] * yint) jj += 1 cl1h += (dVdzdOm[i] * kl_yl_multi * mint * zp) cl2h += (dVdzdOm[i] * pk[i] * Darr[i] * Darr[i] * kl_yl_multi * mk2 * my2) cl1h *= dlnz cl2h *= dlnz cl = cl1h + cl2h return cl1h, cl2h, cl @jit(nopython=True) def integrate_kkhalo(ell, lnzarr, chiarr, dVdzdOm, marr, mf, BDarr, rhobarr, rho_crit_arr, bias, Darr, pk, zsarr, chisarr, Ns, dlnz, dlnm, omega_b0, omega_m0, cosmo_h, constk, consty, input_mvir): ''' Eq. 3.1 Ma et al. ''' cl1h = 0.0 cl2h = 0.0 jj = 0 for i, lnzi in enumerate(lnzarr): zi = np.exp(lnzi) - 1. zp = 1. + zi #print zi, Wk(zi, chiarr[i], zsarr, angsarr, Ns, constk) kl_multi = Wk(zi, chiarr[i], zsarr, chisarr, Ns, constk) / chiarr[i] / chiarr[i] / rhobarr[i] mint = 0.0 mk2 = 0.0 for mi in marr: kint = 0.0 if input_mvir: Mvir, Rvir, M200, R200, rho_s, Rs = MvirToMRfrac(mi, zi, BDarr[i], rho_crit_arr[i], cosmo_h, frac=200.0) else: Mvir, Rvir, M200, R200, rho_s, Rs = MfracToMvir(mi, zi, BDarr[i], rho_crit_arr[i], cosmo_h, frac=200.0) #Eq. 3.2 Ma et al #limit_kk_Rvir.py tests the limit of Rvir. rp = np.linspace(0, config.kRmax * Rvir, config.kRspace) for tr in rp: if tr == 0: continue kint += (tr * tr * np.sin(ell * tr / chiarr[i]) / (ell * tr / chiarr[i]) * rho_s / (tr/Rs) / (1. + tr/Rs)**2.) kint *= (4. * np.pi * (rp[1] - rp[0])) mint += (dlnm * mf[jj] * kint * kint) mk2 += (dlnm * bias[jj] * mf[jj] * kint) jj += 1 cl1h += (dVdzdOm[i] * kl_multi * kl_multi * mint * zp) cl2h += (dVdzdOm[i] * pk[i] * Darr[i] * Darr[i] * kl_multi * kl_multi * mk2 * mk2 * zp) cl1h *= dlnz cl2h *= dlnz cl = cl1h + cl2h return cl1h, cl2h, cl @jit(nopython=True) def integrate_yyhalo(ell, lnzarr, chiarr, dVdzdOm, marr, mf, BDarr, rhobarr, rho_crit_arr, bias, Darr, pk, dlnz, dlnm, omega_b0, omega_m0, cosmo_h, constk, consty, input_mvir): ''' Eq. 3.1 Ma et al. ''' cl1h = 0.0 cl2h = 0.0 jj = 0 for i, lnzi in enumerate(lnzarr[:]): zi = np.exp(lnzi) - 1. zp = 1. + zi mint = 0.0 my2 = 0.0 for j, mi in enumerate(marr[:]): if input_mvir: Mvir, Rvir, M200, R200, rho_s, Rs = MvirToMRfrac(mi/cosmo_h, zi, BDarr[i], rho_crit_arr[i]*cosmo_h*cosmo_h, cosmo_h, frac=200.0) else: Mvir, Rvir, M200, R200, rho_s, Rs = MfracToMvir(mi, zi, BDarr[i], rho_crit_arr[i], cosmo_h, frac=200.0) xmax = config.yRmax * Rvir / Rs ells = chiarr[i] / cosmo_h / zp / Rs xarr = np.linspace(1e-5, xmax, config.yRspace) yint = 0. for x in xarr: if x == 0: continue yint += (x * x * np.sin(ell * x / ells) / (ell * x / ells) * battaglia_profile_2d(x, 0., Rs, M200, R200, zi, rho_crit_arr[i]*cosmo_h*cosmo_h, omega_b0, omega_m0, cosmo_h)) yint *= (4 * np.pi * Rs * (xarr[1] - xarr[0]) / ells / ells) mint += (dlnm * mf[jj] * yint * yint) my2 += (dlnm * bias[jj] * mf[jj] * yint) jj += 1 cl1h += (dVdzdOm[i] * consty * consty * mint * zp) cl2h += (dVdzdOm[i] * pk[i] * Darr[i] * Darr[i] * consty * consty * my2 * my2 * zp) cl1h *= dlnz cl2h *= dlnz cl = cl1h + cl2h return cl1h, cl2h, cl def cl_WL_tSZ(fwhm_k, fwhm_y, kk, yy, ky, zsfile, odir='../data'): ''' Compute WL X tSZ halomodel for a given source redshift distribution ''' if ky: sigma_k = fwhm_k * np.pi / 2.355 / 60. /180. #angle in radian sigma_y = fwhm_y * np.pi / 2.355 / 60. /180. #angle in radian sigmasq = sigma_k * sigma_y elif kk: sigma_k = fwhm_k * np.pi / 2.355 / 60. /180. #angle in radian sigmasq = sigma_k * sigma_k elif yy: sigma_y = fwhm_y * np.pi / 2.355 / 60. /180. #angle in radian sigmasq = sigma_y * sigma_y else: raise ValueError('Either kk, yy or ky should be True') cosmo0 = CosmologyFunctions(0) omega_b0 = cosmo0._omega_b0 omega_m0 = cosmo0._omega_m0 cosmo_h = cosmo0._h light_speed = config.light_speed #km/s mpctocm = config.mpctocm kB_kev_K = config.kB_kev_K sigma_t_cm = config.sigma_t_cm #cm^2 rest_electron_kev = config.rest_electron_kev #keV constk = 3. * omega_m0 * (cosmo_h * 100. / light_speed)**2. / 2. #Mpc^-2 consty = mpctocm * sigma_t_cm / rest_electron_kev fz= np.genfromtxt(zsfile) zsarr = fz[:,0] Ns = fz[:,1] zint = np.sum(Ns) * (zsarr[1] - zsarr[0]) Ns /= zint kmin = config.kmin #1/Mpc kmax = config.kmax kspace = config.kspace mmin = config.mmin mmax = config.mmax mspace = config.mspace zmin = config.zmin zmax = config.zmax zspace = config.zspace dlnk = np.log(kmax/kmin) / kspace lnkarr = np.linspace(np.log(kmin), np.log(kmax), kspace) karr = np.exp(lnkarr).astype(np.float64) #No little h #Input Mpc/h to power spectra and get Mpc^3/h^3 pk_arr = np.array([cosmo0.linear_power(k/cosmo0._h) for k in karr]).astype(np.float64) pkspl = InterpolatedUnivariateSpline(karr/cosmo0._h, pk_arr, k=2) #pl.loglog(karr, pk_arr) #pl.show() dlnm = np.log(mmax/mmin) / mspace lnmarr = np.linspace(np.log(mmin * cosmo0._h), np.log(mmax * cosmo0._h), mspace) marr = np.exp(lnmarr).astype(np.float64) lnzarr = np.linspace(np.log(1.+zmin), np.log(1.+zmax), zspace) zarr = np.exp(lnzarr) - 1.0 dlnz = np.log((1.+zmax)/(1.+zmin)) / zspace print 'dlnk, dlnm dlnz', dlnk, dlnm, dlnz #No little h #Need to give mass * h and get the sigma without little h #The following lines are used only used for ST MF and ST bias sigma_m0 = np.array([cosmo0.sigma_m(m) for m in marr]) rho_norm0 = cosmo0.rho_bar() lnMassSigmaSpl = InterpolatedUnivariateSpline(lnmarr, sigma_m0, k=3) hzarr, BDarr, rhobarr, chiarr, dVdzdOm, rho_crit_arr = [], [], [], [], [], [] bias, Darr = [], [] mf, dlnmdlnm = [], [] for i, zi in enumerate(zarr): cosmo = CosmologyFunctions(zi) rcrit = cosmo.rho_crit() rbar = cosmo.rho_bar() bn = cosmo.BryanDelta() BDarr.append(bn) #OK rho_crit_arr.append(rcrit) #OK rhobarr.append(rbar) chiarr.append(cosmo.comoving_distance()) hzarr.append(cosmo.E0(zi)) #Number of Msun objects/Mpc^3 (i.e. unit is 1/Mpc^3)
[ " if config.MF =='Tinker':" ]
1,377
lcc
python
null
a4496fc9e2bf0797e31ad91e16fcbb8eef95cbc5986bb746
// $Id: FigSingleLineText.java 132 2010-09-26 23:32:33Z marcusvnac $ // Copyright (c) 1996-2008 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.diagram.ui; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.util.Arrays; import javax.swing.SwingUtilities; import org.argouml.model.AttributeChangeEvent; import org.argouml.model.InvalidElementException; import org.argouml.model.Model; import org.argouml.model.UmlChangeEvent; import org.argouml.uml.diagram.DiagramSettings; import org.tigris.gef.presentation.FigText; /** * A SingleLine FigText to provide consistency across Figs displaying single * lines of text.<ul> * <li>The display area is transparent * <li>Text is center justified * <li>There is no line border * <li>There is space below the line for a "Clarifier", * i.e. a red squiggly line. * </ul><p> * * Some of these have an UML object as owner, others do not. * * @author Bob Tarling */ public class FigSingleLineText extends ArgoFigText { /** * The properties of 'owner' that this is interested in */ private String[] properties; /** * The constructor. * * @param x the initial x position * @param y the initial y position * @param w the initial width * @param h the initial height * @param expandOnly true if the Fig should never shrink * @deprecated for 0.27.3 by tfmorris. Use * {@link #FigSingleLineText(Object, Rectangle, DiagramSettings, boolean)}. */ @SuppressWarnings("deprecation") @Deprecated public FigSingleLineText(int x, int y, int w, int h, boolean expandOnly) { super(x, y, w, h, expandOnly); initialize(); // initNotationArguments(); /* There is no NotationProvider yet! */ } private void initialize() { setFillColor(FILL_COLOR); // in case someone turns it on setFilled(false); setTabAction(FigText.END_EDITING); setReturnAction(FigText.END_EDITING); setLineWidth(0); setTextColor(TEXT_COLOR); } /** * The constructor. * * @param x the initial x position * @param y the initial y position * @param w the initial width * @param h the initial height * @param expandOnly true if this fig shall not shrink * @param property the property to listen to * @deprecated for 0.27.3 by tfmorris. Use * {@link #FigSingleLineText(Object, Rectangle, DiagramSettings, boolean)}. */ @Deprecated public FigSingleLineText(int x, int y, int w, int h, boolean expandOnly, String property) { this(x, y, w, h, expandOnly, new String[] {property}); } /** * The constructor. * * @param x the initial x position * @param y the initial y position * @param w the initial width * @param h the initial height * @param expandOnly true if this fig shall not shrink * @param allProperties the properties to listen to * @see org.tigris.gef.presentation.FigText#FigText( * int, int, int, int, boolean) * @deprecated for 0.27.3 by tfmorris. Use * {@link #FigSingleLineText(Object, Rectangle, DiagramSettings, boolean)}. */ @Deprecated public FigSingleLineText(int x, int y, int w, int h, boolean expandOnly, String[] allProperties) { this(x, y, w, h, expandOnly); this.properties = allProperties; } /** * Construct text fig * * @param owner owning UML element * @param bounds position and size * @param settings rendering settings * @param expandOnly true if the Fig should only expand and never contract */ public FigSingleLineText(Object owner, Rectangle bounds, DiagramSettings settings, boolean expandOnly) { this(owner, bounds, settings, expandOnly, (String[]) null); } /** * Construct text fig * * @param owner owning UML element * @param bounds position and size * @param settings rendering settings * @param expandOnly true if the Fig should only expand and never contract * @param property name of property to listen to */ public FigSingleLineText(Object owner, Rectangle bounds, DiagramSettings settings, boolean expandOnly, String property) { this(owner, bounds, settings, expandOnly, new String[] {property}); } /** * Constructor for text fig without owner. * Using this constructor shall mean * that this fig will never have an owner. * * @param bounds position and size * @param settings rendering settings * @param expandOnly true if the Fig should only expand and never contract */ public FigSingleLineText(Rectangle bounds, DiagramSettings settings, boolean expandOnly) { this(null, bounds, settings, expandOnly); } /** * Construct text fig * * @param owner owning UML element * @param bounds position and size * @param settings rendering settings * @param expandOnly true if the Fig should only expand and never contract * @param allProperties names of properties to listen to */ public FigSingleLineText(Object owner, Rectangle bounds, DiagramSettings settings, boolean expandOnly, String[] allProperties) { super(owner, bounds, settings, expandOnly); initialize(); this.properties = allProperties; addModelListener(); } @Override public Dimension getMinimumSize() { Dimension d = new Dimension(); Font font = getFont();
[ " if (font == null) {" ]
924
lcc
java
null
d18db499c41a15c135ce3f82d3cc62afdcd46c02c9a100e3
import numpy as np from numpy.linalg import inv import os #see detail comments in hexahedra_4 x0_v,y0_v,z0_v=np.array([1.,0.,0.]),np.array([0.,1.,0.]),np.array([0.,0.,1.]) #anonymous function f1 calculating transforming matrix with the basis vector expressions,x1y1z1 is the original basis vector #x2y2z2 are basis of new coor defined in the original frame,new=T.orig f1=lambda x1,y1,z1,x2,y2,z2:np.array([[np.dot(x2,x1),np.dot(x2,y1),np.dot(x2,z1)],\ [np.dot(y2,x1),np.dot(y2,y1),np.dot(y2,z1)],\ [np.dot(z2,x1),np.dot(z2,y1),np.dot(z2,z1)]]) #f2 calculate the distance b/ p1 and p2 f2=lambda p1,p2:np.sqrt(np.sum((p1-p2)**2)) #anonymous function f3 is to calculate the coordinates of basis with magnitude of 1.,p1 and p2 are coordinates for two known points, the #direction of the basis is pointing from p1 to p2 f3=lambda p1,p2:(1./f2(p1,p2))*(p2-p1)+p1 basis=np.array([5.038,5.434,7.3707]) #atoms to be checked for distance atms_cell_half=[[0.653,1.1121,1.903],[0.847,0.6121,1.903],[0.306,0.744,1.75],[0.194,0.243,1.75],\ [0.5,1.019,1.645],[0,0.518,1.645],[0.847,0.876,1.597],[0.653,0.375,1.597]] atms_cell_full=[[0.153,0.9452,2.097],[0.347,0.4452,2.097],[0.653,1.1121,1.903],[0.847,0.6121,1.903],[0.,0.9691,1.855],[0.5,0.4691,1.855],[0.306,0.744,1.75],[0.194,0.243,1.75],\ [0.5,1.019,1.645],[0,0.518,1.645],[0.847,0.876,1.597],[0.653,0.375,1.597]] atms_cell=atms_cell_half atms=np.append(np.array(atms_cell),np.array(atms_cell)+[-1,0,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[1,0,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[0,-1,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[0,1,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[1,1,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[-1,-1,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[1,-1,0],axis=0) atms=np.append(atms,np.array(atms_cell)+[-1,1,0],axis=0) atms=atms*basis O1,O2=[0.653,1.1121,1.903]*basis,[0.847,0.6121,1.903]*basis O3,O4=[0.306,0.744,1.75]*basis,[0.194,0.243,1.75]*basis O11_top,O12_top=[0.153,0.9452,2.097]*basis,[0.347,0.4452,2.097]*basis anchor1,anchor2=O1,O2 class share_face(): def __init__(self,face=np.array([[0.,0.,2.5],[2.5,0,0.],[0,2.5,0]]),mirror=False): #pass in the vector of three known vertices #mirror setting will make the sorbate projecting in an opposite direction referenced to the p0p1p2 plane self.face=face self.mirror=mirror def share_face_init(self,flag='right_triangle',dr=[0,0,0]): #octahedra has a high symmetrical configuration,there are only two types of share face. #flag 'right_triangle' means the shared face is defined by a right triangle with two equal lateral and the other one #passing through body center;'regular_triangle' means the shared face is defined by a regular triangle #dr is used for fitting purpose, set this to be 0 to get a regular octahedral p0,p1,p2=self.face[0,:],self.face[1,:],self.face[2,:] #consider the possible unregular shape for the known triangle dist_list=[np.sqrt(np.sum((p0-p1)**2)),np.sqrt(np.sum((p1-p2)**2)),np.sqrt(np.sum((p0-p2)**2))] index=dist_list.index(max(dist_list)) if flag=='right_triangle': #'2_1'tag means 2 atoms at upside and downside, the other one at middle layer if index==0:self.center_point=(p0+p1)/2 elif index==1:self.center_point=(p1+p2)/2 elif index==2:self.center_point=(p0+p2)/2 else:self.center_point=(p0+p2)/2 elif flag=='regular_triangle': #the basic idea is building a sperical coordinate system centering at the middle point of each two of the three corner #and then calculate the center point through theta angle, which can be easily calculated under that geometrical seting def _cal_center(p1,p2,p0): origin=(p1+p2)/2 y_v=f3(np.zeros(3),p1-origin) x_v=f3(np.zeros(3),p0-origin) z_v=np.cross(x_v,y_v) T=f1(x0_v,y0_v,z0_v,x_v,y_v,z_v) r=f2(p1,p2)/2. phi=0. theta=np.pi/2+np.arctan(np.sqrt(2)) if self.mirror: theta=np.pi/2-np.arctan(np.sqrt(2)) center_point_new=np.array([r*np.cos(phi)*np.sin(theta),r*np.sin(phi)*np.sin(theta),r*np.cos(theta)]) center_point_org=np.dot(inv(T),center_point_new)+origin #the two possible points are related to each other via invertion over the origin if abs(f2(center_point_org,p0)-f2(center_point_org,p1))>0.00001: center_point_org=2*origin-center_point_org return center_point_org self.center_point=_cal_center(p0,p1,p2) self._find_the_other_three(self.center_point,p0,p1,p2,flag,dr) def _find_the_other_three(self,center_point,p0,p1,p2,flag,dr): dist_list=[np.sqrt(np.sum((p0-p1)**2)),np.sqrt(np.sum((p1-p2)**2)),np.sqrt(np.sum((p0-p2)**2))] index=dist_list.index(max(dist_list)) if flag=='right_triangle': def _cal_points(center_point,p0,p1,p2): #here p0-->p1 is the long lateral z_v=f3(np.zeros(3),p2-center_point) x_v=f3(np.zeros(3),p0-center_point) y_v=np.cross(z_v,x_v) T=f1(x0_v,y0_v,z0_v,x_v,y_v,z_v) r=f2(center_point,p0) #print [r*np.cos(np.pi/2)*np.sin(np.pi/2),r*np.sin(np.pi/2)*np.sin(np.pi/2),0] p3_new=np.array([r*np.cos(np.pi/2)*np.sin(np.pi/2),r*np.sin(np.pi/2)*np.sin(np.pi/2),0]) p4_new=np.array([r*np.cos(3*np.pi/2)*np.sin(np.pi/2),r*np.sin(3*np.pi/2)*np.sin(np.pi/2),0]) p3_old=np.dot(inv(T),p3_new)+center_point p4_old=np.dot(inv(T),p4_new)+center_point p5_old=2*center_point-p2 return T,r,p3_old,p4_old,p5_old if index==0:#p0-->p1 long lateral self.T,self.r,self.p3,self.p4,self.p5=_cal_points(center_point,p0,p1,p2) elif index==1:#p1-->p2 long lateral self.T,self.r,self.p3,self.p4,self.p5=_cal_points(center_point,p1,p2,p0) elif index==2:#p0-->p2 long lateral self.T,self.r,self.p3,self.p4,self.p5=_cal_points(center_point,p0,p2,p1) elif flag=='regular_triangle': x_v=f3(np.zeros(3),p2-center_point) y_v=f3(np.zeros(3),p0-center_point) z_v=np.cross(x_v,x_v) self.T=f1(x0_v,y0_v,z0_v,x_v,y_v,z_v) self.r=f2(center_point,p0) self.p3=(center_point-p0)*((self.r+dr[0])/self.r)+center_point self.p4=(center_point-p1)*((self.r+dr[1])/self.r)+center_point self.p5=(center_point-p2)*((self.r+dr[2])/self.r)+center_point #print f2(self.center_point,self.p3),f2(self.center_point,self.p4) def cal_point_in_fit(self,r,theta,phi): #during fitting,use the same coordinate system, but a different origin #note the origin_coor is the new position for the sorbate0, ie new center point x=r*np.cos(phi)*np.sin(theta) y=r*np.sin(phi)*np.sin(theta) z=r*np.cos(theta) point_in_original_coor=np.dot(inv(self.T),np.array([x,y,z]))+self.center_point return point_in_original_coor def print_xyz(self,file="D:\\test.xyz"): f=open(file,"w") f.write('7\n#\n') s = '%-5s %7.5e %7.5e %7.5e\n' % ('Sb', self.center_point[0],self.center_point[1],self.center_point[2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e\n' % ('O', self.face[0,:][0],self.face[0,:][1],self.face[0,:][2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e\n' % ('O', self.face[1,:][0],self.face[1,:][1],self.face[1,:][2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e\n' % ('O', self.face[2,:][0],self.face[2,:][1],self.face[2,:][2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e\n' % ('O', self.p3[0],self.p3[1],self.p3[2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e\n' % ('O', self.p4[0],self.p4[1],self.p4[2]) f.write(s) s = '%-5s %7.5e %7.5e %7.5e' % ('O', self.p5[0],self.p5[1],self.p5[2]) f.write(s) f.close() class share_edge(share_face): def __init__(self,edge=np.array([[0.,0.,0.],[5,5,5]])): self.edge=edge def cal_p2(self,ref_p=None,phi=np.pi/2,flag='off_center',**args): p0=self.edge[0,:] p1=self.edge[1,:] origin=(p0+p1)/2 dist=f2(p0,p1) diff=p1-p0 c=np.sum(p1**2-p0**2) ref_point=0 if ref_p!=None: ref_point=np.cross(p0-origin,np.cross(p0-origin,ref_p-origin))+origin #print ref_point elif diff[2]==0: ref_point=origin+[0,0,1] else: x,y,z=0.,0.,0. #set the reference point as simply as possible,using the same distance assumption, we end up with a plane equation #then we try to find one cross point between one of the three basis and the plane we just got #here combine two line equations (ref-->p0,and ref-->p1,the distance should be the same) if diff[0]!=0: x=c/(2*diff[0]) elif diff[1]!=0.: y=c/(2*diff[1]) elif diff[2]!=0.: z=c/(2*diff[2]) ref_point=np.array([x,y,z]) if sum(ref_point)==0: #if the vector (p0-->p1) pass through origin [0,0,0],we need to specify another point satisfying the same-distance condition #here, we a known point (x0,y0,z0)([0,0,0] in this case) and the normal vector to calculate the plane equation, #which is a(x-x0)+b(y-y0)+c(z-z0)=0, we specify x y to 1 and 0, calculate z value. #a b c coresponds to vector origin-->p0 ref_point=np.array([1.,0.,-p0[0]/p0[2]]) if flag=='cross_center': x1_v=f3(np.zeros(3),ref_point-origin) z1_v=f3(np.zeros(3),p1-origin) y1_v=np.cross(z1_v,x1_v) T=f1(x0_v,y0_v,z0_v,x1_v,y1_v,z1_v) r=dist/2 #here phi=[0,2pi] x_p2=r*np.cos(phi)*np.sin(np.pi/2) y_p2=r*np.sin(phi)*np.sin(np.pi/2) z_p2=0 p2_new=np.array([x_p2,y_p2,z_p2]) p2_old=np.dot(inv(T),p2_new)+origin self.p2=p2_old self.face=np.append(self.edge,[p2_old],axis=0) self.flag='right_triangle' elif flag=='off_center': x1_v=f3(np.zeros(3),ref_point-origin) z1_v=f3(np.zeros(3),p1-origin) y1_v=np.cross(z1_v,x1_v) T=f1(x0_v,y0_v,z0_v,x1_v,y1_v,z1_v) r=dist/2. #note in this case, phi can be in the range of [0,2pi] x_center=r*np.cos(phi)*np.sin(np.pi/2) y_center=r*np.sin(phi)*np.sin(np.pi/2) z_center=r*np.cos(np.pi/2) center_org=np.dot(inv(T),np.array([x_center,y_center,z_center]))+origin p2_old=2*center_org-p0 self.p2=p2_old self.face=np.append(self.edge,[p2_old],axis=0) self.flag='right_triangle' def all_in_all(self,phi=np.pi/2,ref_p=None,flag='off_center'): self.cal_p2(ref_p=ref_p,phi=phi,flag=flag) self.share_face_init(self.flag) #steric_check will check the steric feasibility by changing the theta angle (0-pi) and or phi [0,2pi] #the dist bw sorbate(both metal and oxygen) and atms (defined on top) will be cal and compared to the cutting_limit #higher cutting limit will result in fewer items in return file (so be wise to choose cutting limit) #the container has 12 items, ie phi (rotation angle), theta, low_dis, apex coors (x,y,z), os1 coors(x,y,z),os2 coors(x,y,z) #in which the low_dis is the lowest dist between sorbate and atm class steric_check(share_edge): def __init__(self,p0=anchor1,p1=anchor2,cutting_limit=2.5): self.edge=np.array([p0,p1]) self.cutting_limit=cutting_limit self.container=np.zeros((1,18))[0:0] print "distance between anchor points is ",f2(p0,p1),'anstrom' def steric_check(self,theta_res=0.1,phi=np.pi/2,flag='off_center',print_path=None): #consider the steric constrain, flag 'off_center' (the center point is off the connection line of anchors) #is more favorable
[ " for theta in np.arange(0,np.pi,theta_res):" ]
800
lcc
python
null
837dcdc595cabd1df2ffe38aeec0464032bc96b95bb36f75
namespace SampleRithmic { using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using Ecng.Common; using Ecng.Xaml; using MoreLinq; using Ookii.Dialogs.Wpf; using StockSharp.Messages; using StockSharp.BusinessEntities; using StockSharp.Rithmic; using StockSharp.Logging; using StockSharp.Xaml; using StockSharp.Localization; public partial class MainWindow { public static MainWindow Instance { get; private set; } public static readonly DependencyProperty IsConnectedProperty = DependencyProperty.Register("IsConnected", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool))); public bool IsConnected { get { return (bool)GetValue(IsConnectedProperty); } set { SetValue(IsConnectedProperty, value); } } public RithmicTrader Trader { get; private set; } private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly LogManager _logManager = new LogManager(); public MainWindow() { InitializeComponent(); Instance = this; _securitiesWindow.MakeHideable(); _ordersWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); _myTradesWindow.MakeHideable(); var guilistener = new GuiLogListener(LogControl); //guilistener.Filters.Add(msg => msg.Level > LogLevels.Debug); _logManager.Listeners.Add(guilistener); _logManager.Listeners.Add(new FileLogListener("rithmic") { LogDirectory = "Logs" }); } protected override void OnClosing(CancelEventArgs e) { Properties.Settings.Default.Save(); _securitiesWindow.DeleteHideable(); _ordersWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _securitiesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); _myTradesWindow.Close(); if (Trader != null) Trader.Dispose(); base.OnClosing(e); } private void ConnectClick(object sender, RoutedEventArgs e) { var pwd = PwdBox.Password; if (!IsConnected) { var settings = Properties.Settings.Default; if (settings.Username.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3751); return; } if (pwd.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str2975); return; } if (Trader == null) { // create connector Trader = new RithmicTrader { LogLevel = LogLevels.Debug }; _logManager.Sources.Add(Trader); // subscribe on connection successfully event Trader.Connected += () => { this.GuiAsync(() => OnConnectionChanged(true)); }; // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // subscribe on error event //Trader.Error += error => // this.GuiAsync(() => MessageBox.Show(this, error.ToString(), "Error")); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; } Trader.UserName = settings.Username; Trader.Server = settings.Server; Trader.Password = pwd; Trader.CertFile = settings.CertFile; Trader.Connect(); } else { Trader.Disconnect(); } } private void OnConnectionChanged(bool isConnected) { IsConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) { var msg = fail.Error.ToString(); MessageBox.Show(this, msg, LocalizedStrings.Str2960); } }); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException("window");
[ "\t\t\tif (window.Visibility == Visibility.Visible)" ]
471
lcc
csharp
null
a50aee631ed0face644834967b1fc81b37cc66c1782f1e1a
import ROOT from ..core import Object, isbasictype, snake_case_methods from .core import Plottable, dim from ..objectproxy import ObjectProxy from ..registry import register from .graph import Graph from array import array class DomainError(Exception): pass class _HistBase(Plottable, Object): TYPES = { 'C': [ROOT.TH1C, ROOT.TH2C, ROOT.TH3C], 'S': [ROOT.TH1S, ROOT.TH2S, ROOT.TH3S], 'I': [ROOT.TH1I, ROOT.TH2I, ROOT.TH3I], 'F': [ROOT.TH1F, ROOT.TH2F, ROOT.TH3F], 'D': [ROOT.TH1D, ROOT.TH2D, ROOT.TH3D] } def __init__(self): Plottable.__init__(self) def _parse_args(self, *args): params = [{'bins': None, 'nbins': None, 'low': None, 'high': None} for _ in xrange(dim(self))] for param in params: if len(args) == 0: raise TypeError("Did not receive expected number of arguments") if type(args[0]) in [tuple, list]: if list(sorted(args[0])) != list(args[0]): raise ValueError( "Bin edges must be sorted in ascending order") if len(set(args[0])) != len(args[0]): raise ValueError("Bin edges must not be repeated") param['bins'] = args[0] param['nbins'] = len(args[0]) - 1 args = args[1:] elif len(args) >= 3: nbins = args[0] if type(nbins) is not int: raise TypeError( "Type of first argument (got %s %s) must be an int" % (type(nbins), nbins)) low = args[1] if not isbasictype(low): raise TypeError( "Type of second argument must be int, float, or long") high = args[2] if not isbasictype(high): raise TypeError( "Type of third argument must be int, float, or long") param['nbins'] = nbins param['low'] = low param['high'] = high if low >= high: raise ValueError( "Upper bound (you gave %f) must be greater than lower " "bound (you gave %f)" % (float(low), float(high))) args = args[3:] else: raise TypeError( "Did not receive expected number of arguments") if len(args) != 0: raise TypeError( "Did not receive expected number of arguments") return params @classmethod def divide(cls, h1, h2, c1=1., c2=1., option=''): ratio = h1.Clone() rootbase = h1.__class__.__bases__[-1] rootbase.Divide(ratio, h1, h2, c1, c2, option) return ratio def Fill(self, *args): bin = self.__class__.__bases__[-1].Fill(self, *args) if bin > 0: return bin - 1 return bin def nbins(self, axis=1): if axis == 1: return self.GetNbinsX() elif axis == 2: return self.GetNbinsY() elif axis == 3: return self.GetNbinsZ() else: raise ValueError("%s is not a valid axis index!" % axis) def axis(self, axis=1): if axis == 1: return self.GetXaxis() elif axis == 2: return self.GetYaxis() elif axis == 3: return self.GetZaxis() else: raise ValueError("%s is not a valid axis index!" % axis) @property def xaxis(self): return self.GetXaxis() @property def yaxis(self): return self.GetYaxis() @property def zaxis(self): return self.GetZaxis() def underflow(self, axis=1): """ Return the underflow for the given axis. Depending on the dimension of the histogram, may return an array. """ if axis not in [1, 2, 3]: raise ValueError("%s is not a valid axis index!" % axis) if self.DIM == 1: return self.GetBinContent(0) elif self.DIM == 2: return [self.GetBinContent(*[i].insert(axis - 1, 0)) for i in xrange(self.nbins((axis + 1) % 2))] elif self.DIM == 3: axis2, axis3 = [1, 2, 3].remove(axis) return [[self.GetBinContent(*[i, j].insert(axis - 1, 0)) for i in xrange(self.nbins(axis2))] for j in xrange(self.nbins(axis3))] def overflow(self, axis=1): """ Return the overflow for the given axis. Depending on the dimension of the histogram, may return an array. """ if axis not in [1, 2, 3]: raise ValueError("%s is not a valid axis index!" % axis) if self.DIM == 1: return self.GetBinContent(self.nbins(1) + 1) elif self.DIM == 2: axis2 = [1, 2].remove(axis) return [self.GetBinContent(*[i].insert(axis - 1, self.nbins(axis))) for i in xrange(self.nbins(axis2))] elif self.DIM == 3: axis2, axis3 = [1, 2, 3].remove(axis) return [[self.GetBinContent( *[i, j].insert(axis - 1, self.nbins(axis))) for i in xrange(self.nbins(axis2))] for j in xrange(self.nbins(axis3))] def lowerbound(self, axis=1): if axis == 1: return self.xedges(0) if axis == 2: return self.yedges(0) if axis == 3: return self.zedges(0) return ValueError("axis must be 1, 2, or 3") def upperbound(self, axis=1): if axis == 1: return self.xedges(-1) if axis == 2: return self.yedges(-1) if axis == 3: return self.zedges(-1) return ValueError("axis must be 1, 2, or 3") def _centers(self, axis, index=None): if index is None: return (self._centers(axis, i) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return (self._edgesl(axis, index) + self._edgesh(axis, index)) / 2 def _edgesl(self, axis, index=None): if index is None: return (self._edgesl(axis, i) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return self.axis(axis).GetBinLowEdge(index + 1) def _edgesh(self, axis, index=None): if index is None: return (self._edgesh(axis, i) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return self.axis(axis).GetBinUpEdge(index + 1) def _edges(self, axis, index=None): nbins = self.nbins(axis) if index is None: def temp_generator(): for index in xrange(nbins): yield self._edgesl(axis, index) yield self._edgesh(axis, index) return temp_generator() index = index % (nbins + 1) if index == nbins: return self._edgesh(axis, -1) return self._edgesl(axis, index) def _width(self, axis, index=None): if index is None: return (self._width(axis, i) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return self._edgesh(axis, index) - self._edgesl(axis, index) def _erravg(self, axis, index=None): if index is None: return (self._erravg(axis, i) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return self._width(axis, index) / 2 def _err(self, axis, index=None): if index is None: return ((self._erravg(axis, i), self._erravg(axis, i)) for i in xrange(self.nbins(axis))) index = index % self.nbins(axis) return (self._erravg(axis, index), self._erravg(axis, index)) def __add__(self, other): copy = self.Clone() copy += other return copy def __iadd__(self, other): if isbasictype(other): if not isinstance(self, _Hist): raise ValueError( "A multidimensional histogram must be filled with a tuple") self.Fill(other) elif type(other) in [list, tuple]: if dim(self) not in [len(other), len(other) - 1]: raise ValueError( "Dimension of %s does not match dimension " "of histogram (with optional weight as last element)" % str(other)) self.Fill(*other) else: self.Add(other) return self def __sub__(self, other): copy = self.Clone() copy -= other return copy def __isub__(self, other): if isbasictype(other): if not isinstance(self, _Hist): raise ValueError( "A multidimensional histogram must be filled with a tuple") self.Fill(other, -1) elif type(other) in [list, tuple]: if len(other) == dim(self): self.Fill(*(other + (-1, ))) elif len(other) == dim(self) + 1: # negate last element self.Fill(*(other[:-1] + (-1 * other[-1], ))) else: raise ValueError( "Dimension of %s does not match dimension " "of histogram (with optional weight as last element)" % str(other)) else: self.Add(other, -1.) return self def __mul__(self, other): copy = self.Clone() copy *= other return copy def __imul__(self, other): if isbasictype(other): self.Scale(other) return self self.Multiply(other) return self def __div__(self, other): copy = self.Clone() copy /= other return copy def __idiv__(self, other): if isbasictype(other): if other == 0: raise ZeroDivisionError() self.Scale(1. / other) return self self.Divide(other) return self def __radd__(self, other): if other == 0: return self.Clone() raise TypeError("unsupported operand type(s) for +: '%s' and '%s'" % (other.__class__.__name__, self.__class__.__name__)) def __rsub__(self, other): if other == 0: return self.Clone() raise TypeError("unsupported operand type(s) for -: '%s' and '%s'" % (other.__class__.__name__, self.__class__.__name__)) def __len__(self): return self.GetNbinsX() def __getitem__(self, index): # TODO: Perhaps this should return a Hist object of dimension (DIM - 1) if index not in range(-1, len(self) + 1): raise IndexError("bin index %i out of range" % index) def __setitem__(self, index): if index not in range(-1, len(self) + 1): raise IndexError("bin index %i out of range" % index) def __iter__(self): return iter(self._content()) def __cmp__(self, other): diff = self.maximum() - other.maximum() if diff > 0: return 1 if diff < 0: return -1 return 0 def errors(self): return iter(self._error_content()) def asarray(self, typecode='f'): return array(typecode, self._content()) class _Hist(_HistBase): DIM = 1 def __init__(self, *args, **kwargs): name = kwargs.get('name', None) title = kwargs.get('title', None) params = self._parse_args(*args) if params[0]['bins'] is None: Object.__init__(self, name, title, params[0]['nbins'], params[0]['low'], params[0]['high']) else: Object.__init__(self, name, title, params[0]['nbins'], array('d', params[0]['bins'])) self._post_init(**kwargs) def _post_init(self, **kwargs): _HistBase.__init__(self) self.decorate(**kwargs) def x(self, index=None): return self._centers(1, index) def xerravg(self, index=None): return self._erravg(1, index) def xerrl(self, index=None): return self._erravg(1, index) def xerrh(self, index=None): return self._erravg(1, index) def xerr(self, index=None): return self._err(1, index) def xwidth(self, index=None): return self._width(1, index) def xedgesl(self, index=None): return self._edgesl(1, index) def xedgesh(self, index=None): return self._edgesh(1, index) def xedges(self, index=None): return self._edges(1, index) def yerrh(self, index=None): return self.yerravg(index) def yerrl(self, index=None): return self.yerravg(index) def y(self, index=None): if index is None: return (self.y(i) for i in xrange(self.nbins(1))) index = index % len(self) return self.GetBinContent(index + 1) def yerravg(self, index=None): if index is None: return (self.yerravg(i) for i in xrange(self.nbins(1))) index = index % len(self) return self.GetBinError(index + 1) def yerr(self, index=None): if index is None: return ((self.yerrl(i), self.yerrh(i)) for i in xrange(self.nbins(1))) index = index % len(self) return (self.yerrl(index), self.yerrh(index)) def GetMaximum(self, **kwargs): return self.maximum(**kwargs) def maximum(self, include_error=False): if not include_error: return self.__class__.__bases__[-1].GetMaximum(self) clone = self.Clone() for i in xrange(clone.GetNbinsX()): clone.SetBinContent( i + 1, clone.GetBinContent(i + 1) + clone.GetBinError(i + 1)) return clone.maximum() def GetMinimum(self, **kwargs): return self.minimum(**kwargs) def minimum(self, include_error=False): if not include_error: return self.__class__.__bases__[-1].GetMinimum(self) clone = self.Clone() for i in xrange(clone.GetNbinsX()): clone.SetBinContent( i + 1, clone.GetBinContent(i + 1) - clone.GetBinError(i + 1)) return clone.minimum() def expectation(self, startbin=0, endbin=None): if endbin is not None and endbin < startbin: raise DomainError("endbin should be greated than startbin") if endbin is None: endbin = len(self) - 1 expect = 0. norm = 0. for index in xrange(startbin, endbin + 1): val = self[index] expect += val * self.x(index) norm += val if norm > 0: return expect / norm else: return (self.xedges(endbin + 1) + self.xedges(startbin)) / 2 def _content(self): return self.y() def _error_content(self): return self.yerravg() def __getitem__(self, index): """ if type(index) is slice: return self._content()[index] """ _HistBase.__getitem__(self, index) return self.y(index) def __getslice__(self, i, j): # TODO: getslice is deprecated. getitem should accept slice objects. return list(self)[i:j] def __setitem__(self, index, value): _HistBase.__setitem__(self, index) self.SetBinContent(index + 1, value) class _Hist2D(_HistBase): DIM = 2 def __init__(self, *args, **kwargs): name = kwargs.get('name', None) title = kwargs.get('title', None) params = self._parse_args(*args) if params[0]['bins'] is None and params[1]['bins'] is None: Object.__init__(self, name, title, params[0]['nbins'], params[0]['low'], params[0]['high'], params[1]['nbins'], params[1]['low'], params[1]['high']) elif params[0]['bins'] is None and params[1]['bins'] is not None: Object.__init__(self, name, title, params[0]['nbins'], params[0]['low'], params[0]['high'], params[1]['nbins'], array('d', params[1]['bins'])) elif params[0]['bins'] is not None and params[1]['bins'] is None: Object.__init__(self, name, title, params[0]['nbins'], array('d', params[0]['bins']), params[1]['nbins'], params[1]['low'], params[1]['high']) else: Object.__init__(self, name, title, params[0]['nbins'], array('d', params[0]['bins']), params[1]['nbins'], array('d', params[1]['bins'])) self._post_init(**kwargs) def _post_init(self, **kwargs): _HistBase.__init__(self) self.decorate(**kwargs) def x(self, index=None): return self._centers(1, index) def xerravg(self, index=None): return self._erravg(1, index) def xerrl(self, index=None): return self._erravg(1, index) def xerrh(self, index=None): return self._erravg(1, index) def xerr(self, index=None): return self._err(1, index) def xwidth(self, index=None): return self._width(1, index) def xedgesl(self, index=None): return self._edgesl(1, index) def xedgesh(self, index=None): return self._edgesh(1, index) def xedges(self, index=None): return self._edges(1, index) def y(self, index=None): return self._centers(2, index) def yerravg(self, index=None): return self._erravg(2, index) def yerrl(self, index=None): return self._erravg(2, index) def yerrh(self, index=None): return self._erravg(2, index) def yerr(self, index=None): return self._err(2, index) def ywidth(self, index=None): return self._width(2, index) def yedgesl(self, index=None): return self._edgesl(2, index) def yedgesh(self, index=None): return self._edgesh(2, index) def yedges(self, index=None): return self._edges(2, index) def zerrh(self, index=None): return self.zerravg(index) def zerrl(self, index=None): return self.zerravg(index) def z(self, ix=None, iy=None): if ix is None and iy is None: return [[self.z(ix, iy) for iy in xrange(self.nbins(2))] for ix in xrange(self.nbins(1))] ix = ix % self.nbins(1) iy = iy % self.nbins(2) return self.GetBinContent(ix + 1, iy + 1) def zerravg(self, ix=None, iy=None): if ix is None and iy is None: return [[self.zerravg(ix, iy) for iy in xrange(self.nbins(2))] for ix in xrange(self.nbins(1))] ix = ix % self.nbins(1) iy = iy % self.nbins(2) return self.GetBinError(ix + 1, iy + 1) def zerr(self, ix=None, iy=None): if ix is None and iy is None: return [[(self.zerravg(ix, iy), self.zerravg(ix, iy)) for iy in xrange(self.nbins(2))] for ix in xrange(self.nbins(1))] ix = ix % self.nbins(1) iy = iy % self.nbins(2) return (self.GetBinError(ix + 1, iy + 1), self.GetBinError(ix + 1, iy + 1)) def _content(self): return self.z() def _error_content(self): return self.zerravg() def __getitem__(self, index): if isinstance(index, tuple): # support indexing like h[1,2] return self.z(*index) _HistBase.__getitem__(self, index) a = ObjectProxy([ self.GetBinContent(index + 1, j) for j in xrange(1, self.GetNbinsY() + 1)]) a.__setposthook__('__setitem__', self._setitem(index)) return a def _setitem(self, i): def __setitem(j, value): self.SetBinContent(i + 1, j + 1, value) return __setitem def ravel(self): """ Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel(). """ nbinsx = self.nbins(1) nbinsy = self.nbins(2) out = Hist(self.nbins(1) * nbinsy, self.xedgesl(0), self.xedgesh(-1) * nbinsy, type=self.TYPE, title=self.title, **self.decorators) for i in range(nbinsx): for j in range(nbinsy): out[i + nbinsy * j] = self[i, j] out.SetBinError(i + nbinsy * j + 1, self.GetBinError(i + 1, j + 1)) return out class _Hist3D(_HistBase): DIM = 3 def __init__(self, *args, **kwargs): name = kwargs.get('name', None) title = kwargs.get('title', None) params = self._parse_args(*args) # ROOT is missing constructors for TH3F... if params[0]['bins'] is None and \ params[1]['bins'] is None and \ params[2]['bins'] is None: Object.__init__(self, name, title, params[0]['nbins'], params[0]['low'], params[0]['high'], params[1]['nbins'], params[1]['low'], params[1]['high'], params[2]['nbins'], params[2]['low'], params[2]['high']) else: if params[0]['bins'] is None: step = (params[0]['high'] - params[0]['low'])\ / float(params[0]['nbins']) params[0]['bins'] = [ params[0]['low'] + n * step
[ " for n in xrange(params[0]['nbins'] + 1)]" ]
2,054
lcc
python
null
7ca84608f996fd9789e4cbc658213c13482f990b4ea1c34e
package protocol.xmpp; import android.util.Log;; import protocol.Contact; import protocol.Protocol; import ru.sawim.comm.Util; import ru.sawim.io.RosterStorage; import ru.sawim.listener.OnMoreMessagesLoaded; import ru.sawim.roster.RosterHelper; import java.util.HashSet; import java.util.concurrent.ConcurrentHashMap; /** * Created by gerc on 05.03.2015. */ public class MessageArchiveManagement { private static final long MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; public static final long MAX_CATCHUP = MILLISECONDS_IN_DAY * 7; public static final long MAX_MESSAGES = 20; private final HashSet<Query> queries = new HashSet<>(); private String getQueryMessageArchiveManagement(Contact contact, Query query) { XmlNode xmlNode = new XmlNode(XmlConstants.S_IQ); xmlNode.putAttribute(XmlConstants.S_TYPE, XmlConstants.S_SET); if (contact != null && contact.isConference()) { xmlNode.putAttribute(XmlConstants.S_TO, Util.xmlEscape(contact.getUserId())); } xmlNode.putAttribute(XmlNode.S_ID, XmppConnection.generateId()); XmlNode queryNode = new XmlNode(XmlConstants.S_QUERY); queryNode.putAttribute(XmlNode.S_XMLNS, "urn:xmpp:mam:0"); queryNode.putAttribute("queryid", query.queryId); XmlNode xNode = new XmlNode("x"); xNode.putAttribute(XmlNode.S_XMLNS, "jabber:x:data"); xNode.putAttribute("type", "submit"); XmlNode formTypeNode = new XmlNode("field"); formTypeNode.putAttribute("var", "FORM_TYPE"); formTypeNode.putAttribute("type", "hidden"); formTypeNode.setValue("value", "urn:xmpp:mam:0"); xNode.addNode(formTypeNode); /* if (query.getStart() > 0) { XmlNode startNode = new XmlNode("field"); startNode.putAttribute("var", "start"); startNode.setValue("value", Util.getTimestamp(query.getStart())); xNode.addNode(startNode); } if (query.getEnd() > 0) { XmlNode endNode = new XmlNode("field"); endNode.putAttribute("var", "end"); endNode.setValue("value", Util.getTimestamp(query.getEnd())); xNode.addNode(endNode); }*/ if (query.withJid != null && contact != null && !contact.isConference()) { XmlNode withNode = new XmlNode("field"); withNode.putAttribute("var", "with"); withNode.setValue("value", query.withJid); xNode.addNode(withNode); } XmlNode setNode = XmlNode.addXmlns("set", "http://jabber.org/protocol/rsm"); setNode.setValue("max", String.valueOf(MAX_MESSAGES)); if (query.getPagingOrder() == PagingOrder.REVERSE) { setNode.setValue("before", query.getReference()); } else { setNode.setValue("after", query.getReference()); } queryNode.addNode(setNode); queryNode.addNode(xNode); xmlNode.addNode(queryNode); return xmlNode.toString(); } private void queryMessageArchiveManagement(XmppConnection connection, Query query) { Contact contact = null; if (query.getWith() != null) { contact = connection.getProtocol().getItemByUID(query.getWith()); } connection.putPacketIntoQueue(getQueryMessageArchiveManagement(contact, query)); } public void catchup(XmppConnection connection) { long startCatchup = getLastMessageTransmitted(connection); long endCatchup = connection.getLastSessionEstablished(); if (startCatchup == 0) { return; } else { ConcurrentHashMap<String, Contact> contacts = connection.getProtocol().getContactItems(); for (Contact contact : contacts.values()) { queryReverse(connection, contact, startCatchup); } } final Query query = new Query(connection.getXmpp().getUserId(), null, startCatchup, endCatchup); queries.add(query); queryMessageArchiveManagement(connection, query); } private long getLastMessageTransmitted(XmppConnection connection) { long timestamp = 0; for (Contact contact : connection.getProtocol().getContactItems().values()) { long lastMessageTransmitted = contact.getLastMessageTransmitted(); if (lastMessageTransmitted > timestamp) { timestamp = lastMessageTransmitted; } } return timestamp; } public Query queryReverse(XmppConnection connection, final Contact contact) { return queryReverse(connection, contact, connection.getLastSessionEstablished()); } public Query queryReverse(XmppConnection connection, final Contact contact, long end) { long lastMessageTransmitted = contact.getLastMessageTransmitted(); return queryReverse(connection, contact, lastMessageTransmitted, end); } public Query queryReverse(XmppConnection connection, Contact contact, long start, long end) { synchronized (queries) { if (start > end) { return null; } final Query query = new Query(connection.getXmpp().getUserId(), contact.getUserId(), start, end, PagingOrder.REVERSE); queries.add(query); queryMessageArchiveManagement(connection, query); return query; } } public Query prev(XmppConnection connection, Contact contact) { synchronized (queries) { Query query = new Query(connection.getXmpp().getUserId(), contact.getUserId(), 0, 0) .prev(contact.firstServerMsgId); queries.add(query); queryMessageArchiveManagement(connection, query); return query; } } public void processFin(XmppConnection connection, XmlNode fin) { Query query = findQuery(fin.getAttribute("queryid")); if (query == null) { return; } boolean complete = XmppConnection.isTrue(fin.getAttribute("complete")); XmlNode set = fin.getFirstNode("set", "http://jabber.org/protocol/rsm"); String last = set == null ? null : set.getFirstNodeValue("last"); String first = set == null ? null : set.getFirstNodeValue("first"); String relevant = query.getPagingOrder() == PagingOrder.NORMAL ? last : first; String count = set == null ? null : set.getFirstNodeValue("count"); if (count != null) { query.setAllMessageCount(Integer.valueOf(count)); } if (relevant != null) { Contact contact = null; if (query.getWith() != null) { contact = connection.getProtocol().getItemByUID(query.getWith()); } contact.firstServerMsgId = first; connection.getXmpp().getStorage().updateFirstServerMsgId(contact); } if (complete || relevant == null) { finalizeQuery(connection.getProtocol(), query); Log.d("MAM", "finished mam after " + query.getAllMessagesCount() + " messages"); } else { final Query nextQuery; if (query.getPagingOrder() == PagingOrder.NORMAL) { nextQuery = query.next(last); } else { nextQuery = query.prev(first); } // queryMessageArchiveManagement(connection, nextQuery); finalizeQuery(connection.getProtocol(), query); synchronized (queries) { // queries.add(nextQuery); } } } public boolean queryInProgress(Contact contact, OnMoreMessagesLoaded moreMessagesLoadedListener) { synchronized (queries) { for (Query query : queries) { if (query.getWith().equals(contact.getUserId())) { if (query.onMoreMessagesLoaded == null && moreMessagesLoadedListener != null) { query.setOnMoreMessagesLoaded(moreMessagesLoadedListener); } return true; } } return false; } } private void finalizeQuery(Protocol protocol, Query query) { synchronized (queries) { queries.remove(query); } Contact contact = null; if (query.getWith() != null) { contact = protocol.getItemByUID(query.getWith()); } if (contact != null) {
[ " if (contact.setLastMessageTransmitted(query.getEnd())) {" ]
630
lcc
java
null
e745ca2cc98ac1c0224978f820c9902c973ae8afb16c93ec
""" piecewise affine equalization ipol demo web app """ from lib import base_app, build, http, image from lib.misc import ctime from lib.base_app import init_app import shutil import cherrypy from cherrypy import TimeoutError import os.path import time import PIL.Image import PIL.ImageDraw class app(base_app): """ piecewise affine equalization app """ title = "Color and Contrast Enhancement by Controlled Piecewise Affine Histogram Equalization" xlink_article = 'http://www.ipol.im/pub/art/2012/lps-pae/' input_nb = 1 input_max_pixels = 700 * 700 # max size (in pixels) of an input image input_max_weight = 10 * 1024 * 1024 # max size (in bytes) of an input file input_dtype = '3x8i' # input image expected data type input_ext = '.png' # input image expected extension (ie file format) is_test = False def __init__(self): """ app setup """ # setup the parent class base_dir = os.path.dirname(os.path.abspath(__file__)) base_app.__init__(self, base_dir) # select the base_app steps to expose # index() and input_xxx() are generic base_app.index.im_func.exposed = True base_app.input_select.im_func.exposed = True base_app.input_upload.im_func.exposed = True # params() is modified from the template base_app.params.im_func.exposed = True # result() is modified from the template base_app.result.im_func.exposed = True def build(self): """ program build/update """ # store common file path in variables tgz_url = "http://www.ipol.im/pub/art/2012/lps-pae/piecewise_eq.tgz" tgz_file = self.dl_dir + "piecewise_eq.tgz" progs = ["piecewise_equalization"] src_bin = dict([(self.src_dir + os.path.join("piecewise_eq", prog), self.bin_dir + prog) for prog in progs]) log_file = self.base_dir + "build.log" # get the latest source archive build.download(tgz_url, tgz_file) # test if any dest file is missing, or too old if all([(os.path.isfile(bin_file) and ctime(tgz_file) < ctime(bin_file)) for bin_file in src_bin.values()]): cherrypy.log("not rebuild needed", context='BUILD', traceback=False) else: # extract the archive build.extract(tgz_file, self.src_dir) # build the programs build.run("make -j4 -C %s %s" % (self.src_dir + "piecewise_eq", " ".join(progs)), stdout=log_file) # save into bin dir if os.path.isdir(self.bin_dir): shutil.rmtree(self.bin_dir) os.mkdir(self.bin_dir) for (src, dst) in src_bin.items(): #print "copy %s to %s" % (src, dst) shutil.copy(src, dst) # cleanup the source dir shutil.rmtree(self.src_dir) return # # PARAMETER HANDLING # @cherrypy.expose @init_app def params(self, newrun=False, msg=None, s1="0", s2="3.0"): """ configure the algo execution """ if newrun: self.clone_input() return self.tmpl_out("params.html", msg=msg, s1=s1, s2=s2) @cherrypy.expose @init_app def wait(self, s1="0", s2="3.0"): """ params handling and run redirection """ # save the parameters try: self.cfg['param'] = {'s1' : float(s1), 's2' : float(s2)} self.cfg.save() except ValueError: return self.error(errcode='badparams', errmsg="The parameters must be numeric.") http.refresh(self.base_url + 'run?key=%s' % self.key) return self.tmpl_out("wait.html") @cherrypy.expose @init_app def run(self): """ algorithm execution """ # read the parameters s1 = self.cfg['param']['s1'] s2 = self.cfg['param']['s2'] # run the algorithm stdout = open(self.work_dir + 'stdout.txt', 'w') try: run_time = time.time() self.run_algo(s1, s2, stdout=stdout, timeout=self.timeout) self.cfg['info']['run_time'] = time.time() - run_time self.cfg.save() except TimeoutError: return self.error(errcode='timeout') except RuntimeError: return self.error(errcode='runtime') http.redir_303(self.base_url + 'result?key=%s' % self.key) # archive if self.cfg['meta']['original']: ar = self.make_archive() ar.add_file("input_0.orig.png", info="uploaded image") ar.add_file("input_0.png", info="original image") ar.add_file("output_1_N2.png", info="result image 1 N=2 (RGB)") ar.add_file("output_2_N2.png", info="result image 2 N=2 (I)") ar.add_file("output_1_N3.png", info="result image 1 N=3 (RGB)") ar.add_file("output_2_N3.png", info="result image 2 N=3 (I)") ar.add_file("output_1_N4.png", info="result image 1 N=4 (RGB)") ar.add_file("output_2_N4.png", info="result image 2 N=4 (I)") ar.add_file("output_1_N5.png", info="result image 1 N=5 (RGB)") ar.add_file("output_2_N4.png", info="result image 2 N=5 (I)") ar.add_file("output_1_N10.png", info="result image 1 N=10 (RGB)") ar.add_file("output_2_N10.png", info="result image 2 N=10 (I)") ar.add_file("output_1_HE.png", info="result image 1 HE (RGB)") ar.add_file("output_2_HE.png", info="result image 2 HE (I)") ar.add_info({"smin": s1}) ar.add_info({"smax": s2}) ar.save() return self.tmpl_out("run.html") def drawtransformImages(self, imname0, imname1, channel, scale, fname=None): """ Compute transform that converts values of image 0 to values of image 1, for the specified channel Images must be of the same size """ #load images im0 = PIL.Image.open(imname0) im1 = PIL.Image.open(imname1) #check image size if im0.size != im1.size: raise ValueError("Images must be of the same size") # check image mode if im0.mode not in ("L", "RGB"): raise ValueError("Unsuported image mode for histogram equalization") if im1.mode not in ("L", "RGB"): raise ValueError("Unsuported image mode for histogram equalization") #load image values rgb2I = (0.333333, 0.333333, 0.333333, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) rgb2r = (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) rgb2g = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) rgb2b = (0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) if im0.mode == "RGB": if channel == "I": # compute gray level image: I = (R + G + B) / 3 im0L = im0.convert("L", rgb2I) elif channel == "R": im0L = im0.convert("L", rgb2r) elif channel == "G": im0L = im0.convert("L", rgb2g) else: im0L = im0.convert("L", rgb2b) h0 = im0L.histogram() else: #im0.mode == "L": h0 = im0.histogram() if im1.mode == "RGB": if channel == "I": # compute gray level image: I = (R + G + B) / 3
[ " im1L = im1.convert(\"L\", rgb2I)" ]
756
lcc
python
null
0c4383dd82b695a9c0f842643d57d89b5f9deac30eb27285
/* NFC Reader is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFC Reader is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package cache.wind.nfc.nfc.reader.pboc; import android.nfc.tech.IsoDep; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import cache.wind.nfc.SPEC; import cache.wind.nfc.nfc.Util; import cache.wind.nfc.nfc.bean.Application; import cache.wind.nfc.nfc.bean.Card; import cache.wind.nfc.nfc.tech.Iso7816; @SuppressWarnings("unchecked") public abstract class StandardPboc { private static Class<?>[][] readers = { { BeijingMunicipal.class, WuhanTong.class, CityUnion.class, TUnion.class, ShenzhenTong.class, }, { StandardECash.class, } }; public static void readCard(IsoDep tech, Card card) throws InstantiationException, IllegalAccessException, IOException { final Iso7816.StdTag tag = new Iso7816.StdTag(tech); tag.connect(); for (final Class<?> g[] : readers) { HINT hint = HINT.RESETANDGONEXT; for (final Class<?> r : g) { final StandardPboc reader = (StandardPboc) r.newInstance(); switch (hint) { case RESETANDGONEXT: if (!reader.resetTag(tag)) continue; case GONEXT: hint = reader.readCard(tag, card); break; default: break; } if (hint == HINT.STOP) break; } } tag.close(); } protected boolean resetTag(Iso7816.StdTag tag) throws IOException { return tag.selectByID(DFI_MF).isOkey() || tag.selectByName(DFN_PSE).isOkey(); } protected enum HINT { STOP, GONEXT, RESETANDGONEXT, } protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 }; protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 }; protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] DFN_PXX = { (byte) 'P' }; protected final static int SFI_EXTRA = 21; protected static int MAX_LOG = 10; protected static int SFI_LOG = 24; protected final static byte TRANS_CSU = 6; protected final static byte TRANS_CSU_CPX = 9; protected abstract Object getApplicationId(); protected byte[] getMainApplicationId() { return DFI_EP; } protected SPEC.CUR getCurrency() { return SPEC.CUR.CNY; } protected boolean selectMainApplication(Iso7816.StdTag tag) throws IOException { final byte[] aid = getMainApplicationId(); return ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid)).isOkey(); } protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!selectMainApplication(tag)) return HINT.GONEXT; Iso7816.Response INFO, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ BALANCE = tag.getBalance(0, true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo21(app, INFO, 4, true); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } protected float parseBalance(Iso7816.Response data) { float ret = 0f; if (data.isOkey() && data.size() >= 4) { int n = Util.toInt(data.getBytes(), 0, 4); if (n > 1000000 || n < -1000000) n -= 0x80000000; ret = n / 100.0f; } return ret; } protected void parseBalance(Application app, Iso7816.Response... data) { float amount = 0f; for (Iso7816.Response rsp : data) amount += parseBalance(rsp); app.setProperty(SPEC.PROP.BALANCE, amount); } protected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { return; } final byte[] d = data.getBytes(); if (dec < 1 || dec > 10) { app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10)); } else { final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d, 20 - dec, dec); app.setProperty(SPEC.PROP.SERIAL, String.format("%d", 0xFFFFFFFFL & sn)); } if (d[9] != 0) app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9])); app.setProperty(SPEC.PROP.DATE, String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27])); } protected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) { if (!r.isOkey()) return false; final byte[] raw = r.getBytes(); final int N = raw.length - 23; if (N < 0) return false; for (int s = 0, e = 0; s <= N; s = e) { l.add(Arrays.copyOfRange(raw, s, (e = s + 23))); } return true; } protected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi) throws IOException { final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG); final Iso7816.Response rsp = tag.readRecord(sfi); if (rsp.isOkey()) { addLog24(rsp, ret); } else {
[ "\t\t\tfor (int i = 1; i <= MAX_LOG; ++i) {" ]
702
lcc
java
null
22e513a622143cc52cb34624fc06151012a9995c967df13c
""" ACE parser From wotsit.org and the SDK header (bitflags) Partial study of a new block type (5) I've called "new_recovery", as its syntax is very close to the former one (of type 2). Status: can only read totally file and header blocks. Author: Christophe Gisquet <christophe.gisquet@free.fr> Creation date: 19 january 2006 """ from hachoir_py2.parser import Parser from hachoir_py2.field import (StaticFieldSet, FieldSet, Bit, Bits, NullBits, RawBytes, Enum, UInt8, UInt16, UInt32, PascalString8, PascalString16, String, TimeDateMSDOS32) from hachoir_py2.core.text_handler import textHandler, filesizeHandler, hexadecimal from hachoir_py2.core.endian import LITTLE_ENDIAN from hachoir_py2.parser.common.msdos import MSDOSFileAttr32 MAGIC = "**ACE**" OS_MSDOS = 0 OS_WIN32 = 2 HOST_OS = { 0: "MS-DOS", 1: "OS/2", 2: "Win32", 3: "Unix", 4: "MAC-OS", 5: "Win NT", 6: "Primos", 7: "APPLE GS", 8: "ATARI", 9: "VAX VMS", 10: "AMIGA", 11: "NEXT", } COMPRESSION_TYPE = { 0: "Store", 1: "Lempel-Ziv 77", 2: "ACE v2.0", } COMPRESSION_MODE = { 0: "fastest", 1: "fast", 2: "normal", 3: "good", 4: "best", } # TODO: Computing the CRC16 would also prove useful # def markerValidate(self): # return not self["extend"].value and self["signature"].value == MAGIC and \ # self["host_os"].value<12 class MarkerFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (Bit, "has_comment", "Whether the archive has a comment"), (NullBits, "unused", 7, "Reserved bits"), (Bit, "sfx", "SFX"), (Bit, "limited_dict", "Junior SFX with 256K dictionary"), (Bit, "multi_volume", "Part of a set of ACE archives"), (Bit, "has_av_string", "This header holds an AV-string"), (Bit, "recovery_record", "Recovery record preset"), (Bit, "locked", "Archive is locked"), (Bit, "solid", "Archive uses solid compression") ) def markerFlags(self): yield MarkerFlags(self, "flags", "Marker flags") def markerHeader(self): yield String(self, "signature", 7, "Signature") yield UInt8(self, "ver_extract", "Version needed to extract archive") yield UInt8(self, "ver_created", "Version used to create archive") yield Enum(UInt8(self, "host_os", "OS where the files were compressed"), HOST_OS) yield UInt8(self, "vol_num", "Volume number") yield TimeDateMSDOS32(self, "time", "Date and time (MS DOS format)") yield Bits(self, "reserved", 64, "Reserved size for future extensions") flags = self["flags"] if flags["has_av_string"].value: yield PascalString8(self, "av_string", "AV String") if flags["has_comment"].value: size = filesizeHandler(UInt16(self, "comment_size", "Comment size")) yield size if size.value > 0: yield RawBytes(self, "compressed_comment", size.value, \ "Compressed comment") class FileFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (Bit, "has_comment", "Presence of file comment"), (Bits, "unused", 10, "Unused bit flags"), (Bit, "encrypted", "File encrypted with password"), (Bit, "previous", "File continued from previous volume"), (Bit, "next", "File continues on the next volume"), (Bit, "solid", "File compressed using previously archived files") ) def fileFlags(self): yield FileFlags(self, "flags", "File flags") def fileHeader(self): yield filesizeHandler(UInt32(self, "compressed_size", "Size of the compressed file")) yield filesizeHandler(UInt32(self, "uncompressed_size", "Uncompressed file size")) yield TimeDateMSDOS32(self, "ftime", "Date and time (MS DOS format)") if self["/header/host_os"].value in (OS_MSDOS, OS_WIN32): yield MSDOSFileAttr32(self, "file_attr", "File attributes") else: yield textHandler(UInt32(self, "file_attr", "File attributes"), hexadecimal) yield textHandler(UInt32(self, "file_crc32", "CRC32 checksum over the compressed file)"), hexadecimal) yield Enum(UInt8(self, "compression_type", "Type of compression"), COMPRESSION_TYPE) yield Enum(UInt8(self, "compression_mode", "Quality of compression"), COMPRESSION_MODE) yield textHandler(UInt16(self, "parameters", "Compression parameters"), hexadecimal) yield textHandler(UInt16(self, "reserved", "Reserved data"), hexadecimal) # Filename yield PascalString16(self, "filename", "Filename") # Comment if self["flags/has_comment"].value: yield filesizeHandler(UInt16(self, "comment_size", "Size of the compressed comment")) if self["comment_size"].value > 0: yield RawBytes(self, "comment_data", self["comment_size"].value, "Comment data") def fileBody(self): size = self["compressed_size"].value if size > 0: yield RawBytes(self, "compressed_data", size, "Compressed data") def fileDesc(self): return "File entry: %s (%s)" % (self["filename"].value, self["compressed_size"].display) def recoveryHeader(self): yield filesizeHandler(UInt32(self, "rec_blk_size", "Size of recovery data")) self.body_size = self["rec_blk_size"].size yield String(self, "signature", 7, "Signature, normally '**ACE**'") yield textHandler(UInt32(self, "relative_start", "Relative start (to this block) of the data this block is mode of"), hexadecimal) yield UInt32(self, "num_blocks", "Number of blocks the data is split into") yield UInt32(self, "size_blocks", "Size of these blocks") yield UInt16(self, "crc16_blocks", "CRC16 over recovery data") # size_blocks blocks of size size_blocks follow # The ultimate data is the xor data of all those blocks size = self["size_blocks"].value for index in xrange(self["num_blocks"].value): yield RawBytes(self, "data[]", size, "Recovery block %i" % index) yield RawBytes(self, "xor_data", size, "The XOR value of the above data blocks") def recoveryDesc(self): return "Recovery block, size=%u" % self["body_size"].display def newRecoveryHeader(self): """ This header is described nowhere """ if self["flags/extend"].value: yield filesizeHandler(UInt32(self, "body_size", "Size of the unknown body following")) self.body_size = self["body_size"].value yield textHandler(UInt32(self, "unknown[]", "Unknown field, probably 0"), hexadecimal) yield String(self, "signature", 7, "Signature, normally '**ACE**'") yield textHandler(UInt32(self, "relative_start", "Offset (=crc16's) of this block in the file"), hexadecimal) yield textHandler(UInt32(self, "unknown[]", "Unknown field, probably 0"), hexadecimal) class BaseFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (NullBits, "unused", 15, "Unused bit flags") ) def parseFlags(self): yield BaseFlags(self, "flags", "Unknown flags") def parseHeader(self): if self["flags/extend"].value: yield filesizeHandler(UInt32(self, "body_size", "Size of the unknown body following")) self.body_size = self["body_size"].value def parseBody(self): if self.body_size > 0: yield RawBytes(self, "body_data", self.body_size, "Body data, unhandled") class Block(FieldSet): TAG_INFO = { 0: ("header", "Archiver header", markerFlags, markerHeader, None), 1: ("file[]", fileDesc, fileFlags, fileHeader, fileBody), 2: ("recovery[]", recoveryDesc, recoveryHeader, None, None), 5: ("new_recovery[]", None, None, newRecoveryHeader, None) } def __init__(self, parent, name, description=None): FieldSet.__init__(self, parent, name, description) self.body_size = 0 self.desc_func = None type = self["block_type"].value if type in self.TAG_INFO: self._name, desc, self.parseFlags, self.parseHeader, self.parseBody = self.TAG_INFO[type] if desc: if isinstance(desc, str): self._description = desc else: self.desc_func = desc else: self.warning("Processing as unknown block block of type %u" % type) if not self.parseFlags: self.parseFlags = parseFlags if not self.parseHeader: self.parseHeader = parseHeader if not self.parseBody: self.parseBody = parseBody def createFields(self): yield textHandler(UInt16(self, "crc16", "Archive CRC16 (from byte 4 on)"), hexadecimal) yield filesizeHandler(UInt16(self, "head_size", "Block size (from byte 4 on)")) yield UInt8(self, "block_type", "Block type") # Flags for flag in self.parseFlags(self): yield flag # Rest of the header for field in self.parseHeader(self): yield field size = self["head_size"].value - (self.current_size // 8) + (2 + 2) if size > 0: yield RawBytes(self, "extra_data", size, "Extra header data, unhandled") # Body in itself for field in self.parseBody(self): yield field def createDescription(self): if self.desc_func: return self.desc_func(self) else:
[ " return \"Block: %s\" % self[\"type\"].display" ]
952
lcc
python
null
5772539578239747ccdb82c5a9bc47b7df833cf9c67b1225
/** * <pre> * The owner of the original code is Ciena Corporation. * * Portions created by the original owner are Copyright (C) 2004-2010 * the original owner. All Rights Reserved. * * Portions created by other contributors are Copyright (C) the contributor. * All Rights Reserved. * * Contributor(s): * (Contributors insert name & email here) * * This file is part of DRAC (Dynamic Resource Allocation Controller). * * DRAC is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * DRAC is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * </pre> */ package com.nortel.appcore.app.drac.server.neproxy.mediation.tl1client.protocol.tl1; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nortel.appcore.app.drac.server.neproxy.mediation.tl1client.TL1LanguageEngine; import com.nortel.appcore.app.drac.server.neproxy.mediation.tl1client.comms.ConnectionDropListener; import com.nortel.appcore.app.drac.server.neproxy.mediation.tl1client.comms.SocketAdapter; /** * This is the external interface to the TL1 engine that sends and parses * messages to /from the NE. This class should provide all that is required to * an external "customer" of the engine. Forcing the use of this interface hides * the underlying implementation from the user. * <p> * NOte that the connected property ( JavaBeans ) is bound, which means that it * will fire a property change evevnt when it changes state. */ public class TL1LanguageEngineImpl implements TL1LanguageEngine, ConnectionDropListener// , CommAdapterByteListener { private final Logger log = LoggerFactory.getLogger(getClass()); /** flag indicating if we are connected */ private boolean connected; /** the proxy for property changes */ private PropertyChangeSupport support; /** the actual engine */ private TL1Engine engine; /** the socket adapter */ private SocketAdapter socketAdapter; /** * new INSTANCE */ TL1LanguageEngineImpl() { connected = false; support = new PropertyChangeSupport(this); } /** * Add a listener for autonomous messages. You will only be notified of the * autonoumous code, and tids that match the args you pass into this method. * * @param code * the autonomous code you are interested in. * @param tid * the tid of the NE that is the source of these auto messages * @param listener * the listener who is notified of auto messages */ @Override public void addAutonomousListener(String code, String tid, ReportListener listener) { if (engine != null) { engine.register(code, tid, listener); } else { log.error("Engine not connected"); } } /** * This listener will be notified of all autonomous events that originate from * the specified TID. <b> Use this sparingly. Having many of these listeners * will impact performance. */ @Override public void addAutonomousListenerForAll(String tid, ReportListener listener) { engine.registerForAll(tid, listener); } /** * Add a property change listener to the engine. This is how listeners can * listen for changes such as the connection state changing. For INSTANCE your * code might look like: * <P> * connectedListener = new PropertyChangeListener() { public void * propertyChange( PropertyChangeEvent e) { // we have only listened for 1 * property, so // we assume it is the connected property Boolean conected = * (Boolean)e.getNewValue(); handleConnected( connected.booleanValue() ); } }; * myTL1LanguageEngine.addPropertyChangeListener ( * TL1LanguageEngine.CONNECTED, connectedListener ); * * @param property * the property the user is interested in listening to changes in. * @param listener * the listener to notify of the changes */ @Override public void addPropertyChangeListener(String property, PropertyChangeListener listener) { support.addPropertyChangeListener(property, listener); } @Override public void closeUnderlyingSocket() { if (socketAdapter != null) { socketAdapter.close(); } } /** * try to connect to the ip and port number. note that there can only ever be * a single connection at a given time. If there is a problem connecting then * an IOException is thrown. */ @Override public void connect(String ip, int port) throws IOException { // tidy cleanEngine(); socketAdapter = new SocketAdapter(ip, port); socketAdapter.connect(0); // we're connected, create a new log. Turn it off. // createLog( ip, port ); // socketAdapter.addCommAdapterByteListener(this); socketAdapter.setConnectionDropListener(this); engine = new TL1Engine(socketAdapter); setConnected(true); } /** * implement the interface that notified us of conenctions going away. */ @Override public void connectionDropped() { // // Vu swapped these two statement to remove the bug that // CONNECTION_FAILED is not notified // /// since the listerner was removed before then. setConnected(false); cleanEngine(); } /** * Create a commlog for this connecttion */ /* * private void createLog(String ip, int port) { if ( log != null ) * log.dispose(); String IP = ip.replace('.', '-'); String file = IP + "-" + * port + ".log"; // log = new CommLog( file ); log = new Log(); } */ /** * destroy this INSTANCE */ @Override public void dispose() { setConnected(false); cleanEngine(); support = null; } /** * getMessageQueueSize method comment. */ @Override public int getMessageQueueSize() { if (engine != null) { return engine.getMessageQueueSize(); } return 0; } /** * getResponseQueueSize method comment. */ @Override public int getResponseQueueSize() { return engine.getResponseQueueSize(); } /** * This flag returns true when the engine is connected to the gateway. It does * not neccessarily imply association, since the engine knows nothing about * login state or anything else. */ @Override public boolean isConnected() { return connected; } // /** // * listen for data from the comm adapter // */ // // public void received(byte[] data, int available) // { // // // } /** * remove the listener for autonomous messages. users must remove listener to * avoid memory leaks * * @param code * the autonomous code you are interested in. * @param tid * the tid of the NE that is the source of these auto messages * @param listener * the listener who is notified of auto messages */ @Override public void removeAutonomousListener(String code, String tid, ReportListener listener) { if (engine != null) { engine.deregister(code, tid, listener); } } /** * This listener will be notified of all autonomous events that originate from * the specified TID. */ @Override public void removeAutonomousListenerForAll(String tid, ReportListener listener) { engine.deregisterForAll(tid, listener); } /** * Good users of this class will remove the property change listener to avoid * memory leaks. * * @param property * the property listening for * @param listener * the listener */ @Override public void removePropertyChangeListener(String property, PropertyChangeListener listener) { support.removePropertyChangeListener(property, listener); } /** * Send the command to the underlying engine. * * @param command * to send to the remote engine. */ @Override public void send(AbstractCommand command) { if (engine != null) { command.send(engine); } } // public void setThreadPriority(int priority) // { // if (engine != null) // { // engine.setThreadPriority(priority); // } // // if (socketAdapter != null) // { // socketAdapter.setReadThreadPriority(priority); // } // } /** * Set the connected boolean and fire off a change event */ void setConnected(boolean newValue) { if (connected == newValue) { return; } boolean old = connected; connected = newValue; support.firePropertyChange(CONNECTED, old, connected); } /** * clean up the engine */ private void cleanEngine() { if (engine != null) { engine.dispose(); } engine = null;
[ "\t\tif (socketAdapter != null) {" ]
1,211
lcc
java
null
8eee41f139373f09ef454c2f6997710fa102d97316c455fe
"""This class holds Cheroot WSGI server implementation. Simplest example on how to use this server:: from cheroot import wsgi def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return [b'Hello world!'] addr = '0.0.0.0', 8070 server = wsgi.Server(addr, my_crazy_app) server.start() The Cheroot WSGI server can serve as many WSGI applications as you want in one instance by using a PathInfoDispatcher:: path_map = { '/': my_crazy_app, '/blog': my_blog_app, } d = wsgi.PathInfoDispatcher(path_map) server = wsgi.Server(addr, d) """ from __future__ import absolute_import, division, print_function __metaclass__ = type import sys import six from six.moves import filter from . import server from .workers import threadpool from ._compat import ntob, bton class Server(server.HTTPServer): """A subclass of HTTPServer which calls a WSGI application.""" wsgi_version = (1, 0) """The version of WSGI to produce.""" def __init__( self, bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5, accepted_queue_size=-1, accepted_queue_timeout=10, peercreds_enabled=False, peercreds_resolve_enabled=False, ): """Initialize WSGI Server instance. Args: bind_addr (tuple): network interface to listen to wsgi_app (callable): WSGI application callable numthreads (int): number of threads for WSGI thread pool server_name (str): web server name to be advertised via Server HTTP header max (int): maximum number of worker threads request_queue_size (int): the 'backlog' arg to socket.listen(); max queued connections timeout (int): the timeout in seconds for accepted connections shutdown_timeout (int): the total time, in seconds, to wait for worker threads to cleanly exit accepted_queue_size (int): maximum number of active requests in queue accepted_queue_timeout (int): timeout for putting request into queue """ super(Server, self).__init__( bind_addr, gateway=wsgi_gateways[self.wsgi_version], server_name=server_name, peercreds_enabled=peercreds_enabled, peercreds_resolve_enabled=peercreds_resolve_enabled, ) self.wsgi_app = wsgi_app self.request_queue_size = request_queue_size self.timeout = timeout self.shutdown_timeout = shutdown_timeout self.requests = threadpool.ThreadPool( self, min=numthreads or 1, max=max, accepted_queue_size=accepted_queue_size, accepted_queue_timeout=accepted_queue_timeout, ) @property def numthreads(self): """Set minimum number of threads.""" return self.requests.min @numthreads.setter def numthreads(self, value): self.requests.min = value class Gateway(server.Gateway): """A base class to interface HTTPServer with WSGI.""" def __init__(self, req): """Initialize WSGI Gateway instance with request. Args: req (HTTPRequest): current HTTP request """ super(Gateway, self).__init__(req) self.started_response = False self.env = self.get_environ() self.remaining_bytes_out = None @classmethod def gateway_map(cls): """Create a mapping of gateways and their versions. Returns: dict[tuple[int,int],class]: map of gateway version and corresponding class """ return {gw.version: gw for gw in cls.__subclasses__()} def get_environ(self): """Return a new environ dict targeting the given wsgi.version.""" raise NotImplementedError # pragma: no cover def respond(self): """Process the current request. From :pep:`333`: The start_response callable must not actually transmit the response headers. Instead, it must store them for the server or gateway to transmit only after the first iteration of the application return value that yields a NON-EMPTY string, or upon the application's first invocation of the write() callable. """ response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in filter(None, response): if not isinstance(chunk, six.binary_type): raise ValueError('WSGI Applications must yield bytes') self.write(chunk) finally: # Send headers if not already sent self.req.ensure_headers_sent() if hasattr(response, 'close'): response.close() def start_response(self, status, headers, exc_info=None): """WSGI callable to begin the HTTP response.""" # "The application may call start_response more than once, # if and only if the exc_info argument is provided." if self.started_response and not exc_info: raise RuntimeError( 'WSGI start_response called a second ' 'time with no exc_info.', ) self.started_response = True # "if exc_info is provided, and the HTTP headers have already been # sent, start_response must raise an error, and should raise the # exc_info tuple." if self.req.sent_headers: try: six.reraise(*exc_info) finally: exc_info = None self.req.status = self._encode_status(status) for k, v in headers: if not isinstance(k, str): raise TypeError( 'WSGI response header key %r is not of type str.' % k, ) if not isinstance(v, str): raise TypeError( 'WSGI response header value %r is not of type str.' % v, ) if k.lower() == 'content-length': self.remaining_bytes_out = int(v) out_header = ntob(k), ntob(v) self.req.outheaders.append(out_header) return self.write @staticmethod def _encode_status(status): """Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as Unicode; that is, they must be of type "str" but are restricted to code points in the "Latin-1" set. """ if six.PY2: return status if not isinstance(status, str): raise TypeError('WSGI response status is not of type str.') return status.encode('ISO-8859-1') def write(self, chunk): """WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application). """ if not self.started_response: raise RuntimeError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if rbo is not None and chunklen > rbo: if not self.req.sent_headers: # Whew. We can send a 500 to the client. self.req.simple_response( '500 Internal Server Error', 'The requested resource returned more bytes than the ' 'declared Content-Length.', ) else: # Dang. We have probably already sent data. Truncate the chunk # to fit (so the client doesn't hang) and raise an error later. chunk = chunk[:rbo] self.req.ensure_headers_sent() self.req.write(chunk) if rbo is not None: rbo -= chunklen if rbo < 0: raise ValueError( 'Response body exceeds the declared Content-Length.', ) class Gateway_10(Gateway): """A Gateway class to interface HTTPServer with WSGI 1.0.x.""" version = 1, 0 def get_environ(self): """Return a new environ dict targeting the given wsgi.version.""" req = self.req req_conn = req.conn env = { # set a non-standard environ entry so the WSGI app can know what # the *real* server protocol is (and what features to support). # See http://www.faqs.org/rfcs/rfc2145.html. 'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': bton(req.path), 'QUERY_STRING': bton(req.qs), 'REMOTE_ADDR': req_conn.remote_addr or '', 'REMOTE_PORT': str(req_conn.remote_port or ''), 'REQUEST_METHOD': bton(req.method), 'REQUEST_URI': bton(req.uri), 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.server_name, # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol. 'SERVER_PROTOCOL': bton(req.request_protocol), 'SERVER_SOFTWARE': req.server.software, 'wsgi.errors': sys.stderr, 'wsgi.input': req.rfile, 'wsgi.input_terminated': bool(req.chunked_read), 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': bton(req.scheme), 'wsgi.version': self.version, } if isinstance(req.server.bind_addr, six.string_types): # AF_UNIX. This isn't really allowed by WSGI, which doesn't # address unix domain sockets. But it's better than nothing. env['SERVER_PORT'] = '' try: env['X_REMOTE_PID'] = str(req_conn.peer_pid) env['X_REMOTE_UID'] = str(req_conn.peer_uid) env['X_REMOTE_GID'] = str(req_conn.peer_gid) env['X_REMOTE_USER'] = str(req_conn.peer_user) env['X_REMOTE_GROUP'] = str(req_conn.peer_group) env['REMOTE_USER'] = env['X_REMOTE_USER'] except RuntimeError: """Unable to retrieve peer creds data. Unsupported by current kernel or socket error happened, or unsupported socket type, or disabled. """ else: env['SERVER_PORT'] = str(req.server.bind_addr[1]) # Request headers env.update( ( 'HTTP_{header_name!s}'. format(header_name=bton(k).upper().replace('-', '_')), bton(v), ) for k, v in req.inheaders.items() ) # CONTENT_TYPE/CONTENT_LENGTH ct = env.pop('HTTP_CONTENT_TYPE', None) if ct is not None: env['CONTENT_TYPE'] = ct cl = env.pop('HTTP_CONTENT_LENGTH', None) if cl is not None: env['CONTENT_LENGTH'] = cl if req.conn.ssl_env: env.update(req.conn.ssl_env) return env class Gateway_u0(Gateway_10): """A Gateway class to interface HTTPServer with WSGI u.0. WSGI u.0 is an experimental protocol, which uses Unicode for keys and values in both Python 2 and Python 3. """ version = 'u', 0 def get_environ(self): """Return a new environ dict targeting the given wsgi.version.""" req = self.req env_10 = super(Gateway_u0, self).get_environ() env = dict(map(self._decode_key, env_10.items())) # Request-URI enc = env.setdefault(six.u('wsgi.url_encoding'), six.u('utf-8')) try: env['PATH_INFO'] = req.path.decode(enc) env['QUERY_STRING'] = req.qs.decode(enc) except UnicodeDecodeError: # Fall back to latin 1 so apps can transcode if needed. env['wsgi.url_encoding'] = 'ISO-8859-1' env['PATH_INFO'] = env_10['PATH_INFO'] env['QUERY_STRING'] = env_10['QUERY_STRING'] env.update(map(self._decode_value, env.items())) return env @staticmethod def _decode_key(item): k, v = item if six.PY2: k = k.decode('ISO-8859-1') return k, v @staticmethod def _decode_value(item): k, v = item skip_keys = 'REQUEST_URI', 'wsgi.input' if not six.PY2 or not isinstance(v, bytes) or k in skip_keys: return k, v return k, v.decode('ISO-8859-1') wsgi_gateways = Gateway.gateway_map() class PathInfoDispatcher: """A WSGI dispatcher for dispatch based on the PATH_INFO.""" def __init__(self, apps): """Initialize path info WSGI app dispatcher. Args: apps (dict[str,object]|list[tuple[str,object]]): URI prefix and WSGI app pairs """ try: apps = list(apps.items()) except AttributeError: pass # Sort the apps by len(path), descending def by_path_len(app): return len(app[0]) apps.sort(key=by_path_len, reverse=True) # The path_prefix strings must start, but not end, with a slash. # Use "" instead of "/". self.apps = [(p.rstrip('/'), a) for p, a in apps] def __call__(self, environ, start_response): """Process incoming WSGI request. Ref: :pep:`3333` Args: environ (Mapping): a dict containing WSGI environment variables start_response (callable): function, which sets response status and headers Returns: list[bytes]: iterable containing bytes to be returned in HTTP response body """
[ " path = environ['PATH_INFO'] or '/'" ]
1,313
lcc
python
null
c4b5d72178219c00e3466b9a8a3483f56036128b3ffe4348
import sys from copy import deepcopy as copy from utils import * from data import Data from math import log from bitarray import bitarray class Model : def __init__( self , dataobj = None , modelfile = None ) : if dataobj : self.data = dataobj self.initialize() if modelfile : self.loadmodel( modelfile ) def initialize( self ) : self.entropyvalues = dict( [ ( field , {} ) for field in self.data.fields ] ) self.sizevalues = dict( [ ( field , {} ) for field in self.data.fields ] ) self.bicvalues = dict( [ ( field , {} ) for field in self.data.fields ] ) self.bestparents = dict( [ ( field , [] ) for field in self.data.fields ] ) self.bitsets = dict( [ ( field , {} ) for field in self.data.fields ] ) self.precalculate_scores() def precalculate_scores( self ) : score_file = "%s/%s%s" % ( os.path.dirname( self.data.source ) , os.path.splitext( os.path.basename( self.data.source ) )[ 0 ] , '_scores.txt' ) if os.path.isfile( score_file ) : print "Reading from %s all scores" % score_file with open( score_file , 'r' ) as f : for line in f : field , par , sc = line.split() if par == '_' : par = '' self.bicvalues[ field ][ par ] = float( sc ) sp = par.split( ',' ) if sp[ 0 ] == '' : sp = [] self.bestparents[ field ].append( sp ) self.create_bitsets() else : print "Pre-calculating all scores from model" self.data.calculatecounters() ''' MDL_SCORE ''' MAX_NUM_PARENTS = int( log( 2 * len( self.data.rows ) / log( len( self.data.rows ) ) ) ) ''' BIC SCORE ''' #MAX_NUM_PARENTS = int( log( len( self.data.rows ) ) ) files = [] for field in self.data.fields : print "Calculating scores for field %s" % field field_file = "%s/%s_%s_%s" % ( os.path.dirname( self.data.source ) , os.path.splitext( os.path.basename( self.data.source ) )[ 0 ] , 'scores' , '%s.txt' % field ) files.append( field_file ) if os.path.isfile( field_file ) : continue options = copy( self.data.fields ) options.remove( field ) for k in xrange( 0 , MAX_NUM_PARENTS ) : print "Size = %s" % ( k + 1 ) subconj = [ list( x ) for x in itertools.combinations( options , k ) ] for sub in subconj : sc = self.bic_score( field , sub ) prune = False for f in sub : par_sub = copy( sub ) par_sub.remove( f ) par_sc = self.bic_score( field , par_sub ) if compare( sc , par_sc ) < 0 : prune = True break if not prune : self.bestparents[ field ].append( copy( sub ) ) tmp = [ ( self.bicvalues[ field ][ self.hashedarray( p ) ] , p ) for p in self.bestparents[ field ] ] tmp.sort( reverse = True ) self.bestparents[ field ] = [ p[ 1 ] for p in tmp ] with open( field_file , 'w' ) as f : lstparents = self.bestparents[ field ] for p in lstparents : par = self.hashedarray( copy( p ) ) hp = copy( par ) if par == '' : hp = '_' f.write( "%s %s %s\n" % ( field , hp , self.bicvalues[ field ][ par ] ) ) self.bicvalues.pop( field , None ) self.data.deletecounters() merge_files( files , score_file ) self.create_bitsets() def reduce_bicscores( self , field ) : print "Reducing score lists for field %s" % field tmp = [ ( self.bicvalues[ field ][ p ] , self.decodearray( p ) ) for p in self.bicvalues[ field ] ] tmp.sort( reverse = True ) for i in xrange( len( tmp ) ) : ( sc , p ) = tmp[ i ] prune = False if not set( p ).issubset( tmp[ 0 ][ 1 ] ) : for j in xrange( i ) : ( old_sc , old_p ) = tmp[ j ] if set( old_p ).issubset( p ) : prune = True break if not prune : self.bestparents[ field ].append( p ) else : self.bicvalues[ field ].pop( self.hashedarray( p ) , None ) def create_bitsets( self ) : for f1 in self.data.fields : for f2 in self.data.fields : if f1 == f2 : continue lstpar = self.bestparents[ f1 ] coinc = ''.join( [ str( int( f2 in s ) ) for s in lstpar ] ) self.bitsets[ f1 ][ f2 ] = bitarray( coinc ) def find_parents( self , field , options ) : rem = [ f for f in self.data.fields if ( f not in options ) and f != field ] le = len( self.bestparents[ field ] ) full = bitarray( '1' * le ) for f in rem : aux = copy( self.bitsets[ field ][ f ] ) aux.invert() full &= aux pos = full.index( True ) return self.bestparents[ field ][ pos ] def loadmodel( self , modelfile ) : self.modelfile = modelfile print "Loading model from %s" % modelfile fieldset = self.data.fields node = { 'parents' : [] , 'childs' : [] } self.network = dict( [ ( field , copy( node ) ) for field in fieldset ] ) with open( modelfile , 'r' ) as f : lines = f.readlines() for l in lines : sp = l[ :-1 ].split( ':' ) field = sp[ 0 ] childs = [ s.strip() for s in sp[ 1 ].split( ',' ) if len( s.strip() ) > 0 ] for ch in childs : self.network[ field ][ 'childs' ].append( ch ) self.network[ ch ][ 'parents' ].append( field ) print "Finding topological order for network" self.topological = topological( self.network , fieldset ) print "Top. Order = %s" % self.topological def setnetwork( self , network , topo_order = None , train = True ) : self.network = copy( network ) if not topo_order : self.topological = topological( self.network , self.data.fields ) else : self.topological = topo_order if train : self.trainmodel() def trainmodel( self ) : #print "Training model..." ''' START POINTER FUNCTIONS ''' calc_probs = self.calculateprobabilities lstfields = self.data.fields ''' END POINTER FUNCTIONS ''' self.probs = dict( [ ( field , {} ) for field in lstfields ] ) for field in self.data.fields : xi = [ field ] pa_xi = self.network[ field ][ 'parents' ] calc_probs( xi , pa_xi ) def calculateprobabilities( self , xsetfield , ysetfield ) : #print "Calculating P( %s | %s )" % ( xsetfield , ysetfield ) implies = self.data.evaluate( xsetfield ) condition = self.data.evaluate( ysetfield ) for xdict in implies : xkey , xval = xdict.keys()[ 0 ] , xdict.values()[ 0 ] if xval not in self.probs[ xkey ] : self.probs[ xkey ][ xval ] = {} if not condition : self.conditional_prob( xdict , {} ) continue for y in condition : self.conditional_prob( xdict , y ) def conditional_prob( self , x , y ) : xkey , xval = x.keys()[ 0 ] , x.values()[ 0 ] cond = self.data.hashed( y ) if cond in self.probs[ xkey ][ xval ] : return self.probs[ xkey ][ xval ][ cond ] numerator = copy( x ) for key in y : numerator[ key ] = y[ key ] denominator = y pnum = self.data.getcount( numerator ) pden = len( self.data.rows ) if not denominator else self.data.getcount( denominator ) pnum , pden = ( pnum + self.bdeuprior( numerator ) , pden + self.bdeuprior( denominator ) ) resp = float( pnum ) / float( pden ) self.probs[ xkey ][ xval ][ cond ] = resp return resp def bdeuprior( self , setfields ) : prior = 1.0 fieldtypes = self.data.fieldtypes for field in setfields : tam = ( len( self.data.stats[ field ] ) if fieldtypes[ field ] == LITERAL_FIELD else 2 ) prior *= tam return ESS / prior def score( self ) : resp = 0.0 for field in self.data.fields : resp += self.bic_score( field , self.network[ field ][ 'parents' ] ) self.network[ 'score' ] = resp return resp def bic_score( self , xsetfield , ysetfield ) : field = xsetfield cond = self.hashedarray( ysetfield ) if cond in self.bicvalues[ field ] : return self.bicvalues[ field ][ cond ] #print "Calculating BIC( %s | %s )" % ( xsetfield , ysetfield ) N = len( self.data.rows ) H = self.entropy( xsetfield , ysetfield ) S = self.size( xsetfield , ysetfield ) resp = ( -N * H ) - ( log( N ) / 2.0 * S ) #print "BIC( %s | %s ) = %s" % ( xsetfield , ysetfield , resp ) self.bicvalues[ field ][ cond ] = resp return resp def mdl_score( self , xsetfield , ysetfield ) : field = xsetfield cond = self.hashedarray( ysetfield ) if cond in self.bicvalues[ field ] : return self.bicvalues[ field ][ cond ] #print "Calculating BIC( %s | %s )" % ( xsetfield , ysetfield ) N = len( self.data.rows ) H = self.entropy( xsetfield , ysetfield ) S = self.size( xsetfield , ysetfield ) resp = N * H + ( log( N ) / 2.0 * S ) #print "BIC( %s | %s ) = %s" % ( xsetfield , ysetfield , resp ) self.bicvalues[ field ][ cond ] = resp return resp def entropy( self , xsetfield , ysetfield ) : field = xsetfield cond = self.hashedarray( ysetfield ) if cond in self.entropyvalues[ field ] : return self.entropyvalues[ field ][ cond ] x = self.data.evaluate( [ xsetfield ] ) y = self.data.evaluate( ysetfield ) N = len( self.data.rows ) resp = 0.0 ''' START POINTER FUNCTIONS ''' getcount = self.data.getcount bdeuprior = self.bdeuprior ''' END POINTER FUNCTIONS ''' for xdict in x : xkey , xval = xdict.keys()[ 0 ] , xdict.values()[ 0 ] if not y : Nij = getcount( xdict ) + bdeuprior( xdict ) resp += ( Nij / N ) * log( Nij / N ) continue for ydict in y : ij = copy( ydict ) ijk = copy( ij ) ijk[ xkey ] = xval Nijk = getcount( ijk ) + bdeuprior( ijk ) Nij = getcount( ij ) + bdeuprior( ij ) resp += ( Nijk / N * log( Nijk / Nij ) ) self.entropyvalues[ field ][ cond ] = -resp return -resp def size( self , xsetfield , ysetfield ) : field = xsetfield cond = self.hashedarray( ysetfield ) if cond in self.sizevalues[ field ] : return self.sizevalues[ field ][ cond ] resp = len( self.data.evaluate( [ xsetfield ] ) ) - 1 for field in ysetfield : resp *= len( self.data.evaluate( [ field ] ) ) self.sizevalues[ field ][ cond ] = resp return resp def hashedarray( self , setfields ) : setfields.sort() return ','.join( setfields ) def decodearray( self , st ) : par = st.split( ',' ) if len( par ) == 1 and par[ 0 ] == '' : par = [] return par if __name__ == "__main__" : if len( sys.argv ) == 4 :
[ "\t\tdatasetfile , field , parents = sys.argv[ 1: ]" ]
1,784
lcc
python
null
3f302be0d966385442a6296e30fa6c4cf6c4bd891c7e8b20
using System; using Server.Items; using Server.Targeting; using Server.Mobiles; using System.Collections.Generic; namespace Server.Engines.Craft { public enum EnhanceResult { None, NotInBackpack, BadItem, BadResource, AlreadyEnhanced, Success, Failure, Broken, NoResources, NoSkill } public class Enhance { private static Dictionary<Type, CraftSystem> _SpecialTable; public static void Initialize() { _SpecialTable = new Dictionary<Type, CraftSystem>(); _SpecialTable[typeof(ClockworkLeggings)] = DefBlacksmithy.CraftSystem; _SpecialTable[typeof(GargishClockworkLeggings)] = DefBlacksmithy.CraftSystem; } private static bool IsSpecial(Item item, CraftSystem system) { foreach (KeyValuePair<Type, CraftSystem> kvp in _SpecialTable) { if (kvp.Key == item.GetType() && kvp.Value == system) return true; } return false; } public static EnhanceResult Invoke(Mobile from, CraftSystem craftSystem, BaseTool tool, Item item, CraftResource resource, Type resType, ref object resMessage) { if (item == null) return EnhanceResult.BadItem; if (!item.IsChildOf(from.Backpack)) return EnhanceResult.NotInBackpack; if (!(item is BaseArmor) && !(item is BaseWeapon)) return EnhanceResult.BadItem; if (item is IArcaneEquip) { IArcaneEquip eq = (IArcaneEquip)item; if (eq.IsArcane) return EnhanceResult.BadItem; } if (CraftResources.IsStandard(resource)) return EnhanceResult.BadResource; int num = craftSystem.CanCraft(from, tool, item.GetType()); if (num > 0) { resMessage = num; return EnhanceResult.None; } CraftItem craftItem = craftSystem.CraftItems.SearchFor(item.GetType()); if (IsSpecial(item, craftSystem)) { craftItem = craftSystem.CraftItems.SearchForSubclass(item.GetType()); } if (craftItem == null || craftItem.Resources.Count == 0) { return EnhanceResult.BadItem; } #region Mondain's Legacy if (craftItem.ForceNonExceptional) return EnhanceResult.BadItem; #endregion bool allRequiredSkills = false; if (craftItem.GetSuccessChance(from, resType, craftSystem, false, ref allRequiredSkills) <= 0.0) return EnhanceResult.NoSkill; CraftResourceInfo info = CraftResources.GetInfo(resource); if (info == null || info.ResourceTypes.Length == 0) return EnhanceResult.BadResource; CraftAttributeInfo attributes = info.AttributeInfo; if (attributes == null) return EnhanceResult.BadResource; int resHue = 0, maxAmount = 0; if (!craftItem.ConsumeRes(from, resType, craftSystem, ref resHue, ref maxAmount, ConsumeType.None, ref resMessage)) return EnhanceResult.NoResources; if (craftSystem is DefBlacksmithy) { AncientSmithyHammer hammer = from.FindItemOnLayer(Layer.OneHanded) as AncientSmithyHammer; if (hammer != null) { hammer.UsesRemaining--; if (hammer.UsesRemaining < 1) hammer.Delete(); } } int phys = 0, fire = 0, cold = 0, pois = 0, nrgy = 0; int dura = 0, luck = 0, lreq = 0, dinc = 0; int baseChance = 0; bool physBonus = false; bool fireBonus = false; bool coldBonus = false; bool nrgyBonus = false; bool poisBonus = false; bool duraBonus = false; bool luckBonus = false; bool lreqBonus = false; bool dincBonus = false; if (item is BaseWeapon) { BaseWeapon weapon = (BaseWeapon)item; if (!CraftResources.IsStandard(weapon.Resource)) return EnhanceResult.AlreadyEnhanced; baseChance = 20; dura = weapon.MaxHitPoints; luck = weapon.Attributes.Luck; lreq = weapon.WeaponAttributes.LowerStatReq; dinc = weapon.Attributes.WeaponDamage; fireBonus = (attributes.WeaponFireDamage > 0); coldBonus = (attributes.WeaponColdDamage > 0); nrgyBonus = (attributes.WeaponEnergyDamage > 0); poisBonus = (attributes.WeaponPoisonDamage > 0); duraBonus = (attributes.WeaponDurability > 0); luckBonus = (attributes.WeaponLuck > 0); lreqBonus = (attributes.WeaponLowerRequirements > 0); dincBonus = (dinc > 0); } else { BaseArmor armor = (BaseArmor)item; if (!CraftResources.IsStandard(armor.Resource)) return EnhanceResult.AlreadyEnhanced; baseChance = 20; phys = armor.PhysicalResistance; fire = armor.FireResistance; cold = armor.ColdResistance; pois = armor.PoisonResistance; nrgy = armor.EnergyResistance; dura = armor.MaxHitPoints; luck = armor.Attributes.Luck; lreq = armor.ArmorAttributes.LowerStatReq; physBonus = (attributes.ArmorPhysicalResist > 0); fireBonus = (attributes.ArmorFireResist > 0); coldBonus = (attributes.ArmorColdResist > 0); nrgyBonus = (attributes.ArmorEnergyResist > 0); poisBonus = (attributes.ArmorPoisonResist > 0); duraBonus = (attributes.ArmorDurability > 0); luckBonus = (attributes.ArmorLuck > 0); lreqBonus = (attributes.ArmorLowerRequirements > 0); dincBonus = false; } int skill = from.Skills[craftSystem.MainSkill].Fixed / 10; if (skill >= 100) baseChance -= (skill - 90) / 10; EnhanceResult res = EnhanceResult.Success; PlayerMobile user = from as PlayerMobile; if (physBonus) CheckResult(ref res, baseChance + phys); if (fireBonus) CheckResult(ref res, baseChance + fire); if (coldBonus) CheckResult(ref res, baseChance + cold); if (nrgyBonus) CheckResult(ref res, baseChance + nrgy); if (poisBonus) CheckResult(ref res, baseChance + pois); if (duraBonus) CheckResult(ref res, baseChance + (dura / 40)); if (luckBonus) CheckResult(ref res, baseChance + 10 + (luck / 2)); if (lreqBonus) CheckResult(ref res, baseChance + (lreq / 4)); if (dincBonus) CheckResult(ref res, baseChance + (dinc / 4)); if (user.NextEnhanceSuccess) { user.NextEnhanceSuccess = false; user.SendLocalizedMessage(1149969); // The magical aura that surrounded you disipates and you feel that your item enhancement chances have returned to normal. res = EnhanceResult.Success; } switch (res) { case EnhanceResult.Broken: { if (!craftItem.ConsumeRes(from, resType, craftSystem, ref resHue, ref maxAmount, ConsumeType.Half, ref resMessage)) return EnhanceResult.NoResources; item.Delete(); break; } case EnhanceResult.Success: { if (!craftItem.ConsumeRes(from, resType, craftSystem, ref resHue, ref maxAmount, ConsumeType.All, ref resMessage)) return EnhanceResult.NoResources; if (item is BaseWeapon) { BaseWeapon w = (BaseWeapon)item; w.Resource = resource; #region Mondain's Legacy if (resource != CraftResource.Heartwood) { w.Attributes.WeaponDamage += attributes.WeaponDamage; w.Attributes.WeaponSpeed += attributes.WeaponSwingSpeed; w.Attributes.AttackChance += attributes.WeaponHitChance; w.Attributes.RegenHits += attributes.WeaponRegenHits; w.WeaponAttributes.HitLeechHits += attributes.WeaponHitLifeLeech; } else { switch (Utility.Random(6)) { case 0: w.Attributes.WeaponDamage += attributes.WeaponDamage; break; case 1: w.Attributes.WeaponSpeed += attributes.WeaponSwingSpeed; break; case 2: w.Attributes.AttackChance += attributes.WeaponHitChance; break; case 3: w.Attributes.Luck += attributes.WeaponLuck; break; case 4: w.WeaponAttributes.LowerStatReq += attributes.WeaponLowerRequirements; break; case 5: w.WeaponAttributes.HitLeechHits += attributes.WeaponHitLifeLeech; break; } } #endregion int hue = w.GetElementalDamageHue(); if (hue > 0) w.Hue = hue; } #region Mondain's Legacy else if (item is BaseShield) { BaseShield shield = (BaseShield)item; shield.Resource = resource; switch (resource) { case CraftResource.AshWood: shield.ArmorAttributes.LowerStatReq += 20; break; case CraftResource.YewWood: shield.Attributes.RegenHits += 1; break; case CraftResource.Heartwood: switch (Utility.Random(7)) { case 0: shield.Attributes.BonusDex += 2; break; case 1: shield.Attributes.BonusStr += 2; break; case 2: shield.Attributes.ReflectPhysical += 5; break; case 3: shield.Attributes.SpellChanneling = 1; shield.Attributes.CastSpeed = -1; break; case 4: shield.ArmorAttributes.SelfRepair += 2; break; case 5: shield.PhysicalBonus += 5; break; case 6: shield.ColdBonus += 3; break; } break; case CraftResource.Bloodwood: shield.Attributes.RegenHits += 2; shield.Attributes.Luck += 40; break; case CraftResource.Frostwood: shield.Attributes.SpellChanneling = 1; shield.Attributes.CastSpeed = -1; break; } } #endregion else if (item is BaseArmor) //Sanity { ((BaseArmor)item).Resource = resource; #region Mondain's Legacy BaseArmor armor = (BaseArmor)item; if (resource != CraftResource.Heartwood) { armor.Attributes.WeaponDamage += attributes.ArmorDamage; armor.Attributes.AttackChance += attributes.ArmorHitChance; armor.Attributes.RegenHits += attributes.ArmorRegenHits; //armor.ArmorAttributes.MageArmor += attributes.ArmorMage; } else { switch (Utility.Random(5)) { case 0: armor.Attributes.WeaponDamage += attributes.ArmorDamage; break; case 1: armor.Attributes.AttackChance += attributes.ArmorHitChance; break; case 2: armor.ArmorAttributes.MageArmor += attributes.ArmorMage; break; case 3: armor.Attributes.Luck += attributes.ArmorLuck; break; case 4: armor.ArmorAttributes.LowerStatReq += attributes.ArmorLowerRequirements; break; } } #endregion } break; } case EnhanceResult.Failure: { if (!craftItem.ConsumeRes(from, resType, craftSystem, ref resHue, ref maxAmount, ConsumeType.Half, ref resMessage)) return EnhanceResult.NoResources; break; } } return res; } public static void CheckResult(ref EnhanceResult res, int chance) { if (res != EnhanceResult.Success) return; // we've already failed..
[ " int random = Utility.Random(100);" ]
976
lcc
csharp
null
218d7b3f8d5e93240d972dc518c5b9e0fe4372b38cd94b33
from typing import Optional, List, Iterable, Dict, Any, Type, Union import re from collections import OrderedDict from xml.dom import minidom from systemrdl import RDLCompiler, RDLImporter from systemrdl import rdltypes from systemrdl.messages import SourceRefBase from systemrdl import component as comp from . import typemaps class IPXACTImporter(RDLImporter): def __init__(self, compiler: RDLCompiler): super().__init__(compiler) self.ns = None # type: str self._current_regwidth = 32 self._addressUnitBits = 8 self._current_addressBlock_access = rdltypes.AccessType.rw @property def src_ref(self) -> SourceRefBase: return self.default_src_ref #--------------------------------------------------------------------------- def import_file(self, path: str) -> None: super().import_file(path) # minidom does not provide file position data. Using a bare SourceRef # for everything created during this import self._current_regwidth = 32 self._addressUnitBits = 8 dom = minidom.parse(path) addressBlock_s = self.seek_to_top_addressBlocks(dom) # Parse all the addressBlock elements found addrmap_or_mems = [] for addressBlock in addressBlock_s: addrmap_or_mem = self.parse_addressBlock(addressBlock) if addrmap_or_mem is not None: addrmap_or_mems.append(addrmap_or_mem) if not addrmap_or_mems: self.msg.fatal( "'memoryMap' must contain at least one 'addressBlock' element", self.src_ref ) if (len(addrmap_or_mems) == 1) and (addrmap_or_mems[0].addr_offset == 0): # OK to drop the hierarchy implied by the enclosing memoryMap # since it is only a wrapper around a single addressBlock at base # offset 0 # This addressBlock will be the top component that is registered # in $root top_component = addrmap_or_mems[0] # de-instantiate the addrmap top_component.type_name = top_component.inst_name top_component.is_instance = False top_component.inst_name = None top_component.original_def = None top_component.external = None top_component.inst_src_ref = None top_component.addr_offset = None else: # memoryMap encloses multiple addressBlock components, or the single # one uses a meaningful address offset. # In order to preserve this information, encapsulate them in a # top-level parent that is named after the memoryMap # Get the top-level memoryMap's element values d = self.flatten_element_values(addressBlock_s[0].parentNode) # Check for required name if 'name' not in d: self.msg.fatal("memoryMap is missing required tag 'name'", self.src_ref) # Create component instance to represent the memoryMap C = comp.Addrmap() C.def_src_ref = self.src_ref # Collect properties and other values C.type_name = d['name'] if 'displayName' in d: self.assign_property(C, "name", d['displayName']) if 'description' in d: self.assign_property(C, "desc", d['description']) # Insert all the addrmap_or_mems as children C.children = addrmap_or_mems top_component = C # register it with the root namespace self.register_root_component(top_component) #--------------------------------------------------------------------------- def seek_to_top_addressBlocks(self, dom: minidom.Element) -> List[minidom.Element]: """ IP-XACT files can be a little ambiguous depending on who they come from This function returns the most reasonable starting point to use as the top-level node for import. Returns a list of addressBlock elements If: - There is exactly one memoryMap - Inside it, a single addressBlock Then the addressBlock is the top-level node (will actually return a list with only one addressBlock) If: - There is exactly one memoryMap - Inside it, more than one addressBlock that has meaningful contents "meaningful" is having a name, base address, and at least one child Then the memoryMap is the top-level node (will actually return a list of remaining meaningful addressBlocks) If there is more than one memoryMap, use the first one that contains an addressBlock child """ # Find <component> and determine namespace prefix c_ipxact = self.get_first_child_by_tag(dom, "ipxact:component") c_spirit = self.get_first_child_by_tag(dom, "spirit:component") if c_ipxact is not None: component = c_ipxact elif c_spirit is not None: component = c_spirit else: self.msg.fatal( "Could not find a 'component' element", self.src_ref ) self.ns = component.prefix # Find <memoryMaps> memoryMaps_s = self.get_children_by_tag(component, self.ns+":memoryMaps") if len(memoryMaps_s) != 1: self.msg.fatal( "'component' must contain exactly one 'memoryMaps' element", self.src_ref ) memoryMaps = memoryMaps_s[0] # Find all <memoryMap> memoryMap_s = self.get_children_by_tag(memoryMaps, self.ns+":memoryMap") # Find the first <memoryMap> that has at least one <addressBlock> for mm in memoryMap_s: addressBlock_s = self.get_children_by_tag(mm, self.ns+":addressBlock") if addressBlock_s: aub = self.get_first_child_by_tag(mm, self.ns+":addressUnitBits") if aub: self._addressUnitBits = self.parse_integer(get_text(aub)) if (self._addressUnitBits < 8) or (self._addressUnitBits % 8 != 0): self.msg.fatal( "Importer only supports <addressUnitBits> that is a multiple of 8", self.src_ref ) break else: self.msg.fatal( "No valid 'memoryMap' found", self.src_ref ) return addressBlock_s #--------------------------------------------------------------------------- def parse_addressBlock(self, addressBlock: minidom.Element) -> Union[comp.Addrmap, comp.Mem]: """ Parses an addressBlock and returns an instantiated addrmap or mem component. If addressBlock is empty or usage specifies 'reserved' then returns None """ # Schema: # {nameGroup} # name (required) --> inst_name # displayName --> prop:name # description --> prop:desc # accessHandles # isPresent --> prop:ispresent # baseAddress (required) --> addr_offset # {addressBlockDefinitionGroup} # typeIdentifier # range (required) --> divide by width and set prop:mementries if Mem # width (required) --> prop:memwidth if Mem # {memoryBlockData} # usage --> Mem vs Addrmap instance # volatile # access --> prop:sw if Mem # parameters # {registerData} # register --> children # registerFile --> children # vendorExtensions d = self.flatten_element_values(addressBlock) if d.get('usage', None) == "reserved": # 1685-2014 6.9.4.2-a.1.iii: defines the entire range of the # addressBlock as reserved or for unknown usage to IP-XACT. This # type shall not contain registers. return None # Check for required values required = {'name', 'baseAddress', 'range', 'width'} missing = required - set(d.keys()) for m in missing: self.msg.fatal("addressBlock is missing required tag '%s'" % m, self.src_ref) # Create component instance is_memory = (d.get('usage', None) == "memory") if is_memory: C = self.instantiate_mem( self.create_mem_definition(), d['name'], self.AU_to_bytes(d['baseAddress']) ) else: C = self.instantiate_addrmap( self.create_addrmap_definition(), d['name'], self.AU_to_bytes(d['baseAddress']) ) # Collect properties and other values if 'displayName' in d: self.assign_property(C, "name", d['displayName']) if 'description' in d: self.assign_property(C, "desc", d['description']) if 'isPresent' in d: self.assign_property(C, "ispresent", d['isPresent']) self._current_regwidth = d['width'] if is_memory: self.assign_property(C, "memwidth", d['width']) self.assign_property( C, "mementries", (d['range'] * self._addressUnitBits) // (d['width']) ) if 'access' in d: self.assign_property(C, "sw", d['access']) if 'access' in d: self._current_addressBlock_access = d['access'] else: self._current_addressBlock_access = rdltypes.AccessType.rw # collect children for child_el in d['child_els']: if child_el.localName == "register": R = self.parse_register(child_el) if R: self.add_child(C, R) elif child_el.localName == "registerFile" and not is_memory: R = self.parse_registerFile(child_el) if R: self.add_child(C, R) else: self.msg.error( "Invalid child element <%s> found in <%s:addressBlock>" % (child_el.tagName, self.ns), self.src_ref ) if 'vendorExtensions' in d: C = self.addressBlock_vendorExtensions(d['vendorExtensions'], C) if not is_memory and not C.children: # If a register addressBlock has no children, skip it return None return C #--------------------------------------------------------------------------- def parse_registerFile(self, registerFile: minidom.Element) -> comp.Regfile: """ Parses an registerFile and returns an instantiated regfile component """ # Schema: # {nameGroup} # name (required) --> inst_name # displayName --> prop:name # description --> prop:desc # accessHandles # isPresent --> prop:ispresent # dim --> dimensions # addressOffset (required) # {registerFileDefinitionGroup} # typeIdentifier # range (required) # {registerData} # register --> children # registerFile --> children # parameters # vendorExtensions d = self.flatten_element_values(registerFile) # Check for required values required = {'name', 'addressOffset', 'range'} missing = required - set(d.keys()) for m in missing: self.msg.fatal("registerFile is missing required tag '%s'" % m, self.src_ref) # Create component instance if 'dim' in d: # is array C = self.instantiate_regfile( self.create_regfile_definition(), d['name'], self.AU_to_bytes(d['addressOffset']), d['dim'], self.AU_to_bytes(d['range']) ) else: C = self.instantiate_regfile( self.create_regfile_definition(), d['name'], self.AU_to_bytes(d['addressOffset']) ) # Collect properties and other values if 'displayName' in d: self.assign_property(C, "name", d['displayName']) if 'description' in d: self.assign_property(C, "desc", d['description']) if 'isPresent' in d: self.assign_property(C, "ispresent", d['isPresent']) # collect children for child_el in d['child_els']: if child_el.localName == "register": R = self.parse_register(child_el) if R: self.add_child(C, R) elif child_el.localName == "registerFile": R = self.parse_registerFile(child_el) if R: self.add_child(C, R) else: self.msg.error( "Invalid child element <%s> found in <%s:registerFile>" % (child_el.tagName, self.ns), self.src_ref ) if 'vendorExtensions' in d: C = self.registerFile_vendorExtensions(d['vendorExtensions'], C) if not C.children: # Register File contains no fields! RDL does not allow this. Discard self.msg.warning( "Discarding registerFile '%s' because it does not contain any children" % (C.inst_name), self.src_ref ) return None return C #--------------------------------------------------------------------------- def parse_register(self, register: minidom.Element) -> comp.Reg: """ Parses a register and returns an instantiated reg component """ # Schema: # {nameGroup} # name (required) --> inst_name # displayName --> prop:name # description --> prop:desc # accessHandles # isPresent --> prop:ispresent # dim --> dimensions # addressOffset (required) # {registerDefinitionGroup} # typeIdentifier # size (required) # volatile # access # reset { <<1685-2009>> # value # mask # } # field... # alternateRegisters # parameters # vendorExtensions d = self.flatten_element_values(register) # Check for required values required = {'name', 'addressOffset', 'size'} missing = required - set(d.keys()) for m in missing: self.msg.fatal("register is missing required tag '%s'" % m, self.src_ref) # Create component instance if 'dim' in d: # is array C = self.instantiate_reg( self.create_reg_definition(), d['name'], self.AU_to_bytes(d['addressOffset']), d['dim'], d['size'] // 8 ) else: C = self.instantiate_reg( self.create_reg_definition(), d['name'], self.AU_to_bytes(d['addressOffset']) ) # Collect properties and other values if 'displayName' in d: self.assign_property(C, "name", d['displayName']) if 'description' in d: self.assign_property(C, "desc", d['description']) if 'isPresent' in d: self.assign_property(C, "ispresent", d['isPresent']) self.assign_property(C, "regwidth", d['size']) reg_access = d.get('access', self._current_addressBlock_access) reg_reset_value = d.get('reset.value', None) reg_reset_mask = d.get('reset.mask', None) # collect children for child_el in d['child_els']: if child_el.localName == "field": field = self.parse_field(child_el, reg_access, reg_reset_value, reg_reset_mask) if field is not None: self.add_child(C, field) else: self.msg.error( "Invalid child element <%s> found in <%s:register>" % (child_el.tagName, self.ns), self.src_ref ) if 'vendorExtensions' in d: C = self.register_vendorExtensions(d['vendorExtensions'], C) if not C.children: # Register contains no fields! RDL does not allow this. Discard self.msg.warning( "Discarding register '%s' because it does not contain any fields" % (C.inst_name), self.src_ref ) return None return C #--------------------------------------------------------------------------- def parse_field(self, field: minidom.Element, reg_access: rdltypes.AccessType, reg_reset_value: Optional[int], reg_reset_mask: Optional[int]) -> comp.Field: """ Parses an field and returns an instantiated field component """ # Schema: # {nameGroup} # name (required) --> inst_name # displayName --> prop:name # description --> prop:desc # accessHandles # isPresent --> prop:ispresent # bitOffset (required) # resets { <<1685-2014>> # reset { # value # mask # } # } # {fieldDefinitionGroup} # typeIdentifier # bitWidth (required) # {fieldData} # volatile # access # enumeratedValues... # modifiedWriteValue # writeValueConstraint # readAction # testable # reserved # parameters # vendorExtensions d = self.flatten_element_values(field) # Check for required values required = {'name', 'bitOffset', 'bitWidth'} missing = required - set(d.keys()) for m in missing: self.msg.fatal("field is missing required tag '%s'" % m, self.src_ref) # Discard field if it is reserved if d.get('reserved', False): return None # Create component instance C = self.instantiate_field( self.create_field_definition(), d['name'], d['bitOffset'], d['bitWidth'] ) # Collect properties and other values if 'displayName' in d: self.assign_property(C, "name", d['displayName']) if 'description' in d: self.assign_property(C, "desc", d['description']) if 'isPresent' in d: self.assign_property(C, "ispresent", d['isPresent']) if 'access' in d: self.assign_property(C, "sw", d['access']) else: self.assign_property(C, "sw", reg_access) if 'testable' in d: self.assign_property(C, "donttest", not d['testable']) if 'reset.value' in d: self.assign_property(C, "reset", d['reset.value']) elif reg_reset_value is not None: mask = (1 << C.width) - 1 rst = (reg_reset_value >> C.lsb) & mask if reg_reset_mask is None: rmask = mask else: rmask = (reg_reset_mask >> C.lsb) & mask if rmask: self.assign_property(C, "reset", rst) if 'readAction' in d: self.assign_property(C, "onread", d['readAction']) if 'modifiedWriteValue' in d: self.assign_property(C, "onwrite", d['modifiedWriteValue']) if 'enum_el' in d: enum_type = self.parse_enumeratedValues(d['enum_el'], C.inst_name + "_enum_t") self.assign_property(C, "encode", enum_type) if 'vendorExtensions' in d: C = self.field_vendorExtensions(d['vendorExtensions'], C) return C #--------------------------------------------------------------------------- def parse_integer(self, s: str) -> int: """ Converts an IP-XACT number string into an int IP-XACT technically supports integer expressions in these fields. For now, I don't have a compelling reason to support them. Handles the following formats: - Normal decimal: 123, -456 - Verilog-style: 'b10, 'o77, d123, 'hff, 8'hff - scaledInteger: - May have # or 0x prefix for hex - May have K, M, G, or T multiplier suffix """ s = s.strip() multiplier = { "K": 1024, "M": 1024*1024, "G": 1024*1024*1024, "T": 1024*1024*1024*1024 } m = re.fullmatch(r'(-?\d+)(K|M|G|T)?', s, re.I) if m: v = int(m.group(1)) if m.group(2): v *= multiplier[m.group(2).upper()] return v m = re.fullmatch(r"\d*'h([0-9a-f]+)", s, re.I) if m: return int(m.group(1), 16) m = re.fullmatch(r"(-)?(0x|#)([0-9a-f]+)(K|M|G|T)?", s, re.I) if m: v = int(m.group(3), 16) if m.group(1): v = -v if m.group(4): v *= multiplier[m.group(4).upper()] return v m = re.fullmatch(r"\d*'d([0-9]+)", s, re.I) if m: return int(m.group(1), 10) m = re.fullmatch(r"\d*'b([0-1]+)", s, re.I) if m: return int(m.group(1), 2) m = re.fullmatch(r"\d*'o([0-7]+)", s, re.I) if m: return int(m.group(1), 8) raise ValueError #--------------------------------------------------------------------------- def parse_boolean(self, s: str) -> bool: """ Converts several boolean-ish representations to a true bool. """ s = s.lower().strip() if s in ("true", "1"): return True elif s in ("false", "0"): return False else: raise ValueError("Unable to parse boolean value '%s'" % s) #--------------------------------------------------------------------------- def flatten_element_values(self, el: minidom.Element) -> Dict[str, Any]: """ Given any of the IP-XACT RAL component elements, flatten the key/value tags into a dictionary. Handles values contained in: addressBlock, register, registerFile, field Ignores several tags that are not interesting to the RAL importer """ d = { 'child_els' : [] } # type: Dict[str, Any] for child in self.iterelements(el): if child.localName == "name": # Sanitize name d[child.localName] = re.sub( r'[:\-.]', "_", get_text(child).strip() ) elif child.localName in ("displayName", "usage"): # Copy string types directly, but stripped d[child.localName] = get_text(child).strip() elif child.localName == "description": # Copy description string types unmodified d[child.localName] = get_text(child) elif child.localName in ("baseAddress", "addressOffset", "range", "width", "size", "bitOffset", "bitWidth"): # Parse integer types d[child.localName] = self.parse_integer(get_text(child)) elif child.localName in ("isPresent", "volatile", "testable", "reserved"): # Parse boolean types d[child.localName] = self.parse_boolean(get_text(child)) elif child.localName in ("register", "registerFile", "field"): # Child elements that need to be parsed elsewhere d['child_els'].append(child) elif child.localName in ("reset", "resets"): if child.localName == "resets": # pick the first reset reset = self.get_first_child_by_tag(child, self.ns + ":reset") if reset is None: continue else: reset = child value_el = self.get_first_child_by_tag(reset, self.ns + ":value") if value_el: d['reset.value'] = self.parse_integer(get_text(value_el)) mask_el = self.get_first_child_by_tag(reset, self.ns + ":mask") if mask_el: d['reset.mask'] = self.parse_integer(get_text(mask_el)) elif child.localName == "access": s = get_text(child).strip() sw = typemaps.sw_from_access(s) if sw is None: self.msg.error( "Invalid value '%s' found in <%s>" % (s, child.tagName), self.src_ref ) else: d['access'] = sw elif child.localName == "dim": # Accumulate array dimensions dim = self.parse_integer(get_text(child)) if 'dim' in d: d['dim'].append(dim) else: d['dim'] = [dim] elif child.localName == "readAction": s = get_text(child).strip() onread = typemaps.onread_from_readaction(s) if onread is None: self.msg.error( "Invalid value '%s' found in <%s>" % (s, child.tagName), self.src_ref ) else: d['readAction'] = onread elif child.localName == "modifiedWriteValue": s = get_text(child).strip() onwrite = typemaps.onwrite_from_mwv(s) if onwrite is None: self.msg.error( "Invalid value '%s' found in <%s>" % (s, child.tagName), self.src_ref ) else: d['modifiedWriteValue'] = onwrite elif child.localName == "enumeratedValues": # Deal with this later d['enum_el'] = child elif child.localName == "vendorExtensions": # Deal with this later d['vendorExtensions'] = child return d #--------------------------------------------------------------------------- def parse_enumeratedValues(self, enumeratedValues: minidom.Element, type_name: str) -> Type[rdltypes.UserEnum]: """ Parses an enumeration listing and returns the user-defined enum type """ entries = OrderedDict() for enumeratedValue in self.iterelements(enumeratedValues): if enumeratedValue.localName != "enumeratedValue": continue # Flatten element values d = {} # type: Dict[str, Any] for child in self.iterelements(enumeratedValue): if child.localName in ("name", "displayName"): d[child.localName] = get_text(child).strip() elif child.localName == "description": d[child.localName] = get_text(child) elif child.localName == "value": d[child.localName] = self.parse_integer(get_text(child)) # Check for required values required = {'name', 'value'} missing = required - set(d.keys()) for m in missing: self.msg.fatal("enumeratedValue is missing required tag '%s'" % m, self.src_ref) entry_name = d['name'] entry_value = d['value'] displayname = d.get('displayName', None) desc = d.get('description', None)
[ " entries[entry_name] = (entry_value, displayname, desc)" ]
2,406
lcc
python
null
585e8ba1eb1b3be2a7a81d0eebb3178d8d03ec8aea535999
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Configuration; using System.IO; using System.Collections; using System.Reflection; namespace FOG { public partial class FrmSetup : Form { public const String PROGRAMFILES_VAR = "{{FOG_PF_DIR}}"; private CheckBox[] arChkBx; private ArrayList alModules; private String CONFIGPATH; private String CONFIGPATHBACKUP; private String strInstallLocation; private bool headless; public FrmSetup(String[] args) { InitializeComponent(); parseArgs(args); CONFIGPATH = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\etc\config.ini"; CONFIGPATHBACKUP = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\etc\config.ini.backup"; } private void parseArgs(String[] args) { if (args != null) { strInstallLocation = @"c:\program files\fog"; for (int i = 0; i < args.Length; i++) { String arg = args[i]; if (arg != null && arg.CompareTo("/fog-defaults=true") == 0) { headless = true; } else if (arg != null && arg.StartsWith("/pf=", StringComparison.CurrentCultureIgnoreCase)) { strInstallLocation = arg.Replace("/pf=",""); if (strInstallLocation != null && strInstallLocation.Length > 0) { strInstallLocation = strInstallLocation.Replace("\"", ""); if (strInstallLocation.EndsWith("\\")) strInstallLocation.Remove(strInstallLocation.LastIndexOf(@"\")); } } } } } public Boolean isQuiet() { return headless; } public Boolean writeQuiet() { return writeFile("", strInstallLocation); } public Boolean isConfigFilePresent() { try { return (File.Exists(CONFIGPATH)); } catch (Exception) { return false; } } public Boolean isConfigured() { if (File.Exists(CONFIGPATH)) { String[] strConfig = File.ReadAllLines(CONFIGPATH); Boolean found = false; for (int i = 0; i < strConfig.Length; i++) { if (strConfig[i].Contains("x.x.x.x")) { found = true; break; } } return !found; } return false; } private void FrmSetup_Load(object sender, EventArgs e) { pnlIP.Dock = DockStyle.Fill; pnlDone.Dock = DockStyle.Fill; pnlDone.Visible = false; btnDone.Left = btnSave.Left; btnDone.Top = btnSave.Top; if (isConfigFilePresent()) { Boolean blFound = !isConfigured(); if (blFound) loadServiceInfo(); if (!blFound) { MessageBox.Show("It appears that the FOG service has already been configured"); this.Close(); } } else { MessageBox.Show("Fatal Error:\nUnable to locate coniguration file for FOG Service!"); this.Close(); } } private void loadServiceInfo() { alModules = new ArrayList(); if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory)) { String[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory); for (int i = 0; i < files.Length; i++) { if (files[i].EndsWith(".dll")) { try { byte[] buffer = File.ReadAllBytes(files[i]); Assembly assemb = Assembly.Load(buffer); if (assemb != null) { Type[] type = assemb.GetTypes(); for (int z = 0; z < type.Length; z++) { if (type[z] != null) { try { Object module = Activator.CreateInstance(type[z]); Assembly abstractA = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + @"AbstractFOGService.dll"); Type t = abstractA.GetTypes()[0]; if (module.GetType().IsSubclassOf(t)) { alModules.Add(new SubClassMenuItem(files[i], ((AbstractFOGService)module).mGetDescription())); } t = null; abstractA = null; module = null; } catch { } } } } assemb = null; } catch { } } } if (alModules.Count > 0) { arChkBx = new CheckBox[alModules.Count]; for (int i = 0; i < alModules.Count; i++) { try { SubClassMenuItem sub = (SubClassMenuItem)alModules[i]; arChkBx[i] = new CheckBox(); arChkBx[i].Text = sub.getDescription(); arChkBx[i].Width = pnlServices.Width - 10; arChkBx[i].Height = 40; arChkBx[i].Checked = true; pnlServices.Controls.Add(arChkBx[i]); pnlServices.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else {
[ " Label noneFound = new Label();" ]
451
lcc
csharp
null
c8bb6c7b2115807916ef0d828a186d6e698ed8a7962bc728
/******** * This file is part of Ext.NET. * * Ext.NET is free software: you can redistribute it and/or modify * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Ext.NET is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE * along with Ext.NET. If not, see <http://www.gnu.org/licenses/>. * * * @version : 1.2.0 - Ext.NET Pro License * @author : Ext.NET, Inc. http://www.ext.net/ * @date : 2011-09-12 * @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved. * @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0. * See license.txt and http://www.ext.net/license/. * See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt ********/ using System; using System.ComponentModel; using System.IO; using System.Web.UI; using Newtonsoft.Json; using Ext.Net.Utilities; namespace Ext.Net { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> [Meta] [Description("")] public abstract partial class MultiSelectBase<T> : Field, IStore where T : StateManagedItem { /// <summary> /// The data store to use. /// </summary> [Meta] [ConfigOption("store", JsonMode.ToClientID)] [Category("6. MultiSelect")] [DefaultValue("")] [IDReferenceProperty(typeof(Store))] [Description("The data store to use.")] public virtual string StoreID { get { return (string)this.ViewState["StoreID"] ?? ""; } set { this.ViewState["StoreID"] = value; } } private StoreCollection store; /// <summary> /// The data store to use. /// </summary> [Meta] [ConfigOption("store>Primary")] [Category("7. MultiSelect")] [PersistenceMode(PersistenceMode.InnerProperty)] [Description("The data store to use.")] public virtual StoreCollection Store { get { if (this.store == null) { this.store = new StoreCollection(); this.store.AfterItemAdd += this.AfterStoreAdd; this.store.AfterItemRemove += this.AfterStoreRemove; } return this.store; } } /// <summary> /// /// </summary> [Description("")] protected virtual void AfterStoreAdd(Store item) { this.Controls.AddAt(0, item); this.LazyItems.Insert(0, item); } /// <summary> /// /// </summary> [Description("")] protected virtual void AfterStoreRemove(Store item) { this.Controls.Remove(item); this.LazyItems.Remove(item); } private ListItemCollection<T> items; /// <summary> /// /// </summary> [Meta] [PersistenceMode(PersistenceMode.InnerProperty)] [ViewStateMember] [Description("")] public ListItemCollection<T> Items { get { if (this.items == null) { this.items = new ListItemCollection<T>(); } return this.items; } } /// <summary> /// /// </summary> [ConfigOption("store", JsonMode.Raw)] [DefaultValue("")] [Description("")] protected string ItemsProxy { get { if (this.StoreID.IsNotEmpty() || this.Store.Primary != null) { return ""; } return this.ItemsToStore; } } private string ItemsToStore { get { StringWriter sw = new StringWriter(); JsonTextWriter jw = new JsonTextWriter(sw); ListItemCollectionJsonConverter converter = new ListItemCollectionJsonConverter(); converter.WriteJson(jw, this.Items, null); return sw.GetStringBuilder().ToString(); } } private SelectedListItemCollection selectedItems; /// <summary> /// /// </summary> [Meta] [PersistenceMode(PersistenceMode.InnerProperty)] [ViewStateMember] [Description("")] public SelectedListItemCollection SelectedItems { get { if (this.selectedItems == null) { this.selectedItems = new SelectedListItemCollection(); } return this.selectedItems; } } /// <summary> /// The underlying data field name to bind to this MultiSelect. /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("The underlying data field name to bind to this MultiSelect.")] public virtual string DisplayField { get { return (string)this.ViewState["DisplayField"] ?? "text"; } set { this.ViewState["DisplayField"] = value; } } /// <summary> /// The underlying data value name to bind to this MultiSelect. /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("The underlying data value name to bind to this MultiSelect.")] public virtual string ValueField { get { return (string)this.ViewState["ValueField"] ?? "value"; } set { this.ViewState["ValueField"] = value; } } /// <summary> /// False to validate that the value length > 0 (defaults to true). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(true)] [Description("False to validate that the value length > 0 (defaults to true).")] public virtual bool AllowBlank { get { object obj = this.ViewState["AllowBlank"]; return (obj == null) ? true : (bool)obj; } set { this.ViewState["AllowBlank"] = value; } } /// <summary> /// Maximum input field length allowed (defaults to Number.MAX_VALUE). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(-1)] [Description("Maximum input field length allowed (defaults to Number.MAX_VALUE).")] public virtual int MaxLength { get { object obj = this.ViewState["MaxLength"]; return (obj == null) ? -1 : (int)obj; } set { this.ViewState["MaxLength"] = value; } } /// <summary> /// Minimum input field length required (defaults to 0). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(0)] [Description("Minimum input field length required (defaults to 0).")] public virtual int MinLength { get { object obj = this.ViewState["MinLength"]; return (obj == null) ? 0 : (int)obj; } set { this.ViewState["MinLength"] = value; } } /// <summary> /// Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}'). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Localizable(true)] [Description("Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}').")] public virtual string MaxLengthText { get { return (string)this.ViewState["MaxLengthText"] ?? ""; } set { this.ViewState["MaxLengthText"] = value; } } /// <summary> /// Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}'). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Localizable(true)] [Description("Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}').")] public virtual string MinLengthText { get { return (string)this.ViewState["MinLengthText"] ?? ""; } set { this.ViewState["MinLengthText"] = value; } } /// <summary> /// Error text to display if the allow blank validation fails (defaults to 'This field is required'). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Localizable(true)] [Description("Error text to display if the allow blank validation fails (defaults to 'This field is required').")] public virtual string BlankText { get { return (string)this.ViewState["BlankText"] ?? ""; } set { this.ViewState["BlankText"] = value; } } /// <summary> /// Causes drag operations to copy nodes rather than move (defaults to false). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(false)] [Description("Causes drag operations to copy nodes rather than move (defaults to false).")] public virtual bool Copy { get { object obj = this.ViewState["Copy"]; return (obj == null) ? false : (bool)obj; } set { this.ViewState["Copy"] = value; } } /// <summary> /// /// </summary> [Meta] [ConfigOption("allowDup")] [Category("6. MultiSelect")] [DefaultValue(false)] [Description("")] public virtual bool AllowDuplicates { get { object obj = this.ViewState["AllowDuplicates"]; return (obj == null) ? false : (bool)obj; } set { this.ViewState["AllowDuplicates"] = value; } } /// <summary> /// /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(false)] [Description("")] public virtual bool AllowTrash { get { object obj = this.ViewState["AllowTrash"]; return (obj == null) ? false : (bool)obj; } set { this.ViewState["AllowTrash"] = value; } } /// <summary> /// The title text to display in the panel header (defaults to '') /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("The title text to display in the panel header (defaults to '')")] public virtual string Legend { get { return (string)this.ViewState["Legend"] ?? ""; } set { this.ViewState["Legend"] = value; } } /// <summary> /// The string used to delimit between items when set or returned as a string of values /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(",")] [Description("The string used to delimit between items when set or returned as a string of values")] public virtual string Delimiter { get { return (string)this.ViewState["Delimiter"] ?? ","; } set { this.ViewState["Delimiter"] = value; } } /// <summary> /// The ddgroup name(s) for the View's DragZone (defaults to undefined). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("The ddgroup name(s) for the View's DragZone (defaults to undefined).")] public virtual string DragGroup { get { return (string)this.ViewState["DragGroup"] ?? ""; } set { this.ViewState["DragGroup"] = value; } } /// <summary> /// The ddgroup name(s) for the View's DropZone (defaults to undefined). /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("The ddgroup name(s) for the View's DropZone (defaults to undefined).")] public virtual string DropGroup { get { return (string)this.ViewState["DropGroup"] ?? ""; } set { this.ViewState["DropGroup"] = value; } } /// <summary> /// /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(false)] [Description("")] public virtual bool AppendOnly { get { object obj = this.ViewState["AppendOnly"]; return (obj == null) ? false : (bool)obj; } set { this.ViewState["AppendOnly"] = value; } } /// <summary> /// /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue("")] [Description("")] public virtual string SortField { get { return (string)this.ViewState["SortField"] ?? ""; } set { this.ViewState["SortField"] = value; } } /// <summary> /// /// </summary> [Meta] [ConfigOption(JsonMode.ToLower)] [DefaultValue(SortDirection.ASC)] [NotifyParentProperty(true)] [Description("")] public SortDirection Direction { get { object obj = this.ViewState["Direction"]; return (obj == null) ? SortDirection.ASC : (SortDirection)obj; } set { this.ViewState["Direction"] = value; } } /// <summary> /// True to submit text of selected items /// </summary> [Meta] [ConfigOption] [Category("6. MultiSelect")] [DefaultValue(true)] [Description("True to submit text of selected items")] public virtual bool SubmitText { get {
[ " object obj = this.ViewState[\"SubmitText\"];" ]
1,411
lcc
csharp
null
211036deb12c17fbe2d6904e590bcf927cced0a233eb0c78
/** * this file is part of Voxels * * Voxels is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Voxels is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Voxels. If not, see <http://www.gnu.org/licenses/>. */ package org.voxels; import java.nio.FloatBuffer; /** @author jacob */ public final class RenderingStream { private static class MatrixNode { public final Matrix mat; public MatrixNode next; public MatrixNode() { this.mat = Matrix.allocate(Matrix.IDENTITY); this.next = null; } } private static MatrixNode[] freeMatrixHead = new MatrixNode[] { null }; private static void freeMatrix(final MatrixNode m) { synchronized(freeMatrixHead) { m.next = freeMatrixHead[0]; freeMatrixHead[0] = m; } } private static MatrixNode allocMatrix() { synchronized(freeMatrixHead) { MatrixNode retval = freeMatrixHead[0]; if(retval != null) { freeMatrixHead[0] = retval.next; retval.next = null; Matrix.set(retval.mat, Matrix.IDENTITY); return retval; } } return new MatrixNode(); } /** if <code>RenderingStream</code> should use vertex arrays and the texture * atlas */ public static boolean USE_VERTEX_ARRAY = true; private static final TextureAtlas.TextureHandle whiteTexture = TextureAtlas.addImage(new Image(Color.V(1.0f))); /** * */ public static final TextureAtlas.TextureHandle NO_TEXTURE = null; private RenderingStream next = null; private static final RenderingStream[] pool = new RenderingStream[] { null }; public static RenderingStream allocate() { synchronized(pool) { if(pool[0] == null) return new RenderingStream(); RenderingStream retval = pool[0]; pool[0] = retval.next; retval.clear(); return retval; } } public static void free(final RenderingStream rs) { if(rs == null) return; synchronized(pool) { rs.next = pool[0]; pool[0] = rs; } } private static float[] expandArray(final float[] array, final int newSize) { float[] retval = new float[newSize]; if(array != null) System.arraycopy(array, 0, retval, 0, array.length); return retval; } // private static TextureAtlas.TextureHandle[] // expandArray(final TextureAtlas.TextureHandle[] array, final int newSize) // { // TextureAtlas.TextureHandle[] retval = new // TextureAtlas.TextureHandle[newSize]; // System.arraycopy(array, 0, retval, 0, array.length); // return retval; // } private final float[][] vertexArray = new float[hashPrime][]; private final float[][] colorArray = new float[hashPrime][]; private final float[][] texCoordArray = new float[hashPrime][]; private final float[][] transformedTexCoordArray = new float[hashPrime][]; private static final int hashPrime = 8191; private final TextureAtlas.TextureHandle[] textureArray = new TextureAtlas.TextureHandle[hashPrime]; private final int[] trianglesUsed = new int[hashPrime]; private final int[] trianglesAllocated = new int[hashPrime]; private MatrixNode matrixStack = null; private int trianglePoint = -1; private TextureAtlas.TextureHandle currentTexture = null; private int currentTextureHash; public RenderingStream clear() { for(int i = 0; i < hashPrime; i++) this.trianglesUsed[i] = 0; this.next = null; while(this.matrixStack != null) { MatrixNode node = this.matrixStack; this.matrixStack = node.next; freeMatrix(node); } this.matrixStack = allocMatrix(); this.matrixStack.next = null; this.trianglePoint = -1; this.currentTexture = null; return this; } /** * */ private RenderingStream() { for(int i = 0; i < hashPrime; i++) this.trianglesUsed[i] = 0; this.next = null; this.matrixStack = allocMatrix(); this.matrixStack.next = null; this.trianglePoint = -1; } public RenderingStream beginTriangle(final TextureAtlas.TextureHandle texture) { TextureAtlas.TextureHandle testTexture = texture; if(testTexture == NO_TEXTURE) testTexture = whiteTexture; if(this.currentTexture != testTexture) { this.currentTexture = testTexture; this.currentTextureHash = this.currentTexture.hashCode() % hashPrime; if(this.currentTextureHash < 0) this.currentTextureHash += hashPrime; if(this.textureArray[this.currentTextureHash] != null && this.textureArray[this.currentTextureHash] != this.currentTexture) throw new RuntimeException("RenderingStream texture hash collision : " + this.currentTexture.hashCode() + " collides with " + this.textureArray[this.currentTextureHash].hashCode()); this.textureArray[this.currentTextureHash] = this.currentTexture; } if(this.trianglePoint >= 0) throw new IllegalStateException("beginTriangle called twice without endTriangle call in between"); this.trianglePoint = 0; if(this.trianglesUsed[this.currentTextureHash] >= this.trianglesAllocated[this.currentTextureHash] / (3 * 3)) { this.trianglesAllocated[this.currentTextureHash] += 256; int newSize = this.trianglesAllocated[this.currentTextureHash]; this.vertexArray[this.currentTextureHash] = expandArray(this.vertexArray[this.currentTextureHash], newSize * 3 * 3); this.colorArray[this.currentTextureHash] = expandArray(this.colorArray[this.currentTextureHash], newSize * 4 * 3); this.texCoordArray[this.currentTextureHash] = expandArray(this.texCoordArray[this.currentTextureHash], newSize * 2 * 3); this.transformedTexCoordArray[this.currentTextureHash] = expandArray(this.transformedTexCoordArray[this.currentTextureHash], newSize * 2 * 3); } return this; } public RenderingStream endTriangle() { if(this.trianglePoint != 3) { if(this.trianglePoint == -1) throw new IllegalStateException("endTriangle called without beginTriangle call before"); throw new IllegalStateException("endTriangle called without three vertex calls before"); } this.trianglePoint = -1; this.trianglesUsed[this.currentTextureHash]++; return this; } private Vector vertex_t1 = Vector.allocate(); public RenderingStream vertex(final float x, final float y, final float z, final float u, final float v, final float r, final float g, final float b, final float a) { if(this.trianglePoint == -1) throw new IllegalStateException("vertex called without beginTriangle call before"); if(this.trianglePoint >= 3) throw new IllegalStateException("missing endTriangle call before"); Vector p = this.matrixStack.mat.apply(this.vertex_t1, Vector.set(this.vertex_t1, x, y, z)); int vi = (this.trianglePoint + 3 * this.trianglesUsed[this.currentTextureHash]) * 3; int ci = (this.trianglePoint + 3 * this.trianglesUsed[this.currentTextureHash]) * 4; int ti = (this.trianglePoint + 3 * this.trianglesUsed[this.currentTextureHash]) * 2; this.trianglePoint++; this.colorArray[this.currentTextureHash][ci++] = r; this.colorArray[this.currentTextureHash][ci++] = g; this.colorArray[this.currentTextureHash][ci++] = b; this.colorArray[this.currentTextureHash][ci] = a; this.vertexArray[this.currentTextureHash][vi++] = p.getX(); this.vertexArray[this.currentTextureHash][vi++] = p.getY(); this.vertexArray[this.currentTextureHash][vi] = p.getZ(); this.texCoordArray[this.currentTextureHash][ti++] = u; this.texCoordArray[this.currentTextureHash][ti] = v; return this; } public RenderingStream vertex(final Vector p, final float u, final float v, final float r, final float g, final float b, final float a) { return vertex(p.getX(), p.getY(), p.getZ(), u, v, r, g, b, a); } public RenderingStream vertex(final Vector p, final float u, final float v, final Color c) { return vertex(p.getX(), p.getY(), p.getZ(), u, v, Color.GetRValue(c) / 255f, Color.GetGValue(c) / 255f, Color.GetBValue(c) / 255f, Color.GetAValue(c) / 255f); } public RenderingStream vertex(final float x, final float y, final float z, final float u, final float v, final Color c) { return vertex(x, y, z, u, v, Color.GetRValue(c) / 255f, Color.GetGValue(c) / 255f, Color.GetBValue(c) / 255f, Color.GetAValue(c) / 255f); } /** insert a new rectangle from &lt;<code>x1</code>, <code>y1</code>, 0&gt; * to &lt;<code>x2</code>, <code>y2</code>, 0&gt; * * @param x1 * the first point's x coordinate * @param y1 * the first point's y coordinate * @param x2 * the second point's x coordinate * @param y2 * the second point's y coordinate * @param u1 * the first point's u coordinate * @param v1 * the first point's v coordinate * @param u2 * the second point's u coordinate * @param v2 * the second point's v coordinate * @param color * the new rectangle's color * @param texture * the texture or <code>Polygon.NO_TEXTURE</code> * @return <code>this</code> */ public RenderingStream addRect(final float x1, final float y1, final float x2, final float y2, final float u1, final float v1, final float u2, final float v2, final Color color, final TextureAtlas.TextureHandle texture) { beginTriangle(texture); vertex(x1, y1, 0, u1, v1, color); vertex(x2, y1, 0, u2, v1, color); vertex(x2, y2, 0, u2, v2, color); endTriangle(); beginTriangle(texture); vertex(x2, y2, 0, u2, v2, color); vertex(x1, y2, 0, u1, v2, color); vertex(x1, y1, 0, u1, v1, color); endTriangle(); return this; } /** @return the current matrix */ public Matrix getMatrix() { return this.matrixStack.mat; } /** @return this */ public RenderingStream pushMatrixStack() { Matrix oldMat = this.matrixStack.mat; MatrixNode newNode = allocMatrix(); Matrix.set(newNode.mat, oldMat); newNode.next = this.matrixStack; this.matrixStack = newNode; return this; } /** @param mat * the matrix to set to * @return this */ public RenderingStream setMatrix(final Matrix mat) { if(mat == null) throw new NullPointerException(); Matrix.set(this.matrixStack.mat, mat); return this; } /** @param mat * the matrix to concat to * @return this */ public RenderingStream concatMatrix(final Matrix mat) { if(mat == null) throw new NullPointerException(); mat.concat(this.matrixStack.mat, this.matrixStack.mat); return this; } /** @return this */ public RenderingStream popMatrixStack() { if(this.matrixStack.next == null) throw new IllegalStateException("can not pop the last matrix off the stack"); MatrixNode node = this.matrixStack; this.matrixStack = this.matrixStack.next; freeMatrix(node); return this; } /** @param rs * the rendering stream * @return <code>this</code> */ public RenderingStream add(final RenderingStream rs) { if(rs == null) throw new NullPointerException(); assert rs != this; for(int textureHash = 0; textureHash < hashPrime; textureHash++) { for(int tri = 0, vi = 0, ci = 0, ti = 0; tri < rs.trianglesUsed[textureHash]; tri++) { beginTriangle(rs.textureArray[textureHash]); for(int i = 0; i < 3; i++) { float x = rs.vertexArray[textureHash][vi++]; float y = rs.vertexArray[textureHash][vi++]; float z = rs.vertexArray[textureHash][vi++]; float u = rs.texCoordArray[textureHash][ti++]; float v = rs.texCoordArray[textureHash][ti++]; float r = rs.colorArray[textureHash][ci++]; float g = rs.colorArray[textureHash][ci++]; float b = rs.colorArray[textureHash][ci++]; float a = rs.colorArray[textureHash][ci++]; vertex(x, y, z, u, v, r, g, b, a); } endTriangle(); } } return this; } private FloatBuffer vertexBuffer = null; private FloatBuffer texCoordBuffer = null; private FloatBuffer colorBuffer = null; private FloatBuffer checkBufferLength(final FloatBuffer origBuffer, final int minLength) { if(origBuffer == null || origBuffer.capacity() < minLength) return Main.platform.createFloatBuffer(minLength); return origBuffer; } /** @return this */ public RenderingStream render() { if(this.trianglePoint != -1) throw new IllegalStateException("render called between beginTriangle and endTriangle"); if(USE_VERTEX_ARRAY) { Main.opengl.glEnableClientState(Main.opengl.GL_COLOR_ARRAY()); Main.opengl.glEnableClientState(Main.opengl.GL_TEXTURE_COORD_ARRAY()); Main.opengl.glEnableClientState(Main.opengl.GL_VERTEX_ARRAY()); for(int textureHash = 0; textureHash < hashPrime; textureHash++) { if(this.trianglesUsed[textureHash] <= 0) continue; if(!this.textureArray[textureHash].getImage().isSelected()) { this.textureArray[textureHash].getImage().selectTexture(); } this.vertexBuffer = checkBufferLength(this.vertexBuffer, this.vertexArray[textureHash].length); this.vertexBuffer.clear(); this.vertexBuffer.put(this.vertexArray[textureHash], 0, this.trianglesUsed[textureHash] * 3 * 3); this.vertexBuffer.flip(); this.texCoordBuffer = checkBufferLength(this.texCoordBuffer, this.texCoordArray[textureHash].length); this.texCoordBuffer.clear(); this.texCoordBuffer.put(this.texCoordArray[textureHash], 0, this.trianglesUsed[textureHash] * 2 * 3); this.texCoordBuffer.flip(); this.colorBuffer = checkBufferLength(this.colorBuffer, this.colorArray[textureHash].length); this.colorBuffer.clear(); this.colorBuffer.put(this.colorArray[textureHash], 0, this.trianglesUsed[textureHash] * 4 * 3); this.colorBuffer.flip(); Main.opengl.glVertexPointer(this.vertexBuffer); Main.opengl.glTexCoordPointer(this.texCoordBuffer); Main.opengl.glColorPointer(this.colorBuffer); Main.opengl.glDrawArrays(Main.opengl.GL_TRIANGLES(), 0, this.trianglesUsed[textureHash] * 3); } Main.opengl.glDisableClientState(Main.opengl.GL_COLOR_ARRAY()); Main.opengl.glDisableClientState(Main.opengl.GL_TEXTURE_COORD_ARRAY()); Main.opengl.glDisableClientState(Main.opengl.GL_VERTEX_ARRAY()); } else { for(int textureHash = 0; textureHash < hashPrime; textureHash++) { boolean insideBeginEnd = false;
[ " int ti = 0, ci = 0, vi = 0;" ]
1,502
lcc
java
null
374f798258a61ee74e40065b162fa268f1abb4cffaf4ed85
# lint-amnesty, pylint: disable=missing-module-docstring import json import logging import sys from functools import wraps import calc import crum from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpResponseServerError from django.views.decorators.csrf import ensure_csrf_cookie, requires_csrf_token from django.views.defaults import server_error from django.shortcuts import redirect from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from lms.djangoapps.courseware.access import has_access from lms.djangoapps.courseware.masquerade import setup_masquerade from openedx.core.djangoapps.schedules.utils import reset_self_paced_schedule from openedx.features.course_experience.utils import dates_banner_should_display from common.djangoapps.track import views as track_views from common.djangoapps.edxmako.shortcuts import render_to_response from common.djangoapps.student.roles import GlobalStaff log = logging.getLogger(__name__) def ensure_valid_course_key(view_func): """ This decorator should only be used with views which have argument course_key_string (studio) or course_id (lms). If course_key_string (studio) or course_id (lms) is not valid raise 404. """ @wraps(view_func) def inner(request, *args, **kwargs): course_key = kwargs.get('course_key_string') or kwargs.get('course_id') if course_key is not None: try: CourseKey.from_string(course_key) except InvalidKeyError: raise Http404 # lint-amnesty, pylint: disable=raise-missing-from response = view_func(request, *args, **kwargs) return response return inner def ensure_valid_usage_key(view_func): """ This decorator should only be used with views which have argument usage_key_string. If usage_key_string is not valid raise 404. """ @wraps(view_func) def inner(request, *args, **kwargs): usage_key = kwargs.get('usage_key_string') if usage_key is not None: try: UsageKey.from_string(usage_key) except InvalidKeyError: raise Http404 # lint-amnesty, pylint: disable=raise-missing-from response = view_func(request, *args, **kwargs) return response return inner def require_global_staff(func): """View decorator that requires that the user have global staff permissions. """ @wraps(func) def wrapped(request, *args, **kwargs): if GlobalStaff().has_user(request.user): return func(request, *args, **kwargs) else: return HttpResponseForbidden( "Must be {platform_name} staff to perform this action.".format( platform_name=settings.PLATFORM_NAME ) ) return login_required(wrapped) def fix_crum_request(func): """ A decorator that ensures that the 'crum' package (a middleware that stores and fetches the current request in thread-local storage) can correctly fetch the current request. Under certain conditions, the current request cannot be fetched by crum (e.g.: when HTTP errors are raised in our views via 'raise Http404', et. al.). This decorator manually sets the current request for crum if it cannot be fetched. """ @wraps(func) def wrapper(request, *args, **kwargs): if not crum.get_current_request(): crum.set_current_request(request=request) return func(request, *args, **kwargs) return wrapper @requires_csrf_token def jsonable_server_error(request, template_name='500.html'): """ 500 error handler that serves JSON on an AJAX request, and proxies to the Django default `server_error` view otherwise. """ if request.is_ajax(): msg = {"error": "The edX servers encountered an error"} return HttpResponseServerError(json.dumps(msg)) else: return server_error(request, template_name=template_name) def handle_500(template_path, context=None, test_func=None): """ Decorator for view specific 500 error handling. Custom handling will be skipped only if test_func is passed and it returns False Usage: @handle_500( template_path='certificates/server-error.html', context={'error-info': 'Internal Server Error'}, test_func=lambda request: request.GET.get('preview', None) ) def my_view(request): # Any unhandled exception in this view would be handled by the handle_500 decorator # ... """ def decorator(func): """ Decorator to render custom html template in case of uncaught exception in wrapped function """ @wraps(func) def inner(request, *args, **kwargs): """ Execute the function in try..except block and return custom server-error page in case of unhandled exception """ try: return func(request, *args, **kwargs) except Exception: # pylint: disable=broad-except if settings.DEBUG: # lint-amnesty, pylint: disable=no-else-raise # In debug mode let django process the 500 errors and display debug info for the developer raise elif test_func is None or test_func(request): # Display custom 500 page if either # 1. test_func is None (meaning nothing to test) # 2. or test_func(request) returns True log.exception("Error in django view.") return render_to_response(template_path, context) else: # Do not show custom 500 error when test fails raise return inner return decorator def calculate(request): ''' Calculator in footer of every page. ''' equation = request.GET['equation'] try: result = calc.evaluator({}, {}, equation) except: # lint-amnesty, pylint: disable=bare-except event = {'error': list(map(str, sys.exc_info())), 'equation': equation} track_views.server_track(request, 'error:calc', event, page='calc') return HttpResponse(json.dumps({'result': 'Invalid syntax'})) # lint-amnesty, pylint: disable=http-response-with-json-dumps return HttpResponse(json.dumps({'result': str(result)})) # lint-amnesty, pylint: disable=http-response-with-json-dumps def info(request): """ Info page (link from main header) """ return render_to_response("info.html", {}) def add_p3p_header(view_func): """ This decorator should only be used with views which may be displayed through the iframe. It adds additional headers to response and therefore gives IE browsers an ability to save cookies inside the iframe Details: http://blogs.msdn.com/b/ieinternals/archive/2013/09/17/simple-introduction-to-p3p-cookie-blocking-frame.aspx http://stackoverflow.com/questions/8048306/what-is-the-most-broad-p3p-header-that-will-work-with-ie """ @wraps(view_func) def inner(request, *args, **kwargs): """ Helper function """ response = view_func(request, *args, **kwargs) response['P3P'] = settings.P3P_HEADER return response return inner @ensure_csrf_cookie def reset_course_deadlines(request): """ Set the start_date of a schedule to today, which in turn will adjust due dates for sequentials belonging to a self paced course IMPORTANT NOTE: If updates are happening to the logic here, ALSO UPDATE the `reset_course_deadlines` function in openedx/features/course_experience/api/v1/views.py as well. """ course_key = CourseKey.from_string(request.POST.get('course_id')) _course_masquerade, user = setup_masquerade( request, course_key, has_access(request.user, 'staff', course_key) ) missed_deadlines, missed_gated_content = dates_banner_should_display(course_key, user) if missed_deadlines and not missed_gated_content: reset_self_paced_schedule(user, course_key) referrer = request.META.get('HTTP_REFERER') return redirect(referrer) if referrer else HttpResponse() def expose_header(header, response): """ Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value """ exposedHeaders = response.get('Access-Control-Expose-Headers', '')
[ " exposedHeaders += f', {header}' if exposedHeaders else header" ]
796
lcc
python
null
7ffdfbe9a1f219ca6e4ba947f389a17ae4f1378b03a7c921
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // <http://www.mysql.com/about/legal/licensing/foss-exception.html>. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// <summary> /// Summary description for MySqlPool. /// </summary> internal sealed class MySqlPool { private List<Driver> inUsePool; private Queue<Driver> idlePool; private MySqlConnectionStringBuilder settings; private uint minSize; private uint maxSize; private ProcedureCache procedureCache; private bool beingCleared; private int available; private AutoResetEvent autoEvent; private void EnqueueIdle(Driver driver) { driver.IdleSince = DateTime.Now; idlePool.Enqueue(driver); } public MySqlPool(MySqlConnectionStringBuilder settings) { minSize = settings.MinimumPoolSize; maxSize = settings.MaximumPoolSize; available = (int)maxSize; autoEvent = new AutoResetEvent(false); if (minSize > maxSize) minSize = maxSize; this.settings = settings; inUsePool = new List<Driver>((int)maxSize); idlePool = new Queue<Driver>((int)maxSize); // prepopulate the idle pool to minSize for (int i = 0; i < minSize; i++) EnqueueIdle(CreateNewPooledConnection()); procedureCache = new ProcedureCache((int)settings.ProcedureCacheSize); } #region Properties public MySqlConnectionStringBuilder Settings { get { return settings; } set { settings = value; } } public ProcedureCache ProcedureCache { get { return procedureCache; } } /// <summary> /// It is assumed that this property will only be used from inside an active /// lock. /// </summary> private bool HasIdleConnections { get { return idlePool.Count > 0; } } private int NumConnections { get { return idlePool.Count + inUsePool.Count; } } /// <summary> /// Indicates whether this pool is being cleared. /// </summary> public bool BeingCleared { get { return beingCleared; } } internal Hashtable ServerProperties { get; set; } #endregion /// <summary> /// It is assumed that this method is only called from inside an active lock. /// </summary> private Driver GetPooledConnection() { Driver driver = null; // if we don't have an idle connection but we have room for a new // one, then create it here. lock ((idlePool as ICollection).SyncRoot) { if (HasIdleConnections) driver = idlePool.Dequeue(); } // Obey the connection timeout if (driver != null) { try { driver.ResetTimeout((int)Settings.ConnectionTimeout * 1000); } catch (Exception) { driver.Close(); driver = null; } } if (driver != null) { // first check to see that the server is still alive if (!driver.Ping()) { driver.Close(); driver = null; } else if (settings.ConnectionReset) // if the user asks us to ping/reset pooled connections // do so now driver.Reset(); } if (driver == null) driver = CreateNewPooledConnection(); Debug.Assert(driver != null); lock ((inUsePool as ICollection).SyncRoot) { inUsePool.Add(driver); } return driver; } /// <summary> /// It is assumed that this method is only called from inside an active lock. /// </summary> private Driver CreateNewPooledConnection() { Debug.Assert((maxSize - NumConnections) > 0, "Pool out of sync."); Driver driver = Driver.Create(settings); driver.Pool = this; return driver; } public void ReleaseConnection(Driver driver) { lock ((inUsePool as ICollection).SyncRoot) { if (inUsePool.Contains(driver)) inUsePool.Remove(driver); } if (driver.ConnectionLifetimeExpired() || beingCleared) { driver.Close(); Debug.Assert(!idlePool.Contains(driver)); } else { lock ((idlePool as ICollection).SyncRoot) { EnqueueIdle(driver); } } Interlocked.Increment(ref available); autoEvent.Set(); } /// <summary> /// Removes a connection from the in use pool. The only situations where this method /// would be called are when a connection that is in use gets some type of fatal exception /// or when the connection is being returned to the pool and it's too old to be /// returned. /// </summary> /// <param name="driver"></param> public void RemoveConnection(Driver driver) { lock ((inUsePool as ICollection).SyncRoot) { if (inUsePool.Contains(driver)) { inUsePool.Remove(driver); Interlocked.Increment(ref available); autoEvent.Set(); } } // if we are being cleared and we are out of connections then have // the manager destroy us. if (beingCleared && NumConnections == 0) MySqlPoolManager.RemoveClearedPool(this); } private Driver TryToGetDriver() { int count = Interlocked.Decrement(ref available); if (count < 0) { Interlocked.Increment(ref available); return null; } try { Driver driver = GetPooledConnection(); return driver; } catch (Exception ex) { MySqlTrace.LogError(-1, ex.Message); Interlocked.Increment(ref available); throw; } } public Driver GetConnection() { int fullTimeOut = (int)settings.ConnectionTimeout * 1000; int timeOut = fullTimeOut; DateTime start = DateTime.Now; while (timeOut > 0) { Driver driver = TryToGetDriver(); if (driver != null) return driver; // We have no tickets right now, lets wait for one. if (!autoEvent.WaitOne(timeOut, false)) break; timeOut = fullTimeOut - (int)DateTime.Now.Subtract(start).TotalMilliseconds; } throw new MySqlException(Resources.TimeoutGettingConnection); } /// <summary> /// Clears this pool of all idle connections and marks this pool and being cleared /// so all other connections are closed when they are returned. /// </summary> internal void Clear() { lock ((idlePool as ICollection).SyncRoot) { // first, mark ourselves as being cleared beingCleared = true; // then we remove all connections sitting in the idle pool while (idlePool.Count > 0) { Driver d = idlePool.Dequeue(); d.Close(); } // there is nothing left to do here. Now we just wait for all // in use connections to be returned to the pool. When they are // they will be closed. When the last one is closed, the pool will // be destroyed. } } /// <summary> /// Remove expired drivers from the idle pool /// </summary> /// <returns></returns> /// <remarks> /// Closing driver is a potentially lengthy operation involving network /// IO. Therefore we do not close expired drivers while holding /// idlePool.SyncRoot lock. We just remove the old drivers from the idle /// queue and return them to the caller. The caller will need to close /// them (or let GC close them) /// </remarks> internal List<Driver> RemoveOldIdleConnections() { List<Driver> oldDrivers = new List<Driver>(); DateTime now = DateTime.Now; lock ((idlePool as ICollection).SyncRoot) { // The drivers appear to be ordered by their age, i.e it is // sufficient to remove them until the first element is not // too old. while(idlePool.Count > minSize) {
[ " Driver d = idlePool.Peek();" ]
1,070
lcc
csharp
null
07673406347dbc81c33565aadcb582257991cdab25eab669
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2019-2021 Pyresample developers # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. """Area config handling and creation utilities.""" import io import logging import math import os import pathlib import warnings from typing import Any, Union import numpy as np import yaml from pyproj import Proj, Transformer from pyproj.crs import CRS, CRSError from pyresample.utils import proj4_str_to_dict try: from xarray import DataArray except ImportError: class DataArray(object): """Stand-in for DataArray for holding units information.""" def __init__(self, data, attrs=None): """Initialize 'attrs' and 'data' properties.""" self.attrs = attrs or {} self.data = np.array(data) def __getitem__(self, item): """Get a subset of the data contained in a DataArray.""" return DataArray(self.data[item], attrs=self.attrs) def __getattr__(self, item): """Get metadata property from 'attrs'.""" return self.attrs[item] def __len__(self): """Get size of the data.""" return len(self.data) class AreaNotFound(KeyError): """Exception raised when specified are is no found in file.""" def load_area(area_file_name, *regions): """Load area(s) from area file. Parameters ---------- area_file_name : str, pathlib.Path, stream, or list thereof List of paths or streams. Any str or pathlib.Path will be interpreted as a path to a file. Any stream will be interpreted as containing a yaml definition file. To read directly from a string, use :func:`load_area_from_string`. regions : str argument list Regions to parse. If no regions are specified all regions in the file are returned Returns ------- area_defs : AreaDefinition or list If one area name is specified a single AreaDefinition object is returned. If several area names are specified a list of AreaDefinition objects is returned Raises ------ AreaNotFound: If a specified area name is not found """ area_list = parse_area_file(area_file_name, *regions) if len(area_list) == 1: return area_list[0] return area_list def load_area_from_string(area_strs, *regions): """Load area(s) from area strings. Like :func:`~pyresample.area_config.load_area`, but load from string directly. Parameters ---------- area_strs : str or List[str] Strings containing yaml definitions. regions : str Regions to parse. Returns ------- area_defs : AreaDefinition or list If one area name is specified a single AreaDefinition object is returned. If several area names are specified a list of AreaDefinition objects is returned """ if isinstance(area_strs, str): area_strs = [area_strs] return load_area([io.StringIO(area_str) for area_str in area_strs], *regions) def parse_area_file(area_file_name, *regions): """Parse area information from area file. Parameters ----------- area_file_name : str or list One or more paths to area definition files regions : str argument list Regions to parse. If no regions are specified all regions in the file are returned Returns ------- area_defs : list List of AreaDefinition objects Raises ------ AreaNotFound: If a specified area is not found """ try: return _parse_yaml_area_file(area_file_name, *regions) except (yaml.scanner.ScannerError, yaml.parser.ParserError): return _parse_legacy_area_file(area_file_name, *regions) def _read_yaml_area_file_content(area_file_name): """Read one or more area files in to a single dict object.""" from pyresample.utils import recursive_dict_update if isinstance(area_file_name, (str, pathlib.Path)): area_file_name = [area_file_name] area_dict = {} for area_file_obj in area_file_name: if isinstance(area_file_obj, io.IOBase): # already a stream tmp_dict = yaml.safe_load(area_file_obj) else: # hopefully a path to a file, but in the past a yaml string could # be passed directly, assume any string with a newline must be # a yaml file and not a path if isinstance(area_file_obj, str) and "\n" in area_file_obj: warnings.warn("It looks like you passed a YAML string " "directly. This is deprecated since pyresample " "1.14.1, please use load_area_from_string or " "pass a stream or a path to a file instead", DeprecationWarning) tmp_dict = yaml.safe_load(area_file_obj) else: with open(area_file_obj) as area_file_obj: tmp_dict = yaml.safe_load(area_file_obj) area_dict = recursive_dict_update(area_dict, tmp_dict) return area_dict def _parse_yaml_area_file(area_file_name, *regions): """Parse area information from a yaml area file. Args: area_file_name: filename, file-like object, yaml string, or list of these. The result of loading multiple area files is the combination of all the files, using the first file as the "base", replacing things after that. """ area_dict = _read_yaml_area_file_content(area_file_name) area_list = regions or area_dict.keys() res = [] for area_name in area_list: params = area_dict.get(area_name) if params is None: raise AreaNotFound('Area "{0}" not found in file "{1}"'.format(area_name, area_file_name)) params.setdefault('area_id', area_name) # Optional arguments. params['shape'] = _capture_subarguments(params, 'shape', ['height', 'width']) params['upper_left_extent'] = _capture_subarguments(params, 'upper_left_extent', ['upper_left_extent', 'x', 'y', 'units']) params['center'] = _capture_subarguments(params, 'center', ['center', 'x', 'y', 'units']) params['area_extent'] = _capture_subarguments(params, 'area_extent', ['area_extent', 'lower_left_xy', 'upper_right_xy', 'units']) params['resolution'] = _capture_subarguments(params, 'resolution', ['resolution', 'dx', 'dy', 'units']) params['radius'] = _capture_subarguments(params, 'radius', ['radius', 'dx', 'dy', 'units']) params['rotation'] = _capture_subarguments(params, 'rotation', ['rotation', 'units']) res.append(create_area_def(**params)) return res def _capture_subarguments(params, arg_name, sub_arg_list): """Capture :func:`~pyresample.utils.create_area_def` sub-arguments (i.e. units, height, dx, etc) from a yaml file. Example: resolution: dx: 11 dy: 22 units: meters # returns DataArray((11, 22), attrs={'units': 'meters}) """ # Check if argument is in yaml. argument = params.get(arg_name) if not isinstance(argument, dict): return argument argument_keys = argument.keys() for sub_arg in argument_keys: # Verify that provided sub-arguments are valid. if sub_arg not in sub_arg_list: raise ValueError('Invalid area definition: {0} is not a valid sub-argument for {1}'.format(sub_arg, arg_name)) elif arg_name in argument_keys: # If the arg_name is provided as a sub_arg, then it contains all the data and does not need other sub_args. if sub_arg != arg_name and sub_arg != 'units': raise ValueError('Invalid area definition: {0} has too many sub-arguments: Both {0} and {1} were ' 'specified.'. format(arg_name, sub_arg)) # If the arg_name is provided, it's expected that units is also provided. elif 'units' not in argument_keys: raise ValueError('Invalid area definition: {0} has the sub-argument {0} without units'.format(arg_name)) units = argument.pop('units', None) list_of_values = argument.pop(arg_name, []) for sub_arg in sub_arg_list: sub_arg_value = argument.get(sub_arg) # Don't append units to the argument. if sub_arg_value is not None: if sub_arg in ('lower_left_xy', 'upper_right_xy') and isinstance(sub_arg_value, list): list_of_values.extend(sub_arg_value) else: list_of_values.append(sub_arg_value) # If units are provided, convert to xarray. if units is not None: return DataArray(list_of_values, attrs={'units': units}) return list_of_values def _read_legacy_area_file_lines(area_file_name): if isinstance(area_file_name, str): area_file_name = [area_file_name] for area_file_obj in area_file_name: if (isinstance(area_file_obj, str) and not os.path.isfile(area_file_obj)): # file content string for line in area_file_obj.splitlines(): yield line continue elif isinstance(area_file_obj, str): # filename with open(area_file_obj, 'r') as area_file: for line in area_file.readlines(): yield line def _parse_legacy_area_file(area_file_name, *regions): """Parse area information from a legacy area file.""" area_file = _read_legacy_area_file_lines(area_file_name) area_list = list(regions) if not area_list: select_all_areas = True area_defs = [] else: select_all_areas = False area_defs = [None for i in area_list] # Extract area from file in_area = False for line in area_file: if not in_area: if 'REGION' in line and not line.strip().startswith('#'): area_id = line.replace('REGION:', ''). \ replace('{', '').strip() if area_id in area_list or select_all_areas: in_area = True area_content = '' elif '};' in line: in_area = False try: if select_all_areas: area_defs.append(_create_area(area_id, area_content)) else: area_defs[area_list.index(area_id)] = _create_area(area_id, area_content) except KeyError: raise ValueError('Invalid area definition: %s, %s' % (area_id, area_content)) else: area_content += line # Check if all specified areas were found if not select_all_areas: for i, area in enumerate(area_defs): if area is None: raise AreaNotFound('Area "%s" not found in file "%s"' % (area_list[i], area_file_name)) return area_defs def _create_area(area_id, area_content): """Parse area configuration.""" from configobj import ConfigObj config_obj = area_content.replace('{', '').replace('};', '') config_obj = ConfigObj([line.replace(':', '=', 1) for line in config_obj.splitlines()]) config = config_obj.dict() config['REGION'] = area_id try: string_types = basestring except NameError: string_types = str if not isinstance(config['NAME'], string_types): config['NAME'] = ', '.join(config['NAME']) config['XSIZE'] = int(config['XSIZE']) config['YSIZE'] = int(config['YSIZE']) if 'ROTATION' in config.keys(): config['ROTATION'] = float(config['ROTATION']) else: config['ROTATION'] = 0 config['AREA_EXTENT'][0] = config['AREA_EXTENT'][0].replace('(', '') config['AREA_EXTENT'][3] = config['AREA_EXTENT'][3].replace(')', '') for i, val in enumerate(config['AREA_EXTENT']): config['AREA_EXTENT'][i] = float(val) config['PCS_DEF'] = _get_proj4_args(config['PCS_DEF']) return create_area_def(config['REGION'], config['PCS_DEF'], description=config['NAME'], proj_id=config['PCS_ID'], shape=(config['YSIZE'], config['XSIZE']), area_extent=config['AREA_EXTENT'], rotation=config['ROTATION']) def get_area_def(area_id, area_name, proj_id, proj4_args, width, height, area_extent, rotation=0): """Construct AreaDefinition object from arguments. Parameters ----------- area_id : str ID of area area_name :str Description of area proj_id : str ID of projection proj4_args : list, dict, or str Proj4 arguments as list of arguments or string width : int Number of pixel in x dimension height : int Number of pixel in y dimension rotation: float Rotation in degrees (negative is cw) area_extent : list Area extent as a list of ints (LL_x, LL_y, UR_x, UR_y) Returns ------- area_def : object AreaDefinition object """ proj_dict = _get_proj4_args(proj4_args) return create_area_def(area_id, proj_dict, description=area_name, proj_id=proj_id, shape=(height, width), area_extent=area_extent) def _get_proj4_args(proj4_args): """Create dict from proj4 args.""" from pyresample.utils.proj4 import convert_proj_floats if isinstance(proj4_args, str): # float conversion is done in `proj4_str_to_dict` already return proj4_str_to_dict(str(proj4_args)) from configobj import ConfigObj proj_config = ConfigObj(proj4_args) return convert_proj_floats(proj_config.items()) def create_area_def(area_id, projection, width=None, height=None, area_extent=None, shape=None, upper_left_extent=None, center=None, resolution=None, radius=None, units=None, **kwargs): """Create AreaDefinition from whatever information is known. Parameters ---------- area_id : str ID of area projection : pyproj CRS object, dict, str, int, tuple, object Projection parameters. This can be in any format understood by :func:`pyproj.crs.CRS.from_user_input`, such as a pyproj CRS object, proj4 dict, proj4 string, EPSG integer code, or others. description : str, optional Description/name of area. Defaults to area_id proj_id : str, optional ID of projection (deprecated) units : str, optional Units that provided arguments should be interpreted as. This can be one of 'deg', 'degrees', 'meters', 'metres', and any parameter supported by the `cs2cs -lu <https://proj4.org/apps/cs2cs.html#cmdoption-cs2cs-lu>`_ command. Units are determined in the following priority: 1. units expressed with each variable through a DataArray's attrs attribute. 2. units passed to ``units`` 3. units used in ``projection`` 4. meters width : str, optional Number of pixels in the x direction height : str, optional Number of pixels in the y direction area_extent : list, optional Area extent as a list (lower_left_x, lower_left_y, upper_right_x, upper_right_y) shape : list, optional Number of pixels in the y and x direction (height, width) upper_left_extent : list, optional Upper left corner of upper left pixel (x, y) center : list, optional Center of projection (x, y) resolution : list or float, optional Size of pixels: (dx, dy) radius : list or float, optional Length from the center to the edges of the projection (dx, dy) rotation: float, optional rotation in degrees(negative is cw) nprocs : int, optional Number of processor cores to be used lons : numpy array, optional Grid lons lats : numpy array, optional Grid lats optimize_projection: Whether the projection parameters have to be optimized for a DynamicAreaDefinition. Returns ------- AreaDefinition or DynamicAreaDefinition : AreaDefinition or DynamicAreaDefinition If shape and area_extent are found, an AreaDefinition object is returned. If only shape or area_extent can be found, a DynamicAreaDefinition object is returned Raises ------ ValueError: If neither shape nor area_extent could be found Notes ----- * ``resolution`` and ``radius`` can be specified with one value if dx == dy * If ``resolution`` and ``radius`` are provided as angles, center must be given or findable. In such a case, they represent [projection x distance from center[0] to center[0]+dx, projection y distance from center[1] to center[1]+dy] """ description = kwargs.pop('description', area_id) proj_id = kwargs.pop('proj_id', None) # convert EPSG dictionaries to projection string # (hold on to EPSG code as much as possible) if isinstance(projection, dict) and 'EPSG' in projection: projection = "EPSG:{}".format(projection['EPSG']) try: crs = _get_proj_data(projection) p = Proj(crs, preserve_units=True) except (RuntimeError, CRSError): # Assume that an invalid projection will be "fixed" by a dynamic area definition later return _make_area(area_id, description, proj_id, projection, shape, area_extent, **kwargs) # If no units are provided, try to get units used in proj_dict. If still none are provided, use meters. if units is None: units = _get_proj_units(crs) # Allow height and width to be provided for more consistency across functions in pyresample. if height is not None or width is not None: shape = _validate_variable(shape, (height, width), 'shape', ['height', 'width']) # Makes sure list-like objects are list-like, have the right shape, and contain only numbers. center = _verify_list('center', center, 2) radius = _verify_list('radius', radius, 2) upper_left_extent = _verify_list('upper_left_extent', upper_left_extent, 2) resolution = _verify_list('resolution', resolution, 2) shape = _verify_list('shape', shape, 2) area_extent = _verify_list('area_extent', area_extent, 4) # Converts from lat/lon to projection coordinates (x,y) if not in projection coordinates. Returns tuples. center = _convert_units(center, 'center', units, p, crs) upper_left_extent = _convert_units(upper_left_extent, 'upper_left_extent', units, p, crs) if area_extent is not None: # convert area extent, pass as (X, Y) area_extent_ll = area_extent[:2] area_extent_ur = area_extent[2:] area_extent_ll = _convert_units(area_extent_ll, 'area_extent', units, p, crs) area_extent_ur = _convert_units(area_extent_ur, 'area_extent', units, p, crs) area_extent = area_extent_ll + area_extent_ur # Fills in missing information to attempt to create an area definition. if area_extent is None or shape is None: area_extent, shape, resolution = \ _extrapolate_information(area_extent, shape, center, radius, resolution, upper_left_extent, units, p, crs) return _make_area(area_id, description, proj_id, projection, shape, area_extent, resolution=resolution, **kwargs) def _make_area( area_id: str, description: str, proj_id: str, projection: Union[dict, CRS], shape: tuple, area_extent: tuple, **kwargs): """Handle the creation of an area definition for create_area_def.""" from pyresample.geometry import AreaDefinition, DynamicAreaDefinition # Remove arguments that are only for DynamicAreaDefinition. optimize_projection = kwargs.pop('optimize_projection', False) resolution = kwargs.pop('resolution', None) # If enough data is provided, create an AreaDefinition. If only shape or area_extent are found, make a # DynamicAreaDefinition. If not enough information was provided, raise a ValueError. height, width = (None, None) if shape is not None: height, width = shape if None not in (area_extent, shape): return AreaDefinition(area_id, description, proj_id, projection, width, height, area_extent, **kwargs) return DynamicAreaDefinition(area_id=area_id, description=description, projection=projection, width=width, height=height, area_extent=area_extent, rotation=kwargs.get('rotation'), resolution=resolution, optimize_projection=optimize_projection) def _get_proj_data(projection: Any) -> CRS: """Take projection information and returns a proj CRS. Takes projection information in any format understood by :func:`pyproj.crs.CRS.from_user_input`. There is special handling for the "EPSG:XXXX" case where "XXXX" is an EPSG number code. It can be provided as a string `"EPSG:XXXX"` or as a dictionary (when provided via YAML) as `{'EPSG': XXXX}`. If it is passed as a string ("EPSG:XXXX") then the rules of :func:`~pyresample.utils._proj.proj4_str_to_dict` are followed. If a dictionary and pyproj 2.0+ is installed then the string `"EPSG:XXXX"` is passed to ``proj4_str_to_dict``. If pyproj<2.0 is installed then the string ``+init=EPSG:XXXX`` is passed to ``proj4_str_to_dict`` which provides limited information to area config operations. """ if isinstance(projection, dict) and 'EPSG' in projection: projection = "EPSG:{}".format(projection['EPSG']) return CRS.from_user_input(projection) def _get_proj_units(crs): if crs.is_geographic: unit_name = 'degrees' else: unit_name = crs.axis_info[0].unit_name return { 'metre': 'm', 'meter': 'm', 'kilometre': 'km', 'kilometer': 'km', }.get(unit_name, unit_name) def _sign(num): """Return the sign of the number provided. Returns: 1 if number is greater than 0, -1 otherwise """ return -1 if num < 0 else 1 def _round_poles(center, units, p): """Round center to the nearest pole if it is extremely close to said pole. Used to work around floating point precision issues . """ # For a laea projection, this allows for an error of 11 meters around the pole. error = .0001 if 'deg' in units: if abs(abs(center[1]) - 90) < error: center = (center[0], _sign(center[1]) * 90) else: center = p(*center, inverse=True, errcheck=True) if abs(abs(center[1]) - 90) < error: center = (center[0], _sign(center[1]) * 90) center = p(*center, errcheck=True) return center def _distance_from_center_forward( var: tuple, center: tuple, p: Proj): """Convert distances in degrees to projection units.""" # Interprets radius and resolution as distances between latitudes/longitudes. # Since the distance between longitudes and latitudes is not constant in # most projections, there must be reference point to start from. if center is None: center = (0, 0) center_as_angle = p(*center, inverse=True, errcheck=True) pole = 90 # If on a pole, use northern/southern latitude for both height and width. if abs(abs(center_as_angle[1]) - pole) < 1e-3: direction_of_poles = _sign(center_as_angle[1]) var = (center[1] - p(0, center_as_angle[1] - direction_of_poles * abs(var[0]), errcheck=True)[1], center[1] - p(0, center_as_angle[1] - direction_of_poles * abs(var[1]), errcheck=True)[1]) # Uses southern latitude and western longitude if radius is positive. Uses northern latitude and # eastern longitude if radius is negative. else: var = (center[0] - p(center_as_angle[0] - var[0], center_as_angle[1], errcheck=True)[0], center[1] - p(center_as_angle[0], center_as_angle[1] - var[1], errcheck=True)[1]) return var def _convert_units( var, name: str, units: str, p: Proj, crs: CRS, inverse: bool = False, center=None): """Convert units from lon/lat to projection coordinates (meters). If `inverse` it True then the inverse calculation is done. """ if var is None: return None if isinstance(var, DataArray): units = var.units var = tuple(var.data.tolist()) if crs.is_geographic and not ('deg' == units or 'degrees' == units): raise ValueError('latlon/latlong projection cannot take {0} as units: {1}'.format(units, name)) # Check if units are an angle. is_angle = ('deg' == units or 'degrees' == units) if ('deg' in units) and not is_angle: logging.warning('units provided to {0} are incorrect: {1}'.format(name, units)) # Convert from var projection units to projection units given by projection from user. if not is_angle: if units == 'meters' or units == 'metres': units = 'm' if _get_proj_units(crs) != units: tmp_proj_dict = crs.to_dict() tmp_proj_dict['units'] = units transformer = Transformer.from_crs(tmp_proj_dict, p.crs) var = transformer.transform(*var) if name == 'center': var = _round_poles(var, units, p) # Return either degrees or meters depending on if the inverse is true or not. # Don't convert if inverse is True: Want degrees. # Converts list-like from degrees to meters. if is_angle and not inverse: if name in ('radius', 'resolution'): var = _distance_from_center_forward(var, center, p) elif not crs.is_geographic: # only convert to meters # this allows geographic projections to use coordinates outside # normal lon/lat ranges (ex. -90/90) var = p(*var, errcheck=True) # Don't convert if inverse is False: Want meters. elif not is_angle and inverse: # Converts list-like from meters to degrees. var = p(*var, inverse=True, errcheck=True) if name in ['radius', 'resolution']: var = (abs(var[0]), abs(var[1])) return var def _round_shape(shape, radius=None, resolution=None): """Make sure shape is an integer. Rounds down if shape is less than .01 above nearest whole number to handle floating point precision issues. Otherwise the number is round up. """ # Used for area definition to prevent indexing None. if shape is None: return None incorrect_shape = False height, width = shape if abs(width - round(width)) > 1e-8: incorrect_shape = True if width - math.floor(width) >= .01: width = math.ceil(width) width = int(round(width)) if abs(height - round(height)) > 1e-8: incorrect_shape = True if height - math.floor(height) >= .01: height = math.ceil(height) height = int(round(height)) if incorrect_shape: if radius is not None and resolution is not None: new_resolution = (2 * radius[0] / width, 2 * radius[1] / height) logging.warning('shape found from radius and resolution does not contain only ' 'integers: {0}\nRounding shape to {1} and resolution from {2} meters to ' '{3} meters'.format(shape, (height, width), resolution, new_resolution)) else: logging.warning('shape provided does not contain only integers: {0}\n' 'Rounding shape to {1}'.format(shape, (height, width))) return height, width def _validate_variable(var, new_var, var_name, input_list): """Make sure data given by the user does not conflict with itself. If a variable that was given by the user contradicts other data provided, an exception is raised. Example: upper_left_extent is (-10, 10), but area_extent is (-20, -20, 20, 20). """ if var is not None and not np.allclose(np.array(var, dtype=float), np.array(new_var, dtype=float), equal_nan=True): raise ValueError('CONFLICTING DATA: {0} given does not match {0} found from {1}'.format( var_name, ', '.join(input_list)) + ':\ngiven: {0}\nvs\nfound: {1}'.format(var, new_var)) return new_var def _extrapolate_information(area_extent, shape, center, radius, resolution, upper_left_extent, units, p, crs): """Attempt to find shape and area_extent based on data provided. Parameters are used in a specific order to determine area_extent and shape. The area_extent and shape are later used to create an `AreaDefinition`. Providing some parameters may have no effect if other parameters could be used to determine area_extent and shape. The order of the parameters used is: 1. area_extent 2. upper_left_extent and center 3. radius and resolution 4. resolution and shape 5. radius and center 6. upper_left_extent and radius """ # Input unaffected by data below: When area extent is calculated, it's either with # shape (giving you an area definition) or with center/radius/upper_left_extent (which this produces). # Yet output (center/radius/upper_left_extent) is essential for data below. if area_extent is not None: # Function 1-A new_center = ((area_extent[2] + area_extent[0]) / 2, (area_extent[3] + area_extent[1]) / 2) center = _validate_variable(center, new_center, 'center', ['area_extent']) # If radius is given in an angle without center it will raise an exception, and to verify, it must be in meters. radius = _convert_units(radius, 'radius', units, p, crs, center=center) new_radius = ((area_extent[2] - area_extent[0]) / 2, (area_extent[3] - area_extent[1]) / 2) radius = _validate_variable(radius, new_radius, 'radius', ['area_extent']) new_upper_left_extent = (area_extent[0], area_extent[3]) upper_left_extent = _validate_variable( upper_left_extent, new_upper_left_extent, 'upper_left_extent', ['area_extent']) # Output used below, but nowhere else is upper_left_extent made. Thus it should go as early as possible. elif None not in (upper_left_extent, center): # Function 1-B radius = _convert_units(radius, 'radius', units, p, crs, center=center) new_radius = (center[0] - upper_left_extent[0], upper_left_extent[1] - center[1]) radius = _validate_variable(radius, new_radius, 'radius', ['upper_left_extent', 'center']) else: radius = _convert_units(radius, 'radius', units, p, crs, center=center) # Convert resolution to meters if given as an angle. If center is not found, an exception is raised. resolution = _convert_units(resolution, 'resolution', units, p, crs, center=center) # Inputs unaffected by data below: area_extent is not an input. However, output is used below. if radius is not None and resolution is not None: # Function 2-A new_shape = _round_shape((2 * radius[1] / resolution[1], 2 * radius[0] / resolution[0]), radius=radius, resolution=resolution) shape = _validate_variable(shape, new_shape, 'shape', ['radius', 'resolution']) elif resolution is not None and shape is not None: # Function 2-B new_radius = (resolution[0] * shape[1] / 2, resolution[1] * shape[0] / 2) radius = _validate_variable(radius, new_radius, 'radius', ['shape', 'resolution']) # Input determined from above functions, but output does not affect above functions: area_extent can be # used to find center/upper_left_extent which are used to find each other, which is redundant. if center is not None and radius is not None: # Function 1-C new_area_extent = (center[0] - radius[0], center[1] - radius[1], center[0] + radius[0], center[1] + radius[1]) area_extent = _validate_variable(area_extent, new_area_extent, 'area_extent', ['center', 'radius']) elif upper_left_extent is not None and radius is not None: # Function 1-D new_area_extent = ( upper_left_extent[0], upper_left_extent[1] - 2 * radius[1], upper_left_extent[0] + 2 * radius[0], upper_left_extent[1]) area_extent = _validate_variable(area_extent, new_area_extent, 'area_extent', ['upper_left_extent', 'radius']) return area_extent, shape, resolution def _format_list(var, name): """Ensure that parameter is list-like of numbers. Used to let resolution and radius be single numbers if their elements are equal. """ # Single-number format. if not isinstance(var, (list, tuple)) and name in ('resolution', 'radius'):
[ " var = (float(var), float(var))" ]
3,675
lcc
python
null
b2e9852774a64a45a97fb402afdda4bca2ad6f026ab0a353
# Stolen Dignity version 0.1 # by DrLecter import sys from com.l2scoria import Config from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest #Quest info QUEST_NUMBER,QUEST_NAME,QUEST_DESCRIPTION = 386,"StolenDignity","Stolen Dignity" qn = "386_StolenDignity" #Variables DROP_RATE=15*Config.RATE_DROP_QUEST REQUIRED_ORE=100 #how many items will be paid for a game (affects onkill sounds too) #Quest items SI_ORE = 6363 #Rewards REWARDS=[5529]+range(5532,5540)+range(5541,5549)+[8331]+range(8341,8343)+[8346]+[8349] #Messages default = "<html><body>You are either not carrying out your quest or don't meet the criteria.</body></html>" error_1 = "Low_level.htm" start = "Start.htm" starting = "Starting.htm" starting2 = "Starting2.htm" binfo1 = "Bingo_howto.htm" bingo = "Bingo_start.htm" bingo0 = "Bingo_starting.htm" ext_msg = "Quest aborted" #NPCs WK_ROMP = 30843 #Mobs MOBS = [ 20670,20671,20954,20956,20958,20959,20960,20964,20969,20967,20970,20971,20974,20975,21001,21003,21005,21020,21021,21089,21108,21110,21113,21114,21116 ] MOB={ 20670:14, 20671:14, 20954:11, 20956:13, 20958:13, 20959:13, 20960:11, 20964:13, 20969:19, 20967:18, 20970:18, 20971:18, 20974:28, 20975:28, 21001:14, 21003:18, 21005:14, 21020:16, 21021:15, 21089:13, 21108:19, 21110:18, 21113:25, 21114:23, 21116:25 } MAX = 100 #templates number = ["second","third","fourth","fifth","sixth"] header = "<html><body>Warehouse Freightman Romp:<br><br>" link = "<td align=center><a action=\"bypass -h Quest 386_StolenDignity " middle = "</tr></table><br><br>Your selection thus far: <br><br><table border=1 width=120 hieght=64>" footer = "</table></body></html>" loser = "Wow! How unlucky can you get? Your choices are highlighted in red below. As you can see, your choices didn't make a single line! Losing this badly is actually quite rare!<br><br>You look so sad, I feel bad for you... Wait here...<br><br>.<br><br>.<br><br>.<br><br>Take this... I hope it will bring you better luck in the future.<br><br>" winner = "Excellent! As you can see, you've formed three lines! Congratulations! As promised, I'll give you some unclaimed merchandise from the warehouse. Wait here...<br><br>.<br><br>.<br><br>.<br><br>Whew, it's dusty! OK, here you go. Do you like it?<br><br>" average = "Hum. Well, your choices are highlighted in red below. As you can see your choices didn't formed three lines... but you were near, so don't be sad. You can always get another few infernium ores and try again. Better luck in the future!<br><br>" def partial(st) : html = " number:<br><br><table border=0><tr>" for z in range(1,10) : html += link+str(z)+"\">"+str(z)+"</a></td>" html += middle chosen = st.get("chosen").split() for y in range(0,7,3) : html +="<tr>" for x in range(3) : html+="<td align=center>"+chosen[x+y]+"</td>" html +="</tr>" html += footer return html def result(st) : chosen = st.get("chosen").split() grid = st.get("grid").split() html = "<table border=1 width=120 height=64>" for y in range(0,7,3) : html +="<tr>" for x in range(3) : html+="<td align=center>" if grid[x+y] == chosen[x+y] : html+="<font color=\"FF0000\"> "+grid[x+y]+" </font>" else : html+=grid[x+y] html+="</td>" html +="</tr>" html += footer return html class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st) : htmltext = event if event == "yes" : htmltext = starting st.setState(STARTED) st.set("cond","1") st.playSound("ItemSound.quest_accept") elif event == "binfo" : htmltext = binfo1 elif event == "0" : htmltext = ext_msg st.exitQuest(1) elif event == "bingo" : if st.getQuestItemsCount(SI_ORE) >= REQUIRED_ORE : st.takeItems(SI_ORE,REQUIRED_ORE) htmltext = bingo0 grid = range(1,10) #random.sample(xrange(1,10),9) ... damn jython that makes me think that inefficient stuff for i in range(len(grid)-1, 0, -1) : j = st.getRandom(8) grid[i], grid[j] = grid[j], grid[i] for i in range(len(grid)): grid[i]=str(grid[i]) st.set("chosen","? ? ? ? ? ? ? ? ?") st.set("grid"," ".join(grid)) st.set("playing","1") else : htmltext = "You don't have required items" else : for i in range(1,10) : if event == str(i) : if st.getInt("playing"): chosen = st.get("chosen").split() grid = st.get("grid").split() if chosen.count("?") >= 3 : chosen[grid.index(str(i))]=str(i) st.set("chosen"," ".join(chosen)) if chosen.count("?")==3 : htmltext = header row = col = diag = 0 for i in range(3) : if ''.join(chosen[3*i:3*i+3]).isdigit() : row += 1 if ''.join(chosen[i:9:3]).isdigit() : col += 1 if ''.join(chosen[0:9:4]).isdigit() : diag += 1 if ''.join(chosen[2:7:2]).isdigit() : diag += 1 if (col + row + diag) == 3 : htmltext += winner st.giveItems(REWARDS[st.getRandom(len(REWARDS))],4) st.playSound("ItemSound.quest_finish") elif (diag + row + col) == 0 : htmltext += loser st.giveItems(REWARDS[st.getRandom(len(REWARDS))],10) st.playSound("ItemSound.quest_jackpot") else : htmltext += average st.playSound("ItemSound.quest_giveup") htmltext += result(st) for var in ["chosen","grid","playing"]: st.unset(var) else : htmltext = header+"Select your "+number[8-chosen.count("?")]+partial(st) else: htmltext=default return htmltext def onTalk (self,npc,player): htmltext = default st = player.getQuestState(qn) if not st : return htmltext npcId = npc.getNpcId() id = st.getState() if id == CREATED : st.set("cond","0") if player.getLevel() < 58 : st.exitQuest(1) htmltext = error_1 else : htmltext = start elif id == STARTED : if st.getQuestItemsCount(SI_ORE) >= REQUIRED_ORE : htmltext = bingo else : htmltext = starting2 return htmltext def onKill(self,npc,player,isPet): partyMember = self.getRandomPartyMemberState(player, STARTED) if not partyMember : return st = partyMember.getQuestState(qn) numItems,chance = divmod(MOB[npc.getNpcId()]*Config.RATE_DROP_QUEST,MAX) prevItems = st.getQuestItemsCount(SI_ORE) if st.getRandom(MAX) < chance : numItems = numItems + 1 if numItems != 0 : st.giveItems(SI_ORE,int(numItems)) if int(prevItems+numItems)/REQUIRED_ORE > int(prevItems)/REQUIRED_ORE : st.playSound("ItemSound.quest_middle") else : st.playSound("ItemSound.quest_itemget") return # Quest class and state definition QUEST = Quest(QUEST_NUMBER, str(QUEST_NUMBER)+"_"+QUEST_NAME, QUEST_DESCRIPTION)
[ "CREATED = State('Start', QUEST)" ]
755
lcc
python
null
733108e23bea8f0fe687224256eb5c0b58a30b29f6ce051d
using System; using System.Reflection; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Kasuga { [Serializable] public struct PlayTime { public static PlayTime Zero; public static PlayTime Empty; public static Regex TimeTagRegex; public static Regex HeadTimeTagRegex; public static Regex FootTimeTagRegex; public static Regex HeadSyllableRegex; private double? _seconds; [XmlIgnore] public bool IsEmpty { get { bool hasValue; try { hasValue = !this.Seconds.HasValue; } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); hasValue = false; } return hasValue; } } [XmlIgnore] public double? Seconds { get { double? nullable; try { nullable = this._seconds; } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); nullable = null; } return nullable; } set { try { this._seconds = value; } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); } } } [XmlText] public string SecondsString { get { string str; try { str = (!this.IsEmpty ? this.Seconds.ToString() : "Empty"); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); str = null; } return str; } set { double num; try { if (!double.TryParse(value, out num)) { this.Seconds = null; } else { this.Seconds = new double?(num); } } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); } } } [XmlIgnore] public string TimeTag { get { string empty; try { if (!this.IsEmpty) { double? seconds = this.Seconds; int num = (int)Math.Floor((double)seconds.Value / 60); double? nullable = this.Seconds; int num1 = (int)Math.Floor((double)nullable.Value - (double)num * 60); double? seconds1 = this.Seconds; int num2 = (int)Math.Floor(((double)seconds1.Value - ((double)num * 60 + (double)num1)) * 100); string[] str = new string[] { "[", num.ToString("D2"), ":", num1.ToString("D2"), ":", num2.ToString("D2"), "]" }; empty = string.Concat(str); } else { empty = string.Empty; } } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); empty = string.Empty; } return empty; } set { try { this = PlayTime.FromTimeTag(value); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); } } } static PlayTime() { PlayTime.Zero = new PlayTime(new double?(0)); PlayTime.Empty = new PlayTime(null); PlayTime.TimeTagRegex = new Regex("\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\]"); PlayTime.HeadTimeTagRegex = new Regex("^\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\]"); PlayTime.FootTimeTagRegex = new Regex("\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\]$"); PlayTime.HeadSyllableRegex = new Regex("^(\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\])(.*?)(\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\])"); } public PlayTime(double? seconds) { try { this._seconds = seconds; } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); this._seconds = null; } } public override bool Equals(object obj) { bool flag; try { flag = this.Equals(obj); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static PlayTime FromTimeTag(string timeTag) { PlayTime playTime; try { Match match = (new Regex("^\\[(\\d{2}):([0-5]{1}\\d{1}):(\\d{2})\\]$")).Match(timeTag); if (match.Success) { double num = (double)int.Parse(match.Groups[1].Value); double num1 = (double)int.Parse(match.Groups[2].Value); double num2 = (double)int.Parse(match.Groups[3].Value); playTime = new PlayTime(new double?(num * 60 + num1 + num2 / 100)); } else { playTime = PlayTime.Empty; } } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); playTime = PlayTime.Empty; } return playTime; } public override int GetHashCode() { int hashCode; try { hashCode = this.GetHashCode(); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); hashCode = 0; } return hashCode; } public static bool IsTimeTag(string str) { bool flag; try { flag = (new Regex("^\\[\\d{2}:[0-5]{1}\\d{1}:\\d{2}\\]$")).IsMatch(str); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static PlayTime Max(PlayTime time1, PlayTime time2) { PlayTime empty; try { if (time1 == PlayTime.Empty && time2 == PlayTime.Empty) { empty = PlayTime.Empty; } else if (time1 == PlayTime.Empty) { empty = time2; } else if (time2 != PlayTime.Empty) { empty = (time1 < time2 ? time2 : time1); } else { empty = time1; } } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); empty = PlayTime.Empty; } return empty; } public static PlayTime Min(PlayTime time1, PlayTime time2) { PlayTime empty; try { if (time1 == PlayTime.Empty && time2 == PlayTime.Empty) { empty = PlayTime.Empty; } else if (time1 == PlayTime.Empty) { empty = time2; } else if (time2 != PlayTime.Empty) { empty = (time1 > time2 ? time2 : time1); } else { empty = time1; } } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); empty = PlayTime.Empty; } return empty; } public static PlayTime operator +(PlayTime time, PlayTimeSpan span) { PlayTime playTime; double? nullable; try { double? seconds = time.Seconds; double? seconds1 = span.Seconds; if (seconds.HasValue & seconds1.HasValue) { nullable = new double?((double)seconds.GetValueOrDefault() + (double)seconds1.GetValueOrDefault()); } else { nullable = null; } playTime = new PlayTime(nullable); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); playTime = PlayTime.Empty; } return playTime; } public static bool operator ==(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() != (double)nullable.GetValueOrDefault() ? false : seconds.HasValue == nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static bool operator >(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() <= (double)nullable.GetValueOrDefault() ? false : seconds.HasValue & nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static bool operator >=(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() < (double)nullable.GetValueOrDefault() ? false : seconds.HasValue & nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static bool operator !=(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() != (double)nullable.GetValueOrDefault() ? true : seconds.HasValue != nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static bool operator <(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() >= (double)nullable.GetValueOrDefault() ? false : seconds.HasValue & nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static bool operator <=(PlayTime time1, PlayTime time2) { bool flag; try { double? seconds = time1.Seconds; double? nullable = time2.Seconds; flag = ((double)seconds.GetValueOrDefault() > (double)nullable.GetValueOrDefault() ? false : seconds.HasValue & nullable.HasValue); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); flag = false; } return flag; } public static PlayTime operator -(PlayTime time, PlayTimeSpan span) { PlayTime playTime; double? nullable; try { double? seconds = time.Seconds; double? seconds1 = span.Seconds; if (seconds.HasValue & seconds1.HasValue) { nullable = new double?((double)seconds.GetValueOrDefault() - (double)seconds1.GetValueOrDefault()); } else { nullable = null; } playTime = new PlayTime(nullable); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); playTime = PlayTime.Empty; } return playTime; } public static PlayTimeSpan operator -(PlayTime time1, PlayTime time2) { PlayTimeSpan playTimeSpan; double? nullable; try { double? seconds = time1.Seconds; double? seconds1 = time2.Seconds; if (seconds.HasValue & seconds1.HasValue) { nullable = new double?((double)seconds.GetValueOrDefault() - (double)seconds1.GetValueOrDefault()); } else { nullable = null; } playTimeSpan = new PlayTimeSpan(nullable); } catch (Exception exception) { ErrorMessage.Show(exception, Assembly.GetExecutingAssembly(), MethodBase.GetCurrentMethod()); playTimeSpan = PlayTimeSpan.Empty; } return playTimeSpan; } public override string ToString() { string empty; try { if (!this.IsEmpty) { double? seconds = this.Seconds; int num = (int)Math.Floor((double)seconds.Value / 3600); double? nullable = this.Seconds; int num1 = (int)Math.Floor(((double)nullable.Value - (double)num * 60 * 60) / 60);
[ "\t\t\t\t\tdouble? seconds1 = this.Seconds;" ]
1,143
lcc
csharp
null
9e42cec6ffd16ad23a4bdd0f6b04734f621a0d2df6c78eb4
/** * Copyright (c) 2013 James King [metapyziks@gmail.com] * * This file is part of OpenTKTK. * * OpenTKTK is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenTKTK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenTKTK. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKTK.Textures; using OpenTKTK.Utils; namespace OpenTKTK.Shaders { public class ShaderProgram : IDisposable { public class AttributeInfo { public ShaderProgram Shader { get; private set; } public String Identifier { get; private set; } public int Location { get; private set; } public int Size { get; private set; } public int Offset { get; private set; } public int Divisor { get; private set; } public int InputOffset { get; private set; } public VertexAttribPointerType PointerType { get; private set; } public bool Normalize { get; private set; } public int Length { get { switch (PointerType) { case VertexAttribPointerType.Byte: case VertexAttribPointerType.UnsignedByte: return Size * sizeof(byte); case VertexAttribPointerType.Short: case VertexAttribPointerType.UnsignedShort: return Size * sizeof(short); case VertexAttribPointerType.Int: case VertexAttribPointerType.UnsignedInt: return Size * sizeof(int); case VertexAttribPointerType.HalfFloat: return Size * sizeof(float) / 2; case VertexAttribPointerType.Float: return Size * sizeof(float); case VertexAttribPointerType.Double: return Size * sizeof(double); default: return 0; } } } public AttributeInfo(ShaderProgram shader, String identifier, int size, int offset, int divisor, int inputOffset, VertexAttribPointerType pointerType = VertexAttribPointerType.Float, bool normalize = false) { Shader = shader; Identifier = identifier; Location = GL.GetAttribLocation(shader.Program, Identifier); Size = size; Offset = offset; Divisor = divisor; InputOffset = inputOffset; PointerType = pointerType; Normalize = normalize; } public override String ToString() { return Identifier + " @" + Location + ", Size: " + Size + ", Offset: " + Offset; } } private class TextureInfo { public ShaderProgram Shader { get; private set; } public String Identifier { get; private set; } public int UniformLocation { get; private set; } public TextureUnit TextureUnit { get; private set; } public Texture CurrentTexture { get; private set; } public TextureInfo(ShaderProgram shader, String identifier, TextureUnit textureUnit = TextureUnit.Texture0) { Shader = shader; Identifier = identifier; UniformLocation = GL.GetUniformLocation(Shader.Program, Identifier); TextureUnit = textureUnit; Shader.Use(); int val = (int) TextureUnit - (int) TextureUnit.Texture0; GL.Uniform1(UniformLocation, val); CurrentTexture = null; } public void SetCurrentTexture(Texture texture) { CurrentTexture = texture; GL.ActiveTexture(TextureUnit); CurrentTexture.Bind(); } } public class AttributeCollection : IEnumerable<AttributeInfo> { private static int GetAttributeSize(ShaderVarType type) { switch (type) { case ShaderVarType.Float: case ShaderVarType.Int: return 1; case ShaderVarType.Vec2: return 2; case ShaderVarType.Vec3: return 3; case ShaderVarType.Vec4: return 4; default: throw new ArgumentException("Invalid attribute type (" + type + ")."); } } private ShaderProgram _shader; internal AttributeCollection(ShaderProgram shader) { _shader = shader; } public AttributeInfo this[int index] { get { return _shader._attributes[index]; } } public AttributeInfo this[String ident] { get { return _shader._attributes.First(x => x.Identifier == ident); } } public IEnumerator<AttributeInfo> GetEnumerator() { return _shader._attributes.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _shader._attributes.GetEnumerator(); } } private static ShaderProgram _sCurProgram; public int VertexDataStride { get; private set; } public int VertexDataSize { get; private set; } private List<AttributeInfo> _attributes; private Dictionary<String, TextureInfo> _textures; private Dictionary<String, int> _uniforms; public int Program { get; private set; } public PrimitiveType PrimitiveType { get; protected set; } public bool Flat { get; private set; } public bool Active { get { return _sCurProgram == this; } } public bool Immediate { get; protected set; } public bool Started { get; protected set; } public AttributeCollection Attributes { get; private set; } public ShaderProgram(bool flat) { PrimitiveType = PrimitiveType.Triangles; Flat = flat;
[ " _attributes = new List<AttributeInfo>();" ]
661
lcc
csharp
null
4ec18b2c8f603cf68ea65e3606254e77895f2945bbc43537
from warnings import warn from copy import deepcopy, copy from six import iteritems, string_types from ..solvers import optimize from .Object import Object from .Solution import Solution from .Reaction import Reaction from .DictList import DictList # Note, when a reaction is added to the Model it will no longer keep personal # instances of its Metabolites, it will reference Model.metabolites to improve # performance. When doing this, take care to monitor metabolite coefficients. # Do the same for Model.reactions[:].genes and Model.genes class Model(Object): """Metabolic Model Refers to Metabolite, Reaction, and Gene Objects. """ def __setstate__(self, state): """Make sure all cobra.Objects in the model point to the model""" self.__dict__.update(state) for y in ['reactions', 'genes', 'metabolites']: for x in getattr(self, y): x._model = self if not hasattr(self, "name"): self.name = None def __init__(self, id_or_model=None, name=None): if isinstance(id_or_model, Model): Object.__init__(self, name=name) self.__setstate__(id_or_model.__dict__) if not hasattr(self, "name"): self.name = None else: Object.__init__(self, id_or_model, name=name) self._trimmed = False self._trimmed_genes = [] self._trimmed_reactions = {} self.genes = DictList() self.reactions = DictList() # A list of cobra.Reactions self.metabolites = DictList() # A list of cobra.Metabolites # genes based on their ids {Gene.id: Gene} self.compartments = {} self.solution = Solution(None) self.media_compositions = {} @property def description(self): warn("description deprecated") return self.name if self.name is not None else "" @description.setter def description(self, value): self.name = value warn("description deprecated") def __add__(self, other_model): """Adds two models. + The issue of reactions being able to exists in multiple Models now arises, the same for metabolites and such. This might be a little difficult as a reaction with the same name / id in two models might have different coefficients for their metabolites due to pH and whatnot making them different reactions. """ new_model = self.copy() new_reactions = deepcopy(other_model.reactions) new_model.add_reactions(new_reactions) new_model.id = self.id + '_' + other_model.id return new_model def __iadd__(self, other_model): """Adds a Model to this model += The issue of reactions being able to exists in multiple Models now arises, the same for metabolites and such. This might be a little difficult as a reaction with the same name / id in two models might have different coefficients for their metabolites due to pH and whatnot making them different reactions. """ new_reactions = deepcopy(other_model.reactions) self.add_reactions(new_reactions) self.id = self.id + '_' + other_model.id return self def copy(self): """Provides a partial 'deepcopy' of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy """ new = self.__class__() do_not_copy = {"metabolites", "reactions", "genes"} for attr in self.__dict__: if attr not in do_not_copy: new.__dict__[attr] = self.__dict__[attr] new.metabolites = DictList() do_not_copy = {"_reaction", "_model"} for metabolite in self.metabolites: new_met = metabolite.__class__() for attr, value in iteritems(metabolite.__dict__): if attr not in do_not_copy: new_met.__dict__[attr] = copy( value) if attr == "formula" else value new_met._model = new new.metabolites.append(new_met) new.genes = DictList() for gene in self.genes: new_gene = gene.__class__(None) for attr, value in iteritems(gene.__dict__): if attr not in do_not_copy: new_gene.__dict__[attr] = copy( value) if attr == "formula" else value new_gene._model = new new.genes.append(new_gene) new.reactions = DictList() do_not_copy = {"_model", "_metabolites", "_genes"} for reaction in self.reactions: new_reaction = reaction.__class__() for attr, value in iteritems(reaction.__dict__): if attr not in do_not_copy: new_reaction.__dict__[attr] = value new_reaction._model = new new.reactions.append(new_reaction) # update awareness for metabolite, stoic in iteritems(reaction._metabolites): new_met = new.metabolites.get_by_id(metabolite.id) new_reaction._metabolites[new_met] = stoic new_met._reaction.add(new_reaction) for gene in reaction._genes: new_gene = new.genes.get_by_id(gene.id) new_reaction._genes.add(new_gene) new_gene._reaction.add(new_reaction) return new def add_metabolites(self, metabolite_list): """Will add a list of metabolites to the the object, if they do not exist and then expand the stochiometric matrix metabolite_list: A list of :class:`~cobra.core.Metabolite` objects """ if not hasattr(metabolite_list, '__iter__'): metabolite_list = [metabolite_list] # First check whether the metabolites exist in the model metabolite_list = [x for x in metabolite_list if x.id not in self.metabolites] for x in metabolite_list: x._model = self self.metabolites += metabolite_list def add_reaction(self, reaction): """Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions. reaction: A :class:`~cobra.core.Reaction` object """ self.add_reactions([reaction]) def add_reactions(self, reaction_list): """Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions. reaction_list: A list of :class:`~cobra.core.Reaction` objects """ # Only add the reaction if one with the same ID is not already # present in the model. # This function really should not used for single reactions if not hasattr(reaction_list, "__len__"): reaction_list = [reaction_list] warn("Use add_reaction for single reactions") reaction_list = DictList(reaction_list) reactions_in_model = [ i.id for i in reaction_list if self.reactions.has_id( i.id)] if len(reactions_in_model) > 0: raise Exception("Reactions already in the model: " + ", ".join(reactions_in_model)) # Add reactions. Also take care of genes and metabolites in the loop for reaction in reaction_list: reaction._model = self # the reaction now points to the model # keys() is necessary because the dict will be modified during # the loop for metabolite in list(reaction._metabolites.keys()): # if the metabolite is not in the model, add it # should we be adding a copy instead. if not self.metabolites.has_id(metabolite.id): self.metabolites.append(metabolite) metabolite._model = self # this should already be the case. Is it necessary? metabolite._reaction = set([reaction]) # A copy of the metabolite exists in the model, the reaction # needs to point to the metabolite in the model. else: stoichiometry = reaction._metabolites.pop(metabolite) model_metabolite = self.metabolites.get_by_id( metabolite.id) reaction._metabolites[model_metabolite] = stoichiometry model_metabolite._reaction.add(reaction) for gene in list(reaction._genes): # If the gene is not in the model, add it if not self.genes.has_id(gene.id): self.genes.append(gene) gene._model = self # this should already be the case. Is it necessary? gene._reaction = set([reaction]) # Otherwise, make the gene point to the one in the model else: model_gene = self.genes.get_by_id(gene.id) if model_gene is not gene: reaction._dissociate_gene(gene) reaction._associate_gene(model_gene) self.reactions += reaction_list def to_array_based_model(self, deepcopy_model=False, **kwargs): """Makes a :class:`~cobra.core.ArrayBasedModel` from a cobra.Model which may be used to perform linear algebra operations with the stoichiomatric matrix. deepcopy_model: Boolean. If False then the ArrayBasedModel points to the Model """ from .ArrayBasedModel import ArrayBasedModel return ArrayBasedModel(self, deepcopy_model=deepcopy_model, **kwargs) def optimize(self, objective_sense='maximize', **kwargs): r"""Optimize model using flux balance analysis objective_sense: 'maximize' or 'minimize' solver: 'glpk', 'cglpk', 'gurobi', 'cplex' or None quadratic_component: None or :class:`scipy.sparse.dok_matrix` The dimensions should be (n, n) where n is the number of reactions. This sets the quadratic component (Q) of the objective coefficient, adding :math:`\\frac{1}{2} v^T \cdot Q \cdot v` to the objective. tolerance_feasibility: Solver tolerance for feasibility. tolerance_markowitz: Solver threshold during pivot time_limit: Maximum solver time (in seconds) .. NOTE :: Only the most commonly used parameters are presented here. Additional parameters for cobra.solvers may be available and specified with the appropriate keyword argument. """ solution = optimize(self, objective_sense=objective_sense, **kwargs) self.solution = solution return solution def remove_reactions(self, reactions, delete=True, remove_orphans=False): """remove reactions from the model reactions: [:class:`~cobra.core.Reaction.Reaction`] or [str] The reactions (or their id's) to remove delete: Boolean Whether or not the reactions should be deleted after removal. If the reactions are not deleted, those objects will be recreated with new metabolite and gene objects. remove_orphans: Boolean Remove orphaned genes and metabolites from the model as well """ if isinstance(reactions, string_types) or hasattr(reactions, "id"): warn("need to pass in a list") reactions = [reactions] for reaction in reactions: try: reaction = self.reactions[self.reactions.index(reaction)] except ValueError: warn('%s not in %s' % (reaction, self)) else: if delete: reaction.delete(remove_orphans=remove_orphans) else: reaction.remove_from_model(remove_orphans=remove_orphans) def repair(self, rebuild_index=True, rebuild_relationships=True): """Update all indexes and pointers in a model""" if rebuild_index: # DictList indexes self.reactions._generate_index() self.metabolites._generate_index() self.genes._generate_index() if rebuild_relationships: for met in self.metabolites: met._reaction.clear() for gene in self.genes: gene._reaction.clear() for rxn in self.reactions: for met in rxn._metabolites: met._reaction.add(rxn) for gene in rxn._genes: gene._reaction.add(rxn) # point _model to self
[ " for l in (self.reactions, self.genes, self.metabolites):" ]
1,227
lcc
python
null
291eb52753b18a31b084cd6c13d64847dd010ab270cd7bff
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinicaladmin.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to Oncology.Configuration.TumourGroup business object (ID: 1074100009). */ public class TumourGroupListVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<TumourGroupListVo> { private static final long serialVersionUID = 1L; private ArrayList<TumourGroupListVo> col = new ArrayList<TumourGroupListVo>(); public String getBoClassName() { return "ims.oncology.configuration.domain.objects.TumourGroup"; } public boolean add(TumourGroupListVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, TumourGroupListVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(TumourGroupListVo instance) { return col.indexOf(instance); } public TumourGroupListVo get(int index) { return this.col.get(index); } public boolean set(int index, TumourGroupListVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(TumourGroupListVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(TumourGroupListVo instance) { return indexOf(instance) >= 0; } public Object clone() { TumourGroupListVoCollection clone = new TumourGroupListVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((TumourGroupListVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public TumourGroupListVoCollection sort() { return sort(SortOrder.ASCENDING); } public TumourGroupListVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public TumourGroupListVoCollection sort(SortOrder order) { return sort(new TumourGroupListVoComparator(order)); } public TumourGroupListVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new TumourGroupListVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public TumourGroupListVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.oncology.configuration.vo.TumourGroupRefVoCollection toRefVoCollection() { ims.oncology.configuration.vo.TumourGroupRefVoCollection result = new ims.oncology.configuration.vo.TumourGroupRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public TumourGroupListVo[] toArray() { TumourGroupListVo[] arr = new TumourGroupListVo[col.size()]; col.toArray(arr); return arr; } public Iterator<TumourGroupListVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class TumourGroupListVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public TumourGroupListVoComparator() { this(SortOrder.ASCENDING); } public TumourGroupListVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public TumourGroupListVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { TumourGroupListVo voObj1 = (TumourGroupListVo)obj1; TumourGroupListVo voObj2 = (TumourGroupListVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.clinicaladmin.vo.beans.TumourGroupListVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.clinicaladmin.vo.beans.TumourGroupListVoBean[] getBeanCollectionArray() { ims.clinicaladmin.vo.beans.TumourGroupListVoBean[] result = new ims.clinicaladmin.vo.beans.TumourGroupListVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { TumourGroupListVo vo = ((TumourGroupListVo)col.get(i)); result[i] = (ims.clinicaladmin.vo.beans.TumourGroupListVoBean)vo.getBean(); } return result; } public static TumourGroupListVoCollection buildFromBeanCollection(java.util.Collection beans) { TumourGroupListVoCollection coll = new TumourGroupListVoCollection();
[ "\t\tif(beans == null)" ]
778
lcc
java
null
f963d6d0a6afee2f2e97ceb0f221aca6ff419e9f3f0e1a2b
/** * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.jpedal.org * (C) Copyright 1997-2008, IDRsolutions and Contributors. * * This file is part of JPedal * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * PdfPanel.java * --------------- */ package org.jpedal; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.dnd.DropTarget; import java.awt.event.MouseEvent; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Map; import javax.swing.border.Border; import org.jpedal.io.ObjectStore; import org.jpedal.objects.PdfPageData; //<start-jfr> //<start-adobe> import org.jpedal.objects.PageLines; //<end-adobe> import org.jpedal.objects.PdfData; import org.jpedal.objects.PrinterOptions; import org.jpedal.objects.raw.PdfArrayIterator; import org.jpedal.objects.layers.PdfLayerList; import org.jpedal.objects.acroforms.rendering.AcroRenderer; //<end-jfr> import org.jpedal.render.DynamicVectorRenderer; import org.jpedal.utils.repositories.Vector_Int; import org.jpedal.utils.repositories.Vector_Rectangle; import org.jpedal.utils.repositories.Vector_Shape; import javax.swing.*; /** * Do not create an instance of this class - provides GUI functionality for * PdfDecoder class to extend */ public class PdfPanel extends JPanel{ private static final long serialVersionUID = -5480323101993399978L; /** Not part of the JPedal API - Required for Storypad */ public JPanel[] extraButton; public boolean useParentButtons = false; protected PdfLayerList layers; /** Holds the x,y,w,h of the current highlighted image, null if none */ int[] highlightedImage = null; /** Enable / Disable Point and Click image extraction */ private boolean ImageExtractionAllowed = true; //<start-jfr> protected Display pages; /** holds the extracted AcroForm data */ //protected PdfFormData currentAcroFormData; //PdfArrayIterator fieldList=null; /**default renderer for acroforms*/ protected AcroRenderer formRenderer;//=new DefaultAcroRenderer(); /**hotspots for display*/ //Hotspots displayHotspots; /**hotspots for printing*/ //Hotspots printHotspots; //<start-adobe> /**holds page lines*/ protected PageLines pageLines; //<end-adobe> //<end-jfr> /** * The colour of the highlighting box around the text */ public static Color highlightColor = new Color(10,100,170); /** * The colour of the text once highlighted */ public static Color backgroundColor = null; /** * The transparency of the highlighting box around the text stored as a float */ public static float highlightComposite = 0.35f; protected Rectangle[] alternateOutlines; String altName; /**tracks indent so changing to continuous does not disturb display*/ private int lastIndent=-1; //<start-jfr> PageOffsets currentOffset; /**copy of flag to tell program whether to create * (and possibly update) screen display */ protected boolean renderPage = false; /**type of printing*/ protected boolean isPrintAutoRotateAndCenter=false; /**flag to show we use PDF page size*/ protected boolean usePDFPaperSize=false; /**page scaling mode to use for printing*/ protected int pageScalingMode=PrinterOptions.PAGE_SCALING_REDUCE_TO_PRINTER_MARGINS; //<end-jfr> /**display mode (continuous, facing, single)*/ protected int displayView=Display.SINGLE_PAGE; /**amount we scroll screen to make visible*/ private int scrollInterval=10; /** count of how many pages loaded */ protected int pageCount = 0; /** * if true * show the crop box as a box with cross on it * and remove the clip. */ private boolean showCrop = false; /** when true setPageParameters draws the page rotated for use with scale to window */ boolean isNewRotationSet=false; /** displays the viewport border */ protected boolean displayViewportBorder=false; /**flag to stop multiple attempts to decode*/ protected boolean isDecoding=false; protected int alignment=Display.DISPLAY_LEFT_ALIGNED; /** used by setPageParameters to draw rotated pages */ protected int displayRotation=0; /**current cursor location*/ private Point current_p; /**allows user to create viewport on page and scale to this*/ protected Rectangle viewableArea=null; /**shows merging for debugging*/ private Vector_Int merge_level ; private Vector_Shape merge_outline; private boolean[] showDebugLevel; private Color[] debugColors; private boolean showMerging=false; /**used to draw demo cross*/ AffineTransform demoAf=null; /**repaint manager*/ private RepaintManager currentManager=RepaintManager.currentManager(this); /**current page*/ protected int pageNumber=1; /**used to reduce or increase image size*/ protected AffineTransform displayScaling; /** * used to apply the imageable area to the displayscaling, used instead of * displayScaling, as to preserve displayScaling */ protected AffineTransform viewScaling=null; /** holds page information used in grouping*/ protected PdfPageData pageData = new PdfPageData(); /**used to track highlight*/ private Rectangle lastHighlight=null; /**rectangle drawn on screen by user*/ protected Rectangle cursorBoxOnScreen = null,lastCursorBoxOnScreen=null; /** whether the cross-hairs are drawn */ private boolean drawCrossHairs = false; /** which box the cursor is currently positioned over */ private int boxContained = -1; /** color to highlight selected handle */ private Color selectedHandleColor = Color.red; /** the gap around each point of reference for cursorBox */ private int handlesGap = 5; /**colour of highlighted rectangle*/ private Color outlineColor; /**rectangle of object currently under cursor*/ protected Rectangle currentHighlightedObject = null; /**colour of a shape we highlight on the page*/ private Color outlineHighlightColor; /**preferred colour to highliht page*/ private Color[] highlightColors; /**gap around object to repaint*/ static final private int strip=2; /**highlight around selected area*/ private Rectangle2D[] outlineZone = null; private int[] processedByRegularExpression=null; /**allow for inset of display*/ protected int insetW=0,insetH=0; /**flag to show if area selected*/ private boolean[] highlightedZonesSelected = null; private boolean[] hasDrownedObjects = null; /**user defined viewport*/ Rectangle userAnnot=null; /** default height width of bufferedimage in pixels */ private int defaultSize = 100; /**height of the BufferedImage in pixels*/ int y_size = defaultSize; /**unscaled page height*/ int max_y; /**unscaled page Width*/ int max_x; /**width of the BufferedImage in pixels*/ int x_size = defaultSize; /**used to plot selection*/ int[] cx=null,cy=null; /**any scaling factor being used to convert co-ords into correct values * and to alter image size */ protected float scaling=1; /**mode for showing outlines*/ private int highlightMode = 0; /**flag for showing all object outlines in PDFPanel*/ public static final int SHOW_OBJECTS = 1; /**flag for showing all lines on page used for grouping */ public static final int SHOW_LINES = 2; /**flag for showing all lines on page used for grouping */ public static final int SHOW_BOXES = 4; /**size of font for selection order*/ protected int size=20; /**font used to show selection order*/ protected Font highlightFont=null; /**border for component*/ protected Border myBorder=null; protected DropTarget dropTarget = null; /** the ObjectStore for this file */ protected ObjectStore objectStoreRef = new ObjectStore(); /**the actual display object*/ protected DynamicVectorRenderer currentDisplay=new DynamicVectorRenderer(1,objectStoreRef,false); // /**flag to show if border appears on printed output*/ protected boolean useBorder=true; private int[] selectionOrder; /**stores area of arrays in which text should be highlighted*/ private Rectangle[] areas; private int[] areaDirection; private Object[] linkedItems,children; private int[] parents; protected boolean useAcceleration=true; /**all text blocks as a shape*/ private Shape[] fragmentShapes; int x_size_cropped; int y_size_cropped; private AffineTransform cursorAf; private Rectangle actualBox; private boolean drawInteractively=false; protected int lastFormPage=-1,lastStart=-1,lastEnd=-1; private int pageUsedForTransform; protected int additionalPageCount=0,xOffset=0; private boolean displayForms = true; //private GraphicsDevice currentGraphicsDevice = null; public boolean extractingAsImage = false; private int highlightX = 0; private int highlightY = 0; public void setExtractingAsImage(boolean extractingAsImage) { this.extractingAsImage = extractingAsImage; } //<start-adobe> public void initNonPDF(PdfDecoder pdf){ pages=new SingleDisplay(pageNumber,pageCount,currentDisplay); pages.setup(true,null, pdf); } /**workout combined area of shapes are in an area*/ public Rectangle getCombinedAreas(Rectangle targetRectangle,boolean justText){ if(this.currentDisplay!=null) return currentDisplay.getCombinedAreas(targetRectangle, justText); return null; } /** * put debugging info for grouping onscreen * to aid in developing and debugging merging algorithms used by Storypad - * (NOT PART OF API and subject to change) */ final public void addMergingDisplayForDebugging(Vector_Int merge_level, Vector_Shape merge_outline,int count,Color[] colors) { this.merge_level=merge_level; this.merge_outline=merge_outline; this.showDebugLevel=new boolean[count]; this.debugColors=colors; } /** * debug zone for Storypad - not part of API */ final public void setDebugView(int level, boolean enabled){ if(showDebugLevel!=null) showDebugLevel[level]=enabled; } //<end-adobe> /** * get pdf as Image of current page with height as required height in pixels - * Page must be decoded first - used to generate thubnails for display. * Use decodePageAsImage forcreating images of pages */ final public BufferedImage getPageAsThumbnail(int height,DynamicVectorRenderer currentDisplay) { if(currentDisplay==null){ currentDisplay=this.currentDisplay; /** * save to disk */ ObjectStore.cachePage(new Integer(pageNumber), currentDisplay); } BufferedImage image = getImageFromRenderer(height,currentDisplay,pageNumber); return image; } /** */ protected BufferedImage getImageFromRenderer(int height,DynamicVectorRenderer rend,int pageNumber) { //int mediaBoxW = pageData.getMediaBoxWidth(pageNumber); int mediaBoxH = pageData.getMediaBoxHeight(pageNumber); int mediaBoxX = pageData.getMediaBoxX(pageNumber); int mediaBoxY = pageData.getMediaBoxY(pageNumber); int crw=pageData.getCropBoxWidth(pageNumber); int crh=pageData.getCropBoxHeight(pageNumber); int crx=pageData.getCropBoxX(pageNumber); int cry=pageData.getCropBoxY(pageNumber); if(cry>0) cry=mediaBoxH-crh-cry; float scale=(float) height/(crh); int rotation=pageData.getRotation(pageNumber); /**allow for rotation*/ int dr=-1; if((rotation==90)|(rotation==270)){ int tmp=crw; crw=crh; crh=tmp; dr=1; tmp=crx; crx=cry; cry=tmp; } AffineTransform scaleAf = getScalingForImage(pageNumber,rotation,scale);//(int)(mediaBoxW*scale), (int)(mediaBoxH*scale), int cx=mediaBoxX-crx,cy=mediaBoxY-cry; scaleAf.translate(cx,dr*cy); return rend.getPageAsImage(scale,crx,cry,crw,crh,pageNumber,scaleAf,BufferedImage.TYPE_INT_RGB); } //<start-adobe> /**set zones we want highlighted onscreen * @deprecated * please look at setFoundTextAreas(Rectangle areas),setHighlightedAreas(Rectangle[] areas) * <b>This is NOT part of the API</b> (used in Storypad) */ final public void setHighlightedZones( int mode, int[] cx,int[] cy, Shape[] fragmentShapes, Object[] linkedItems, int[] parents, Object[] childItems, int[] childParents, Rectangle2D[] outlineZone, boolean[] highlightedZonesSelected,boolean[] hasDrownedObjects,Color[] highlightColors,int[] selectionOrder,int[] processedByRegularExpression) { this.cx=cx; this.cy=cy; this.fragmentShapes=fragmentShapes; this.linkedItems=linkedItems; this.parents=parents; this.children=childItems; this.outlineZone = outlineZone; this.processedByRegularExpression=processedByRegularExpression; this.highlightedZonesSelected = highlightedZonesSelected; this.hasDrownedObjects = hasDrownedObjects; this.highlightMode = mode; this.highlightColors=highlightColors; this.selectionOrder=selectionOrder; //and deselect alt highlights this.alternateOutlines=null; } /**set merging option for Storypad (not part of API)*/ public void setDebugDisplay(boolean isEnabled){ this.showMerging=isEnabled; } /** * set an inset display so that display will not touch edge of panel*/ final public void setInset(int width,int height) { this.insetW=width; this.insetH=height; } /** * make screen scroll to ensure point is visible */ public void ensurePointIsVisible(Point p){ super.scrollRectToVisible(new Rectangle(p.x,y_size-p.y,scrollInterval,scrollInterval)); } //<end-adobe> /** * get sizes of panel <BR> * This is the PDF pagesize (as set in the PDF from pagesize) - * It now includes any scaling factor you have set (ie a PDF size 800 * 600 * with a scaling factor of 2 will return 1600 *1200) */ final public Dimension getMaximumSize() { Dimension pageSize=null; if(displayView!=Display.SINGLE_PAGE) pageSize = pages.getPageSize(displayView); if(pageSize==null){ if((displayRotation==90)|(displayRotation==270)) pageSize= new Dimension((int)(y_size_cropped+insetW+insetW+(xOffset*scaling)+(additionalPageCount*(insetW+insetW))),x_size_cropped+insetH+insetH); else pageSize= new Dimension((int)(x_size_cropped+insetW+insetW+(xOffset*scaling)+(additionalPageCount*(insetW+insetW))),y_size_cropped+insetH+insetH); } if(pageSize==null) pageSize=getMinimumSize(); return pageSize; } /** * get width*/ final public Dimension getMinimumSize() { return new Dimension(100+insetW,100+insetH); } /** * get sizes of panel <BR> * This is the PDF pagesize (as set in the PDF from pagesize) - * It now includes any scaling factor you have set (ie a PDF size 800 * 600 * with a scaling factor of 2 will return 1600 *1200) */ public Dimension getPreferredSize() { return getMaximumSize(); } public Rectangle[] getHighlightedAreas(){ if(areas==null) return null; else{ int count=areas.length; Rectangle[] returnValue=new Rectangle[count]; for(int ii=0;ii<count;ii++){ if(areas[ii]==null) returnValue[ii]=null; else returnValue[ii]=new Rectangle(areas[ii].x,areas[ii].y, areas[ii].width,areas[ii].height); } return returnValue; } } /** * Highlights a section of lines that form a paragraph */ public Rectangle setFoundParagraph(int x, int y){ Rectangle[] lines = PdfHighlights.getLineAreas(); if(lines!=null){ Rectangle point = new Rectangle(x,y,1,1); Rectangle current = new Rectangle(0,0,0,0); boolean lineFound = false; int selectedLine = 0; for(int i=0; i!=lines.length; i++){ if(lines[i].intersects(point)){ selectedLine = i; lineFound = true; break; } } if(lineFound){ double left = lines[selectedLine].x; double cx = lines[selectedLine].getCenterX(); double right = lines[selectedLine].x+lines[selectedLine].width; double cy = lines[selectedLine].getCenterY(); int h = lines[selectedLine].height; current.x=lines[selectedLine].x; current.y=lines[selectedLine].y; current.width=lines[selectedLine].width; current.height=lines[selectedLine].height; boolean foundTop = true; boolean foundBottom = true; Vector_Rectangle selected = new Vector_Rectangle(0); selected.addElement(lines[selectedLine]); while(foundTop){ foundTop = false; for(int i=0; i!=lines.length; i++){ if(lines[i].contains(left, cy+h) || lines[i].contains(cx, cy+h) || lines[i].contains(right, cy+h)){ selected.addElement(lines[i]); foundTop = true; cy = lines[i].getCenterY(); h = lines[i].height; if(current.x>lines[i].x){ current.width = (current.x+current.width)-lines[i].x; current.x = lines[i].x; } if((current.x+current.width)<(lines[i].x+lines[i].width)) current.width = (lines[i].x+lines[i].width)-current.x; if(current.y>lines[i].y){ current.height = (current.y+current.height)-lines[i].y; current.y = lines[i].y; } if((current.y+current.height)<(lines[i].y+lines[i].height)){ current.height = (lines[i].y+lines[i].height)-current.y; } break; } } } //Return to selected item else we have duplicate highlights left = lines[selectedLine].x;
[ "\t\t\t\tcx = lines[selectedLine].getCenterX();" ]
1,861
lcc
java
null
e78664cfc18ba1345c5f345deba0b09a64d425e203bdff71
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.zirco.ui.activities; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.emergent.android.weave.client.WeaveAccountInfo; import com.polysaas.browser.R; import org.zirco.model.DbAdapter; import org.zirco.model.adapters.WeaveBookmarksCursorAdapter; import org.zirco.model.items.WeaveBookmarkItem; import org.zirco.providers.BookmarksProviderWrapper; import org.zirco.providers.WeaveColumns; import org.zirco.sync.ISyncListener; import org.zirco.sync.WeaveSyncTask; import org.zirco.ui.activities.preferences.WeavePreferencesActivity; import org.zirco.utils.ApplicationUtils; import org.zirco.utils.Constants; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class WeaveBookmarksListActivity extends Activity implements ISyncListener { private static final int MENU_SYNC = Menu.FIRST; private static final int MENU_CLEAR = Menu.FIRST + 1; private static final int MENU_OPEN_IN_TAB = Menu.FIRST + 10; private static final int MENU_COPY_URL = Menu.FIRST + 11; private static final int MENU_SHARE = Menu.FIRST + 12; private static final String ROOT_FOLDER = "places"; private LinearLayout mNavigationView; private TextView mNavigationText; private ImageButton mNavigationBack; private ListView mListView; private Button mSetupButton; private Button mSyncButton; private View mEmptyView; private View mEmptyFolderView; private List<WeaveBookmarkItem> mNavigationList; private ProgressDialog mProgressDialog; private DbAdapter mDbAdapter; private Cursor mCursor = null; private WeaveSyncTask mSyncTask; private static final AtomicReference<AsyncTask<WeaveAccountInfo, Integer, Throwable>> mSyncThread = new AtomicReference<AsyncTask<WeaveAccountInfo, Integer, Throwable>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.weave_bookmarks_list_activity); mNavigationView = (LinearLayout) findViewById(R.id.WeaveBookmarksNavigationView); mNavigationText = (TextView) findViewById(R.id.WeaveBookmarksNavigationText); mNavigationBack = (ImageButton) findViewById(R.id.WeaveBookmarksNavigationBack); mListView = (ListView) findViewById(R.id.WeaveBookmarksList); mNavigationBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doNavigationBack(); } }); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { WeaveBookmarkItem selectedItem = BookmarksProviderWrapper.getWeaveBookmarkById(getContentResolver(), id); if (selectedItem != null) { if (selectedItem.isFolder()) { mNavigationList.add(selectedItem); fillData(); } else { String url = selectedItem.getUrl(); if (url != null) { Intent result = new Intent(); result.putExtra(Constants.EXTRA_ID_NEW_TAB, false); result.putExtra(Constants.EXTRA_ID_URL, url); if (getParent() != null) { getParent().setResult(RESULT_OK, result); } else { setResult(RESULT_OK, result); } finish(); } } } } }); mEmptyView = findViewById(R.id.WeaveBookmarksEmptyView); mEmptyFolderView = findViewById(R.id.WeaveBookmarksEmptyFolderView); //mListView.setEmptyView(mEmptyView); mSetupButton = (Button) findViewById(R.id.WeaveBookmarksEmptyViewSetupButton); mSetupButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { startActivity(new Intent(WeaveBookmarksListActivity.this, WeavePreferencesActivity.class)); } }); mSyncButton = (Button) findViewById(R.id.WeaveBookmarksEmptyViewSyncButton); mSyncButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSync(); } }); mNavigationList = new ArrayList<WeaveBookmarkItem>(); mNavigationList.add(new WeaveBookmarkItem(getResources().getString(R.string.WeaveBookmarksListActivity_WeaveRootFolder), null, ROOT_FOLDER, true)); mDbAdapter = new DbAdapter(this); mDbAdapter.open(); registerForContextMenu(mListView); fillData(); } @Override protected void onDestroy() { if (mCursor != null) { mCursor.close(); } mDbAdapter.close(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.add(0, MENU_SYNC, 0, R.string.WeaveBookmarksListActivity_MenuSync); item.setIcon(R.drawable.ic_menu_sync); item = menu.add(0, MENU_CLEAR, 0, R.string.WeaveBookmarksListActivity_MenuClear); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch(item.getItemId()) { case MENU_SYNC: doSync(); return true; case MENU_CLEAR: doClear(); return true; default: return super.onMenuItemSelected(featureId, item); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); long id = ((AdapterContextMenuInfo) menuInfo).id; if (id != -1) { WeaveBookmarkItem item = BookmarksProviderWrapper.getWeaveBookmarkById(getContentResolver(), id); if (!item.isFolder()) { menu.setHeaderTitle(item.getTitle()); menu.add(0, MENU_OPEN_IN_TAB, 0, R.string.BookmarksListActivity_MenuOpenInTab); menu.add(0, MENU_COPY_URL, 0, R.string.BookmarksHistoryActivity_MenuCopyLinkUrl); menu.add(0, MENU_SHARE, 0, R.string.Main_MenuShareLinkUrl); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); WeaveBookmarkItem bookmarkItem = BookmarksProviderWrapper.getWeaveBookmarkById(getContentResolver(), info.id); switch (item.getItemId()) { case MENU_OPEN_IN_TAB: Intent i = new Intent(); i.putExtra(Constants.EXTRA_ID_NEW_TAB, true); i.putExtra(Constants.EXTRA_ID_URL, bookmarkItem.getUrl()); if (getParent() != null) { getParent().setResult(RESULT_OK, i); } else { setResult(RESULT_OK, i); } finish(); return true; case MENU_COPY_URL: ApplicationUtils.copyTextToClipboard(this, bookmarkItem.getUrl(), getString(R.string.Commons_UrlCopyToastMessage)); return true; case MENU_SHARE: ApplicationUtils.sharePage(this, bookmarkItem.getTitle(), bookmarkItem.getUrl()); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mNavigationList.size() > 1) { doNavigationBack(); return true; } else { return super.onKeyUp(keyCode, event); } default: return super.onKeyUp(keyCode, event); } } /** * Set the list loading animation. */ private void setAnimation() { AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(75); set.addAnimation(animation); animation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f ); animation.setDuration(50); set.addAnimation(animation); LayoutAnimationController controller =
[ " new LayoutAnimationController(set, 0.5f);" ]
730
lcc
java
null
ecfe82f294b057561aa2f9cd0122f2dbc5fb0dae134d8df8
// // DO NOT REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // // @Authors: // wolfgangb // // Copyright 2004-2013 by OM International // // This file is part of OpenPetra.org. // // OpenPetra.org is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // OpenPetra.org is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OpenPetra.org. If not, see <http://www.gnu.org/licenses/>. // using System; using System.Data; using System.Windows.Forms; using Ict.Common; using Ict.Common.Controls; using Ict.Common.Verification; using Ict.Common.Remoting.Client; using Ict.Petra.Shared.Interfaces.MPartner; using Ict.Petra.Shared.MPartner.Partner.Data; using Ict.Petra.Shared; using Ict.Petra.Shared.MPartner; using Ict.Petra.Client.App.Core; using Ict.Petra.Client.App.Gui; using Ict.Petra.Client.CommonControls; using Ict.Petra.Shared.MPartner.Validation; namespace Ict.Petra.Client.MPartner.Gui { public partial class TUC_PartnerInterests { /// <summary>holds a reference to the Proxy System.Object of the Serverside UIConnector</summary> private IPartnerUIConnectorsPartnerEdit FPartnerEditUIConnector; #region Public Methods /// <summary>used for passing through the Clientside Proxy for the UIConnector</summary> public IPartnerUIConnectorsPartnerEdit PartnerEditUIConnector { get { return FPartnerEditUIConnector; } set { FPartnerEditUIConnector = value; } } /// <summary>todoComment</summary> public event TRecalculateScreenPartsEventHandler RecalculateScreenParts; /// <summary>todoComment</summary> public event THookupPartnerEditDataChangeEventHandler HookupDataChange; private void RethrowRecalculateScreenParts(System.Object sender, TRecalculateScreenPartsEventArgs e) { OnRecalculateScreenParts(e); } private void OnHookupDataChange(THookupPartnerEditDataChangeEventArgs e) { if (HookupDataChange != null) { HookupDataChange(this, e); } } private void OnRecalculateScreenParts(TRecalculateScreenPartsEventArgs e) { if (RecalculateScreenParts != null) { RecalculateScreenParts(this, e); } } /// <summary> /// This Procedure will get called from the SaveChanges procedure before it /// actually performs any saving operation. /// </summary> /// <param name="sender">The Object that throws this Event</param> /// <param name="e">Event Arguments. /// </param> /// <returns>void</returns> private void DataSavingStarted(System.Object sender, System.EventArgs e) { } /// <summary>todoComment</summary> public void SpecialInitUserControl() { LoadDataOnDemand(); grdDetails.Columns.Clear(); grdDetails.AddTextColumn("Category", FMainDS.PPartnerInterest.ColumnInterestCategory); grdDetails.AddTextColumn("Interest", FMainDS.PPartnerInterest.ColumnInterest); grdDetails.AddTextColumn("Country", FMainDS.PPartnerInterest.ColumnCountry); grdDetails.AddPartnerKeyColumn("Field", FMainDS.PPartnerInterest.ColumnFieldKey); grdDetails.AddTextColumn("Level", FMainDS.PPartnerInterest.ColumnLevel); grdDetails.AddTextColumn("Comment", FMainDS.PPartnerInterest.ColumnComment); OnHookupDataChange(new THookupPartnerEditDataChangeEventArgs(TPartnerEditTabPageEnum.petpInterests)); // Hook up DataSavingStarted Event to be able to run code before SaveChanges is doing anything FPetraUtilsObject.DataSavingStarted += new TDataSavingStartHandler(this.DataSavingStarted); if (grdDetails.Rows.Count > 1) { grdDetails.SelectRowInGrid(1); ShowDetails(1); // do this as for some reason details are not automatically show here at the moment } } /// <summary> /// This Method is needed for UserControls who get dynamicly loaded on TabPages. /// Since we don't have controls on this UserControl that need adjusting after resizing /// on 'Large Fonts (120 DPI)', we don't need to do anything here. /// </summary> public void AdjustAfterResizing() { } #endregion #region Private Methods private void InitializeManualCode() { if (!FMainDS.Tables.Contains(PartnerEditTDSPPartnerInterestTable.GetTableName())) { FMainDS.Tables.Add(new PartnerEditTDSPPartnerInterestTable()); } FMainDS.InitVars(); } /// <summary> /// Loads Partner Interest Data from Petra Server into FMainDS. /// </summary> /// <returns>true if successful, otherwise false.</returns> private Boolean LoadDataOnDemand() { Boolean ReturnValue; // Load Partner Types, if not already loaded try { // Make sure that Typed DataTables are already there at Client side if (FMainDS.PPartnerInterest == null) { FMainDS.Tables.Add(new PartnerEditTDSPPartnerInterestTable()); FMainDS.InitVars(); } if (TClientSettings.DelayedDataLoading) { FMainDS.Merge(FPartnerEditUIConnector.GetDataPartnerInterests()); // Make DataRows unchanged if (FMainDS.PPartnerInterest.Rows.Count > 0) { FMainDS.PPartnerInterest.AcceptChanges(); } } if (FMainDS.PPartnerInterest.Rows.Count != 0) { ReturnValue = true; } else { ReturnValue = false; } } catch (System.NullReferenceException) { return false; } catch (Exception) { throw; } return ReturnValue; } private void ShowDataManual() { } private void ShowDetailsManual(PPartnerInterestRow ARow) { } private void GetDetailDataFromControlsManual(PPartnerInterestRow ARow) { if (ARow.RowState != DataRowState.Deleted) { if (!ARow.IsFieldKeyNull()) { if (ARow.FieldKey == 0) { ARow.SetFieldKeyNull(); } } } } private void FilterInterestCombo(object sender, EventArgs e) { PInterestCategoryTable CategoryTable; PInterestCategoryRow CategoryRow; string SelectedCategory = cmbPPartnerInterestInterestCategory.GetSelectedString(); string SelectedInterest = cmbPPartnerInterestInterest.GetSelectedString(); cmbPPartnerInterestInterest.Filter = PInterestTable.GetCategoryDBName() + " = '" + SelectedCategory + "'"; // reset text to previous value or (if not found) empty text field if (cmbPPartnerInterestInterest.GetSelectedString() != String.Empty) { if (!cmbPPartnerInterestInterest.SetSelectedString(SelectedInterest)) { cmbPPartnerInterestInterest.SetSelectedString("", -1); } } CategoryTable = (PInterestCategoryTable)TDataCache.TMPartner.GetCacheablePartnerTable(TCacheablePartnerTablesEnum.InterestCategoryList); CategoryRow = (PInterestCategoryRow)CategoryTable.Rows.Find(new object[] { SelectedCategory }); if ((CategoryRow != null) && !CategoryRow.IsLevelRangeLowNull() && !CategoryRow.IsLevelRangeHighNull()) { if (CategoryRow.LevelRangeLow == CategoryRow.LevelRangeHigh) { lblInterestLevelExplanation.Text = String.Format(Catalog.GetString("(only level {0} is available for category {1})"), CategoryRow.LevelRangeLow, CategoryRow.Category); } else { lblInterestLevelExplanation.Text = String.Format(Catalog.GetString("(from {0} to {1})"), CategoryRow.LevelRangeLow, CategoryRow.LevelRangeHigh); } } else { lblInterestLevelExplanation.Text = ""; } } /// <summary> /// adding a new partner relationship record /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewRecord(System.Object sender, EventArgs e) { TRecalculateScreenPartsEventArgs RecalculateScreenPartsEventArgs; if (CreateNewPPartnerInterest()) { cmbPPartnerInterestInterestCategory.Focus(); } // Fire OnRecalculateScreenParts event: reset counter in tab header RecalculateScreenPartsEventArgs = new TRecalculateScreenPartsEventArgs(); RecalculateScreenPartsEventArgs.ScreenPart = TScreenPartEnum.spCounters; OnRecalculateScreenParts(RecalculateScreenPartsEventArgs); } /// <summary> /// manual code when adding new row /// </summary> /// <param name="ARow"></param> private void NewRowManual(ref PartnerEditTDSPPartnerInterestRow ARow) { Int32 HighestNumber = 0; PPartnerInterestRow PartnerInterestRow; // find the highest number so far and increase it by 1 for the new key foreach (PPartnerInterestRow row in FMainDS.PPartnerInterest.Rows) { PartnerInterestRow = (PPartnerInterestRow)row;
[ " if (PartnerInterestRow.RowState != DataRowState.Deleted)" ]
803
lcc
csharp
null
0927453c4d51d5c9eef3799b0ae56d6daebdb8afabc59c38
// <TMSEG: Prediction of Transmembrane Helices in Proteins.> // Copyright (C) 2014 Michael Bernhofer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package predictors; import io.ModelHandler; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Random; import util.ErrorUtils; import util.Globals; import util.Mappings; import weka.classifiers.Classifier; import weka.classifiers.trees.RandomForest; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.core.SparseInstance; import weka.core.converters.ArffSaver; import data.Protein; import data.Pssm; /** * Class to predict transmembrane residues within a protein. */ public class HelixIndexer { public static final int indexNotTmh = 0; public static final int indexTmh = 1; public static final int indexSignal = 2; private ArrayList<Attribute> attributes = null; private Instances dataset = null; private Classifier classifier = null; private boolean isTrained = false; private double[] globalConsAa = null; private double[] globalNonConsAa = null; public HelixIndexer() { this.buildAttributes(); this.initialize(); } /** * Initializes the attributes list for the Weka arff-format. */ private void buildAttributes() { this.attributes = new ArrayList<Attribute>(); for (int i = 1; i <= ((2*Globals.INDEXER_WINDOW_SIZE)+1); ++i) { for (int j = 0; j < 21; ++j) { this.attributes.add(new Attribute(Mappings.intToAa(j)+"_"+i)); } } this.attributes.add(new Attribute("conserved_hydrophobicity")); this.attributes.add(new Attribute("non-conserved_hydrophobicity")); this.attributes.add(new Attribute("conserved_hydrophobic")); this.attributes.add(new Attribute("non-conserved_hydrophobic")); this.attributes.add(new Attribute("conserved_pos_charged")); this.attributes.add(new Attribute("non-conserved_pos_charged")); this.attributes.add(new Attribute("conserved_neg_charged")); this.attributes.add(new Attribute("non-conserved_neg_charged")); this.attributes.add(new Attribute("conserved_polar")); this.attributes.add(new Attribute("non-conserved_polar")); ArrayList<String> lengths = new ArrayList<String>(); lengths.add(String.valueOf("0")); lengths.add(String.valueOf("1")); lengths.add(String.valueOf("2")); lengths.add(String.valueOf("3")); lengths.add(String.valueOf("4")); this.attributes.add(new Attribute("n-term_distance", lengths)); this.attributes.add(new Attribute("c-term_distance", lengths)); this.attributes.add(new Attribute("global_length", lengths)); for (int j = 0; j < 20; ++j) { this.attributes.add(new Attribute("global_conserved_"+Mappings.intToAa(j))); this.attributes.add(new Attribute("global_non-conserved_"+Mappings.intToAa(j))); } ArrayList<String> classes = new ArrayList<String>(); classes.add(String.valueOf(HelixIndexer.indexNotTmh)); classes.add(String.valueOf(HelixIndexer.indexTmh)); classes.add(String.valueOf(HelixIndexer.indexSignal)); this.attributes.add(new Attribute("class", classes)); } /** * Initializes the classifier and dataset. */ public void initialize() { this.isTrained = false; this.classifier = null; this.dataset = new Instances("HelixIndexer Model", this.attributes, 0); this.dataset.setClassIndex(this.attributes.size()-1); } /** * Inputs a given list of proteins for the training data. * * @param proteins */ public void input(List<Protein> proteins) { for (Protein protein : proteins) { this.input(protein); } } /** * Inputs a given protein for the training data. * * @param protein */ public void input(Protein protein) { if (protein == null) {return;} if (protein.getStructure() == null) {return;} if (protein.getPssm() == null) {return;} Pssm pssm = protein.getPssm(); int length = pssm.getLength(); char[] structure = protein.getStructure(); if (pssm.getLength() != structure.length) { ErrorUtils.printError(HelixIndexer.class, "PSSM and structure annotation length do not match for " + protein.getName(), null); return; } this.globalComposition(pssm); for (int i = 0; i < length; ++i) { if (Mappings.ssToInt(structure[i]) != Mappings.indexUnknown) { this.addWindowToDatabase(pssm, i, structure); } } } /** * Predicts transmembrane residues for a given list of proteins. * * @param proteins */ public void predict(List<Protein> proteins) { for (Protein protein : proteins) { this.predict(protein); } } /** * Predicts transmembrane residues for a given protein. * * @param protein */ public void predict(Protein protein) { if (protein == null || protein.getPssm() == null) {return;} Pssm pssm = protein.getPssm(); int length = pssm.getLength(); int[] scoresSol = new int[length];
[ "\t\tint[] \t\tscoresTmh \t= new int[length];" ]
569
lcc
java
null
86d39eb1a6f382a4d98e5d61ed62ae7c8942fd177b543add