repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
zhenzhai/edx-platform | common/djangoapps/student/tests/test_email.py | 1 | 18217 |
import json
import unittest
from student.tests.factories import UserFactory, RegistrationFactory, PendingEmailChangeFactory
from student.views import (
reactivation_email_for_user, do_email_change_request, confirm_email_change,
validate_new_email, SETTING_CHANGE_INITIATED
)
from student.models import UserProfile, PendingEmailChange
from django.core.urlresolvers import reverse
from django.core import mail
from django.contrib.auth.models import User
from django.db import transaction
from django.test import TestCase, TransactionTestCase
from django.test.client import RequestFactory
from mock import Mock, patch
from django.http import HttpResponse
from django.conf import settings
from edxmako.shortcuts import render_to_string
from util.request import safe_get_host
from util.testing import EventTestMixin
from openedx.core.djangoapps.theming.tests.test_util import with_is_edx_domain
from openedx.core.djangoapps.theming import helpers as theming_helpers
class TestException(Exception):
"""Exception used for testing that nothing will catch explicitly"""
pass
def mock_render_to_string(template_name, context):
"""Return a string that encodes template_name and context"""
return str((template_name, sorted(context.iteritems())))
def mock_render_to_response(template_name, context):
"""Return an HttpResponse with content that encodes template_name and context"""
# This simulates any db access in the templates.
UserProfile.objects.exists()
return HttpResponse(mock_render_to_string(template_name, context))
class EmailTestMixin(object):
"""Adds useful assertions for testing `email_user`"""
def assertEmailUser(self, email_user, subject_template, subject_context, body_template, body_context):
"""Assert that `email_user` was used to send and email with the supplied subject and body
`email_user`: The mock `django.contrib.auth.models.User.email_user` function
to verify
`subject_template`: The template to have been used for the subject
`subject_context`: The context to have been used for the subject
`body_template`: The template to have been used for the body
`body_context`: The context to have been used for the body
"""
email_user.assert_called_with(
mock_render_to_string(subject_template, subject_context),
mock_render_to_string(body_template, body_context),
theming_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
)
def append_allowed_hosts(self, hostname):
""" Append hostname to settings.ALLOWED_HOSTS """
settings.ALLOWED_HOSTS.append(hostname)
self.addCleanup(settings.ALLOWED_HOSTS.pop)
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
class ActivationEmailTests(TestCase):
"""Test sending of the activation email. """
ACTIVATION_SUBJECT = "Activate Your edX Account"
# Text fragments we expect in the body of an email
# sent from an OpenEdX installation.
OPENEDX_FRAGMENTS = [
"Thank you for signing up for {platform}.".format(platform=settings.PLATFORM_NAME),
"http://edx.org/activate/",
(
"if you require assistance, check the help section of the "
"{platform} website".format(platform=settings.PLATFORM_NAME)
)
]
# Text fragments we expect in the body of an email
# sent from an EdX-controlled domain.
EDX_DOMAIN_FRAGMENTS = [
"Thank you for signing up for {platform}".format(platform=settings.PLATFORM_NAME),
"http://edx.org/activate/",
"https://www.edx.org/contact-us",
"This email was automatically sent by edx.org"
]
def setUp(self):
super(ActivationEmailTests, self).setUp()
def test_activation_email(self):
self._create_account()
self._assert_activation_email(self.ACTIVATION_SUBJECT, self.OPENEDX_FRAGMENTS)
@with_is_edx_domain(True)
def test_activation_email_edx_domain(self):
self._create_account()
self._assert_activation_email(self.ACTIVATION_SUBJECT, self.EDX_DOMAIN_FRAGMENTS)
def _create_account(self):
"""Create an account, triggering the activation email. """
url = reverse('create_account')
params = {
'username': 'test_user',
'email': 'test_user@example.com',
'password': 'edx',
'name': 'Test User',
'honor_code': True,
'terms_of_service': True
}
resp = self.client.post(url, params)
self.assertEqual(
resp.status_code, 200,
msg=u"Could not create account (status {status}). The response was {response}".format(
status=resp.status_code,
response=resp.content
)
)
def _assert_activation_email(self, subject, body_fragments):
"""Verify that the activation email was sent. """
self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
self.assertEqual(msg.subject, subject)
for fragment in body_fragments:
self.assertIn(fragment, msg.body)
@patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
@patch('django.contrib.auth.models.User.email_user')
class ReactivationEmailTests(EmailTestMixin, TestCase):
"""Test sending a reactivation email to a user"""
def setUp(self):
super(ReactivationEmailTests, self).setUp()
self.user = UserFactory.create()
self.unregisteredUser = UserFactory.create()
self.registration = RegistrationFactory.create(user=self.user)
def reactivation_email(self, user):
"""
Send the reactivation email to the specified user,
and return the response as json data.
"""
return json.loads(reactivation_email_for_user(user).content)
def assertReactivateEmailSent(self, email_user):
"""Assert that the correct reactivation email has been sent"""
context = {
'name': self.user.profile.name,
'key': self.registration.activation_key
}
self.assertEmailUser(
email_user,
'emails/activation_email_subject.txt',
context,
'emails/activation_email.txt',
context
)
# Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
request = RequestFactory().post('unused_url')
request.user = self.user
request.META['HTTP_HOST'] = "aGenericValidHostName"
self.append_allowed_hosts("aGenericValidHostName")
with patch('edxmako.request_context.get_current_request', return_value=request):
body = render_to_string('emails/activation_email.txt', context)
host = safe_get_host(request)
self.assertIn(host, body)
def test_reactivation_email_failure(self, email_user):
self.user.email_user.side_effect = Exception
response_data = self.reactivation_email(self.user)
self.assertReactivateEmailSent(email_user)
self.assertFalse(response_data['success'])
def test_reactivation_for_unregistered_user(self, email_user):
"""
Test that trying to send a reactivation email to an unregistered
user fails without throwing a 500 error.
"""
response_data = self.reactivation_email(self.unregisteredUser)
self.assertFalse(response_data['success'])
def test_reactivation_email_success(self, email_user):
response_data = self.reactivation_email(self.user)
self.assertReactivateEmailSent(email_user)
self.assertTrue(response_data['success'])
class EmailChangeRequestTests(EventTestMixin, TestCase):
"""Test changing a user's email address"""
def setUp(self):
super(EmailChangeRequestTests, self).setUp('student.views.tracker')
self.user = UserFactory.create()
self.new_email = 'new.email@edx.org'
self.req_factory = RequestFactory()
self.request = self.req_factory.post('unused_url', data={
'password': 'test',
'new_email': self.new_email
})
self.request.user = self.user
self.user.email_user = Mock()
def do_email_validation(self, email):
"""Executes validate_new_email, returning any resulting error message. """
try:
validate_new_email(self.request.user, email)
except ValueError as err:
return err.message
def do_email_change(self, user, email, activation_key=None):
"""Executes do_email_change_request, returning any resulting error message. """
try:
do_email_change_request(user, email, activation_key)
except ValueError as err:
return err.message
def assertFailedRequest(self, response_data, expected_error):
"""Assert that `response_data` indicates a failed request that returns `expected_error`"""
self.assertFalse(response_data['success'])
self.assertEquals(expected_error, response_data['error'])
self.assertFalse(self.user.email_user.called)
@patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
def test_duplicate_activation_key(self):
"""Assert that if two users change Email address simultaneously, no error is thrown"""
# New emails for the users
user1_new_email = "valid_user1_email@example.com"
user2_new_email = "valid_user2_email@example.com"
# Create a another user 'user2' & make request for change email
user2 = UserFactory.create(email=self.new_email, password="test2")
# Send requests & ensure no error was thrown
self.assertIsNone(self.do_email_change(self.user, user1_new_email))
self.assertIsNone(self.do_email_change(user2, user2_new_email))
def test_invalid_emails(self):
"""
Assert the expected error message from the email validation method for an invalid
(improperly formatted) email address.
"""
for email in ('bad_email', 'bad_email@', '@bad_email'):
self.assertEqual(self.do_email_validation(email), 'Valid e-mail address required.')
def test_change_email_to_existing_value(self):
""" Test the error message if user attempts to change email to the existing value. """
self.assertEqual(self.do_email_validation(self.user.email), 'Old email is the same as the new email.')
def test_duplicate_email(self):
"""
Assert the expected error message from the email validation method for an email address
that is already in use by another account.
"""
UserFactory.create(email=self.new_email)
self.assertEqual(self.do_email_validation(self.new_email), 'An account with this e-mail already exists.')
@patch('django.core.mail.send_mail')
@patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
def test_email_failure(self, send_mail):
""" Test the return value if sending the email for the user to click fails. """
send_mail.side_effect = [Exception, None]
self.assertEqual(
self.do_email_change(self.user, "valid@email.com"),
'Unable to send email activation link. Please try again later.'
)
self.assert_no_events_were_emitted()
@patch('django.core.mail.send_mail')
@patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
def test_email_success(self, send_mail):
""" Test email was sent if no errors encountered. """
old_email = self.user.email
new_email = "valid@example.com"
registration_key = "test registration key"
self.assertIsNone(self.do_email_change(self.user, new_email, registration_key))
context = {
'key': registration_key,
'old_email': old_email,
'new_email': new_email
}
send_mail.assert_called_with(
mock_render_to_string('emails/email_change_subject.txt', context),
mock_render_to_string('emails/email_change.txt', context),
theming_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL),
[new_email]
)
self.assert_event_emitted(
SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'email', old=old_email, new=new_email
)
@patch('django.contrib.auth.models.User.email_user')
@patch('student.views.render_to_response', Mock(side_effect=mock_render_to_response, autospec=True))
@patch('student.views.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
class EmailChangeConfirmationTests(EmailTestMixin, TransactionTestCase):
"""Test that confirmation of email change requests function even in the face of exceptions thrown while sending email"""
def setUp(self):
super(EmailChangeConfirmationTests, self).setUp()
self.user = UserFactory.create()
self.profile = UserProfile.objects.get(user=self.user)
self.req_factory = RequestFactory()
self.request = self.req_factory.get('unused_url')
self.request.user = self.user
self.user.email_user = Mock()
self.pending_change_request = PendingEmailChangeFactory.create(user=self.user)
self.key = self.pending_change_request.activation_key
def assertRolledBack(self):
"""Assert that no changes to user, profile, or pending email have been made to the db"""
self.assertEquals(self.user.email, User.objects.get(username=self.user.username).email)
self.assertEquals(self.profile.meta, UserProfile.objects.get(user=self.user).meta)
self.assertEquals(1, PendingEmailChange.objects.count())
def assertFailedBeforeEmailing(self, email_user):
"""Assert that the function failed before emailing a user"""
self.assertRolledBack()
self.assertFalse(email_user.called)
def check_confirm_email_change(self, expected_template, expected_context):
"""Call `confirm_email_change` and assert that the content was generated as expected
`expected_template`: The name of the template that should have been used
to generate the content
`expected_context`: The context dictionary that should have been used to
generate the content
"""
response = confirm_email_change(self.request, self.key)
self.assertEquals(
mock_render_to_response(expected_template, expected_context).content,
response.content
)
def assertChangeEmailSent(self, email_user):
"""Assert that the correct email was sent to confirm an email change"""
context = {
'old_email': self.user.email,
'new_email': self.pending_change_request.new_email,
}
self.assertEmailUser(
email_user,
'emails/email_change_subject.txt',
context,
'emails/confirm_email_change.txt',
context
)
# Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
request = RequestFactory().post('unused_url')
request.user = self.user
request.META['HTTP_HOST'] = "aGenericValidHostName"
self.append_allowed_hosts("aGenericValidHostName")
with patch('edxmako.request_context.get_current_request', return_value=request):
body = render_to_string('emails/confirm_email_change.txt', context)
url = safe_get_host(request)
self.assertIn(url, body)
def test_not_pending(self, email_user):
self.key = 'not_a_key'
self.check_confirm_email_change('invalid_email_key.html', {})
self.assertFailedBeforeEmailing(email_user)
def test_duplicate_email(self, email_user):
UserFactory.create(email=self.pending_change_request.new_email)
self.check_confirm_email_change('email_exists.html', {})
self.assertFailedBeforeEmailing(email_user)
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS")
def test_old_email_fails(self, email_user):
email_user.side_effect = [Exception, None]
self.check_confirm_email_change('email_change_failed.html', {
'email': self.user.email,
})
self.assertRolledBack()
self.assertChangeEmailSent(email_user)
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS")
def test_new_email_fails(self, email_user):
email_user.side_effect = [None, Exception]
self.check_confirm_email_change('email_change_failed.html', {
'email': self.pending_change_request.new_email
})
self.assertRolledBack()
self.assertChangeEmailSent(email_user)
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', "Test only valid in LMS")
def test_successful_email_change(self, email_user):
self.check_confirm_email_change('email_change_successful.html', {
'old_email': self.user.email,
'new_email': self.pending_change_request.new_email
})
self.assertChangeEmailSent(email_user)
meta = json.loads(UserProfile.objects.get(user=self.user).meta)
self.assertIn('old_emails', meta)
self.assertEquals(self.user.email, meta['old_emails'][0][0])
self.assertEquals(
self.pending_change_request.new_email,
User.objects.get(username=self.user.username).email
)
self.assertEquals(0, PendingEmailChange.objects.count())
@patch('student.views.PendingEmailChange.objects.get', Mock(side_effect=TestException))
def test_always_rollback(self, _email_user):
connection = transaction.get_connection()
with patch.object(connection, 'rollback', wraps=connection.rollback) as mock_rollback:
with self.assertRaises(TestException):
confirm_email_change(self.request, self.key)
mock_rollback.assert_called_with()
| agpl-3.0 |
Azure/azure-sdk-for-python | sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2020_12_01/aio/_configuration.py | 1 | 3280 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class WebSiteManagementClientConfiguration(Configuration):
"""Configuration for WebSiteManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).
:type subscription_id: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
super(WebSiteManagementClientConfiguration, self).__init__(**kwargs)
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2020-12-01"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-web/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
| mit |
maferelo/saleor | saleor/menu/migrations/0001_initial.py | 3 | 3552 | # Generated by Django 2.0.2 on 2018-03-12 15:29
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [("product", "0052_slug_field_length"), ("page", "0001_initial")]
operations = [
migrations.CreateModel(
name="Menu",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("slug", models.SlugField(unique=True)),
],
options={
"permissions": (
("view_menu", "Can view menus"),
("edit_menu", "Can edit menus"),
)
},
),
migrations.CreateModel(
name="MenuItem",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=128)),
("sort_order", models.PositiveIntegerField(editable=False)),
("url", models.URLField(blank=True, max_length=256, null=True)),
("lft", models.PositiveIntegerField(db_index=True, editable=False)),
("rght", models.PositiveIntegerField(db_index=True, editable=False)),
("tree_id", models.PositiveIntegerField(db_index=True, editable=False)),
("level", models.PositiveIntegerField(db_index=True, editable=False)),
(
"category",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="product.Category",
),
),
(
"collection",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="product.Collection",
),
),
(
"menu",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="items",
to="menu.Menu",
),
),
(
"page",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="page.Page",
),
),
(
"parent",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="children",
to="menu.MenuItem",
),
),
],
options={"ordering": ("sort_order",)},
),
]
| bsd-3-clause |
vhumpa/dogtail | tests/gtkdemotest.py | 2 | 1676 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
class GtkDemoTest(unittest.TestCase):
"""
TestCase subclass which handles bringing up and shutting down gtk3-demo as a fixture. Used for writing other test
cases.
"""
def setUp(self):
import dogtail.config
dogtail.config.config.logDebugToStdOut = True
dogtail.config.config.logDebugToFile = False
import dogtail.utils
self.pid = dogtail.utils.run('gtk3-demo')
self.app = dogtail.tree.root.application('gtk3-demo')
def tearDown(self):
import os
import signal
import time
os.kill(self.pid, signal.SIGKILL)
os.system('killall gtk3-demo-application > /dev/null 2>&1')
# Sleep just enough to let the app actually die.
# AT-SPI doesn't like being hammered too fast.
time.sleep(0.5)
def runDemo(self, demoName, retry=True):
"""
Click on the named demo within the gtk3-demo app.
"""
tree = self.app.child(roleName="tree table")
tree.child(demoName, retry=retry).doActionNamed('activate')
def trap_stdout(function, args=None):
"""
Grab stdout output during function execution
"""
import sys
from io import StringIO
saved_stdout = sys.stdout
try:
out = StringIO()
sys.stdout = out
if type(args) is dict:
function(**args)
elif args:
function(args)
else:
function()
output = out.getvalue().strip()
finally:
sys.stdout = saved_stdout
return output
| gpl-2.0 |
AlexSnet/FabricDeployer | projects/migrations/0011_auto__add_taskusage.py | 18 | 4747 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TaskUsage'
db.create_table(u'projects_taskusage', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('times_used', self.gf('django.db.models.fields.PositiveIntegerField')(default=1)),
))
db.send_create_signal(u'projects', ['TaskUsage'])
def backwards(self, orm):
# Deleting model 'TaskUsage'
db.delete_table(u'projects_taskusage')
models = {
u'projects.configuration': {
'Meta': {'object_name': 'Configuration'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['projects.Project']"}),
'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['projects.Stage']", 'null': 'True', 'blank': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'})
},
u'projects.deployment': {
'Meta': {'object_name': 'Deployment'},
'comments': ('django.db.models.fields.TextField', [], {}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'output': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['projects.Stage']"}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '10'})
},
u'projects.project': {
'Meta': {'object_name': 'Project'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'number_of_deployments': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['projects.ProjectType']", 'null': 'True', 'blank': 'True'})
},
u'projects.projecttype': {
'Meta': {'object_name': 'ProjectType'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'projects.stage': {
'Meta': {'object_name': 'Stage'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['projects.Project']"})
},
u'projects.taskusage': {
'Meta': {'object_name': 'TaskUsage'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'times_used': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
}
}
complete_apps = ['projects'] | mit |
Peddle/hue | desktop/core/ext-py/boto-2.38.0/boto/ecs/__init__.py | 153 | 4177 | # Copyright (c) 2010 Chris Moyer http://coredumped.org/
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
import boto
from boto.connection import AWSQueryConnection, AWSAuthConnection
from boto.exception import BotoServerError
import time
import urllib
import xml.sax
from boto.ecs.item import ItemSet
from boto import handler
class ECSConnection(AWSQueryConnection):
"""
ECommerce Connection
For more information on how to use this module see:
http://blog.coredumped.org/2010/09/search-for-books-on-amazon-using-boto.html
"""
APIVersion = '2010-11-01'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, host='ecs.amazonaws.com',
debug=0, https_connection_factory=None, path='/',
security_token=None, profile_name=None):
super(ECSConnection, self).__init__(aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, path,
security_token=security_token,
profile_name=profile_name)
def _required_auth_capability(self):
return ['ecs']
def get_response(self, action, params, page=0, itemSet=None):
"""
Utility method to handle calls to ECS and parsing of responses.
"""
params['Service'] = "AWSECommerceService"
params['Operation'] = action
if page:
params['ItemPage'] = page
response = self.make_request(None, params, "/onca/xml")
body = response.read().decode('utf-8')
boto.log.debug(body)
if response.status != 200:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise BotoServerError(response.status, response.reason, body)
if itemSet is None:
rs = ItemSet(self, action, params, page)
else:
rs = itemSet
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body.encode('utf-8'), h)
if not rs.is_valid:
raise BotoServerError(response.status, '{Code}: {Message}'.format(**rs.errors[0]))
return rs
#
# Group methods
#
def item_search(self, search_index, **params):
"""
Returns items that satisfy the search criteria, including one or more search
indices.
For a full list of search terms,
:see: http://docs.amazonwebservices.com/AWSECommerceService/2010-09-01/DG/index.html?ItemSearch.html
"""
params['SearchIndex'] = search_index
return self.get_response('ItemSearch', params)
def item_lookup(self, **params):
"""
Returns items that satisfy the lookup query.
For a full list of parameters, see:
http://s3.amazonaws.com/awsdocs/Associates/2011-08-01/prod-adv-api-dg-2011-08-01.pdf
"""
return self.get_response('ItemLookup', params) | apache-2.0 |
bigzz/autotest | client/kernelexpand_unittest.py | 4 | 7934 | #!/usr/bin/python
import unittest
try:
import autotest.common as common
except ImportError:
import common
from kernelexpand import decompose_kernel
from kernelexpand import mirror_kernel_components
from autotest.client.shared.settings import settings
from autotest.client.shared.test_utils import mock
km = 'http://www.kernel.org/pub/linux/kernel/'
akpm = km + 'people/akpm/patches/'
gw = 'http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git'
sgw = 'http://git.kernel.org/?p=linux/kernel/git/stable/linux-stable.git'
kml = 'http://www.example.com/mirror/kernel.org/'
akpml = 'http://www.example.com/mirror/akpm/'
mirrorA = [
[akpm, akpml],
[km, kml],
]
class kernelexpandTest(unittest.TestCase):
def setUp(self):
self.god = mock.mock_god(ut=self)
settings.override_value('CLIENT', 'kernel_mirror', km)
settings.override_value('CLIENT', 'kernel_gitweb', '')
settings.override_value('CLIENT', 'stable_kernel_gitweb', '')
def tearDown(self):
self.god.unstub_all()
def test_decompose_simple(self):
correct = [[km + 'v2.6/linux-2.6.23.tar.bz2']]
sample = decompose_kernel('2.6.23')
self.assertEqual(sample, correct)
def test_decompose_simple_30(self):
correct = [[km + 'v3.x/linux-3.0.14.tar.bz2']]
sample = decompose_kernel('3.0.14')
self.assertEqual(sample, correct)
def test_decompose_simple_3X(self):
correct = [[km + 'v3.x/linux-3.2.1.tar.bz2']]
sample = decompose_kernel('3.2.1')
self.assertEqual(sample, correct)
def test_decompose_nominor_30(self):
correct = [[km + 'v3.x/linux-3.0.tar.bz2']]
sample = decompose_kernel('3.0')
self.assertEqual(sample, correct)
def test_decompose_nominor_26_fail(self):
success = False
try:
sample = decompose_kernel('2.6')
success = True
except NameError:
pass
except Exception, e:
self.fail('expected NameError, got something else')
if success:
self.fail('expected NameError, was successful')
def test_decompose_testing_26(self):
correct = km + 'v2.6/testing/linux-2.6.35-rc1.tar.bz2'
sample = decompose_kernel('2.6.35-rc1')[0][1]
self.assertEqual(sample, correct)
def test_decompose_testing_30(self):
correct = km + 'v3.x/testing/linux-3.2-rc1.tar.bz2'
sample = decompose_kernel('3.2-rc1')[0][0]
self.assertEqual(sample, correct)
def test_decompose_testing_30_fail(self):
success = False
try:
sample = decompose_kernel('3.2.1-rc1')
success = True
except NameError:
pass
except Exception, e:
self.fail('expected NameError, got something else')
if success:
self.fail('expected NameError, was successful')
def test_decompose_gitweb(self):
settings.override_value('CLIENT', 'kernel_gitweb', gw)
settings.override_value('CLIENT', 'stable_kernel_gitweb', sgw)
correct = [[km + 'v3.x/linux-3.0.tar.bz2', gw + ';a=snapshot;h=refs/tags/v3.0;sf=tgz']]
sample = decompose_kernel('3.0')
self.assertEqual(sample, correct)
def test_decompose_sha1(self):
settings.override_value('CLIENT', 'kernel_gitweb', gw)
settings.override_value('CLIENT', 'stable_kernel_gitweb', sgw)
correct = [[gw + ';a=snapshot;h=02f8c6aee8df3cdc935e9bdd4f2d020306035dbe;sf=tgz', sgw + ';a=snapshot;h=02f8c6aee8df3cdc935e9bdd4f2d020306035dbe;sf=tgz']]
sample = decompose_kernel('02f8c6aee8df3cdc935e9bdd4f2d020306035dbe')
self.assertEqual(sample, correct)
def test_decompose_fail(self):
success = False
try:
sample = decompose_kernel('1.0.0.0.0')
success = True
except NameError:
pass
except Exception, e:
self.fail('expected NameError, got something else')
if success:
self.fail('expected NameError, was successful')
def test_decompose_rcN(self):
correct = [
[km + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2']
]
sample = decompose_kernel('2.6.23-rc1')
self.assertEqual(sample, correct)
def test_decompose_mmN(self):
correct = [
[km + 'v2.6/linux-2.6.23.tar.bz2'],
[akpm + '2.6/2.6.23/2.6.23-mm1/2.6.23-mm1.bz2']
]
sample = decompose_kernel('2.6.23-mm1')
self.assertEqual(sample, correct)
def test_decompose_gitN(self):
correct = [
[km + 'v2.6/linux-2.6.23.tar.bz2'],
[km + 'v2.6/snapshots/old/patch-2.6.23-git1.bz2',
km + 'v2.6/snapshots/patch-2.6.23-git1.bz2']
]
sample = decompose_kernel('2.6.23-git1')
self.assertEqual(sample, correct)
def test_decompose_rcN_mmN(self):
correct = [
[km + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2'],
[akpm + '2.6/2.6.23-rc1/2.6.23-rc1-mm1/2.6.23-rc1-mm1.bz2']
]
sample = decompose_kernel('2.6.23-rc1-mm1')
self.assertEqual(sample, correct)
def test_mirrorA_simple(self):
correct = [
[kml + 'v2.6/linux-2.6.23.tar.bz2',
km + 'v2.6/linux-2.6.23.tar.bz2']
]
sample = decompose_kernel('2.6.23')
sample = mirror_kernel_components(mirrorA, sample)
self.assertEqual(sample, correct)
def test_mirrorA_rcN(self):
correct = [
[kml + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
kml + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2']
]
sample = decompose_kernel('2.6.23-rc1')
sample = mirror_kernel_components(mirrorA, sample)
self.assertEqual(sample, correct)
def test_mirrorA_mmN(self):
correct = [
[kml + 'v2.6/linux-2.6.23.tar.bz2',
km + 'v2.6/linux-2.6.23.tar.bz2'],
[akpml + '2.6/2.6.23/2.6.23-mm1/2.6.23-mm1.bz2',
kml + 'people/akpm/patches/2.6/2.6.23/2.6.23-mm1/2.6.23-mm1.bz2',
akpm + '2.6/2.6.23/2.6.23-mm1/2.6.23-mm1.bz2']
]
sample = decompose_kernel('2.6.23-mm1')
sample = mirror_kernel_components(mirrorA, sample)
self.assertEqual(sample, correct)
def test_mirrorA_gitN(self):
correct = [
[kml + 'v2.6/linux-2.6.23.tar.bz2',
km + 'v2.6/linux-2.6.23.tar.bz2'],
[kml + 'v2.6/snapshots/old/patch-2.6.23-git1.bz2',
kml + 'v2.6/snapshots/patch-2.6.23-git1.bz2',
km + 'v2.6/snapshots/old/patch-2.6.23-git1.bz2',
km + 'v2.6/snapshots/patch-2.6.23-git1.bz2']
]
sample = decompose_kernel('2.6.23-git1')
sample = mirror_kernel_components(mirrorA, sample)
self.assertEqual(sample, correct)
def test_mirrorA_rcN_mmN(self):
correct = [
[kml + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
kml + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/v2.6.23/linux-2.6.23-rc1.tar.bz2',
km + 'v2.6/testing/linux-2.6.23-rc1.tar.bz2'],
[akpml + '2.6/2.6.23-rc1/2.6.23-rc1-mm1/2.6.23-rc1-mm1.bz2',
kml + 'people/akpm/patches/2.6/2.6.23-rc1/2.6.23-rc1-mm1/2.6.23-rc1-mm1.bz2',
akpm + '2.6/2.6.23-rc1/2.6.23-rc1-mm1/2.6.23-rc1-mm1.bz2']
]
sample = decompose_kernel('2.6.23-rc1-mm1')
sample = mirror_kernel_components(mirrorA, sample)
self.assertEqual(sample, correct)
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
kawamon/hue | desktop/core/ext-py/requests-kerberos-0.12.0/requests_kerberos/kerberos_.py | 2 | 21008 | try:
import kerberos
except ImportError:
import winkerberos as kerberos
import logging
import threading
import re
import sys
import warnings
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import UnsupportedAlgorithm
from requests.auth import AuthBase
from requests.models import Response
from requests.compat import urlparse, StringIO
from requests.structures import CaseInsensitiveDict
from requests.cookies import cookiejar_from_dict
from requests.packages.urllib3 import HTTPResponse
from .exceptions import MutualAuthenticationError, KerberosExchangeError
log = logging.getLogger(__name__)
# Different types of mutual authentication:
# with mutual_authentication set to REQUIRED, all responses will be
# authenticated with the exception of errors. Errors will have their contents
# and headers stripped. If a non-error response cannot be authenticated, a
# MutualAuthenticationError exception will be raised.
# with mutual_authentication set to OPTIONAL, mutual authentication will be
# attempted if supported, and if supported and failed, a
# MutualAuthenticationError exception will be raised. Responses which do not
# support mutual authentication will be returned directly to the user.
# with mutual_authentication set to DISABLED, mutual authentication will not be
# attempted, even if supported.
REQUIRED = 1
OPTIONAL = 2
DISABLED = 3
class NoCertificateRetrievedWarning(Warning):
pass
class UnknownSignatureAlgorithmOID(Warning):
pass
class SanitizedResponse(Response):
"""The :class:`Response <Response>` object, which contains a server's
response to an HTTP request.
This differs from `requests.models.Response` in that it's headers and
content have been sanitized. This is only used for HTTP Error messages
which do not support mutual authentication when mutual authentication is
required."""
def __init__(self, response):
super(SanitizedResponse, self).__init__()
self.status_code = response.status_code
self.encoding = response.encoding
self.raw = response.raw
self.reason = response.reason
self.url = response.url
self.request = response.request
self.connection = response.connection
self._content_consumed = True
self._content = ""
self.cookies = cookiejar_from_dict({})
self.headers = CaseInsensitiveDict()
self.headers['content-length'] = '0'
for header in ('date', 'server'):
if header in response.headers:
self.headers[header] = response.headers[header]
def _negotiate_value(response):
"""Extracts the gssapi authentication token from the appropriate header"""
if hasattr(_negotiate_value, 'regex'):
regex = _negotiate_value.regex
else:
# There's no need to re-compile this EVERY time it is called. Compile
# it once and you won't have the performance hit of the compilation.
regex = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)
_negotiate_value.regex = regex
authreq = response.headers.get('www-authenticate', None)
if authreq:
match_obj = regex.search(authreq)
if match_obj:
return match_obj.group(1)
return None
def _get_certificate_hash(certificate_der):
# https://tools.ietf.org/html/rfc5929#section-4.1
cert = x509.load_der_x509_certificate(certificate_der, default_backend())
try:
hash_algorithm = cert.signature_hash_algorithm
except UnsupportedAlgorithm as ex:
warnings.warn("Failed to get signature algorithm from certificate, "
"unable to pass channel bindings: %s" % str(ex), UnknownSignatureAlgorithmOID)
return None
# if the cert signature algorithm is either md5 or sha1 then use sha256
# otherwise use the signature algorithm
if hash_algorithm.name in ['md5', 'sha1']:
digest = hashes.Hash(hashes.SHA256(), default_backend())
else:
digest = hashes.Hash(hash_algorithm, default_backend())
digest.update(certificate_der)
certificate_hash = digest.finalize()
return certificate_hash
def _get_channel_bindings_application_data(response):
"""
https://tools.ietf.org/html/rfc5929 4. The 'tls-server-end-point' Channel Binding Type
Gets the application_data value for the 'tls-server-end-point' CBT Type.
This is ultimately the SHA256 hash of the certificate of the HTTPS endpoint
appended onto tls-server-end-point. This value is then passed along to the
kerberos library to bind to the auth response. If the socket is not an SSL
socket or the raw HTTP object is not a urllib3 HTTPResponse then None will
be returned and the Kerberos auth will use GSS_C_NO_CHANNEL_BINDINGS
:param response: The original 401 response from the server
:return: byte string used on the application_data.value field on the CBT struct
"""
application_data = None
raw_response = response.raw
if isinstance(raw_response, HTTPResponse):
try:
if sys.version_info > (3, 0):
socket = raw_response._fp.fp.raw._sock
else:
socket = raw_response._fp.fp._sock
except AttributeError:
warnings.warn("Failed to get raw socket for CBT; has urllib3 impl changed",
NoCertificateRetrievedWarning)
else:
try:
server_certificate = socket.getpeercert(True)
except AttributeError:
pass
else:
certificate_hash = _get_certificate_hash(server_certificate)
application_data = b'tls-server-end-point:' + certificate_hash
else:
warnings.warn(
"Requests is running with a non urllib3 backend, cannot retrieve server certificate for CBT",
NoCertificateRetrievedWarning)
return application_data
class HTTPKerberosAuth(AuthBase):
"""Attaches HTTP GSSAPI/Kerberos Authentication to the given Request
object."""
def __init__(
self, mutual_authentication=REQUIRED,
service="HTTP", delegate=False, force_preemptive=False,
principal=None, hostname_override=None,
sanitize_mutual_error_response=True, send_cbt=True):
self.context = {}
self.mutual_authentication = mutual_authentication
self.delegate = delegate
self.pos = None
self.service = service
self.force_preemptive = force_preemptive
self.principal = principal
self.hostname_override = hostname_override
self.sanitize_mutual_error_response = sanitize_mutual_error_response
self.auth_done = False
self.winrm_encryption_available = hasattr(kerberos, 'authGSSWinRMEncryptMessage')
# Set the CBT values populated after the first response
self.send_cbt = send_cbt
self.cbt_binding_tried = False
self.cbt_struct = None
def generate_request_header(self, response, host, host_port_thread=False, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
if not host_port_thread:
# Initialize uniq key for the self.context dictionary
host_port_thread = "%s_%s_%s" % (urlparse(response.url).hostname,
urlparse(response.url).port,
threading.current_thread().ident)
log.debug("generate_request_header(): host_port_thread: {0}".format(host_port_thread))
# Flags used by kerberos module.
gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
if self.delegate:
gssflags |= kerberos.GSS_C_DELEG_FLAG
try:
kerb_stage = "authGSSClientInit()"
# contexts still need to be stored by host_port_thread, but hostname_override
# allows use of an arbitrary hostname for the kerberos exchange
# (eg, in cases of aliased hosts, internal vs external, CNAMEs
# w/ name-based HTTP hosting)
kerb_host = self.hostname_override if self.hostname_override is not None else host
kerb_spn = "{0}@{1}".format(self.service, kerb_host)
result, self.context[host_port_thread] = kerberos.authGSSClientInit(kerb_spn,
gssflags=gssflags, principal=self.principal)
if result < 1:
raise EnvironmentError(result, kerb_stage)
# if we have a previous response from the server, use it to continue
# the auth process, otherwise use an empty value
negotiate_resp_value = '' if is_preemptive else _negotiate_value(response)
kerb_stage = "authGSSClientStep()"
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host_port_thread],
negotiate_resp_value,
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host_port_thread],
negotiate_resp_value)
if result < 0:
raise EnvironmentError(result, kerb_stage)
kerb_stage = "authGSSClientResponse()"
gss_response = kerberos.authGSSClientResponse(self.context[host_port_thread])
return "Negotiate {0}".format(gss_response)
except kerberos.GSSError as error:
log.exception(
"generate_request_header(): {0} failed:".format(kerb_stage))
log.exception(error)
raise KerberosExchangeError("%s failed: %s" % (kerb_stage, str(error.args)))
except EnvironmentError as error:
# ensure we raised this for translation to KerberosExchangeError
# by comparing errno to result, re-raise if not
if error.errno != result:
raise
message = "{0} failed, result: {1}".format(kerb_stage, result)
log.error("generate_request_header(): {0}".format(message))
raise KerberosExchangeError(message)
def authenticate_user(self, response, **kwargs):
"""Handles user authentication with gssapi/kerberos"""
host = urlparse(response.url).hostname
# Initialize uniq key for the self.context dictionary
host_port_thread = "%s_%s_%s" % (urlparse(response.url).hostname,
urlparse(response.url).port,
threading.current_thread().ident)
try:
auth_header = self.generate_request_header(response, host)
except KerberosExchangeError:
# GSS Failure, return existing response
return response
log.debug("authenticate_user(): Authorization header: {0}".format(
auth_header))
response.request.headers['Authorization'] = auth_header
# Consume the content so we can reuse the connection for the next
# request.
response.content
response.raw.release_conn()
_r = response.connection.send(response.request, **kwargs)
_r.history.append(response)
log.debug("authenticate_user(): returning {0}".format(_r))
return _r
def handle_401(self, response, **kwargs):
"""Handles 401's, attempts to use gssapi/kerberos authentication"""
log.debug("handle_401(): Handling: 401")
if _negotiate_value(response) is not None:
_r = self.authenticate_user(response, **kwargs)
log.debug("handle_401(): returning {0}".format(_r))
return _r
else:
log.debug("handle_401(): Kerberos is not supported")
log.debug("handle_401(): returning {0}".format(response))
return response
def handle_other(self, response):
"""Handles all responses with the exception of 401s.
This is necessary so that we can authenticate responses if requested"""
log.debug("handle_other(): Handling: %d" % response.status_code)
if self.mutual_authentication in (REQUIRED, OPTIONAL) and not self.auth_done:
is_http_error = response.status_code >= 400
if _negotiate_value(response) is not None:
log.debug("handle_other(): Authenticating the server")
if not self.authenticate_server(response):
# Mutual authentication failure when mutual auth is wanted,
# raise an exception so the user doesn't use an untrusted
# response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
# Authentication successful
log.debug("handle_other(): returning {0}".format(response))
self.auth_done = True
return response
elif is_http_error or self.mutual_authentication == OPTIONAL:
if not response.ok:
log.error("handle_other(): Mutual authentication unavailable "
"on {0} response".format(response.status_code))
if(self.mutual_authentication == REQUIRED and
self.sanitize_mutual_error_response):
return SanitizedResponse(response)
else:
return response
else:
# Unable to attempt mutual authentication when mutual auth is
# required, raise an exception so the user doesn't use an
# untrusted response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
else:
log.debug("handle_other(): returning {0}".format(response))
return response
def authenticate_server(self, response):
"""
Uses GSSAPI to authenticate the server.
Returns True on success, False on failure.
"""
log.debug("authenticate_server(): Authenticate header: {0}".format(
_negotiate_value(response)))
host = urlparse(response.url).hostname
# Initialize uniq key for the self.context dictionary
host_port_thread = "%s_%s_%s" % (urlparse(response.url).hostname,
urlparse(response.url).port,
threading.current_thread().ident)
try:
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host_port_thread],
_negotiate_value(response),
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host_port_thread],
_negotiate_value(response))
except kerberos.GSSError as e:
# Since Isilon's webhdfs host and port will be the same for
# both 'NameNode' and 'DataNode' connections, Mutual Authentication will fail here
# due to the fact that a 307 redirect is made to the same host and port.
# host_port_thread will be the same when calling authGssClientStep().
# If we get a "Context is already fully established" response, that is OK if
# the response.url contains "datanode=true". "datanode=true" is Isilon-specific
# in that it is not part of CDH. It is an indicator to the Isilon server
# that the operation is a DataNode operation.
if 'datanode=true' in response.url and 'Context is already fully established' in e.args[1]:
log.debug("Caught Isilon mutual auth exception %s - %s" % (response.url, e.args[1][0]))
return True
log.exception("authenticate_server(): authGSSClientStep() failed:")
return False
if result < 1:
log.error("authenticate_server(): authGSSClientStep() failed: "
"{0}".format(result))
return False
log.debug("authenticate_server(): returning {0}".format(response))
return True
def handle_response(self, response, **kwargs):
"""Takes the given response and tries kerberos-auth, as needed."""
num_401s = kwargs.pop('num_401s', 0)
# Check if we have already tried to get the CBT data value
if not self.cbt_binding_tried and self.send_cbt:
# If we haven't tried, try getting it now
cbt_application_data = _get_channel_bindings_application_data(response)
if cbt_application_data:
# Only the latest version of pykerberos has this method available
try:
self.cbt_struct = kerberos.channelBindings(application_data=cbt_application_data)
except AttributeError:
# Using older version set to None
self.cbt_struct = None
# Regardless of the result, set tried to True so we don't waste time next time
self.cbt_binding_tried = True
if self.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
response.request.body.seek(self.pos)
if response.status_code == 401 and num_401s < 2:
# 401 Unauthorized. Handle it, and if it still comes back as 401,
# that means authentication failed.
_r = self.handle_401(response, **kwargs)
log.debug("handle_response(): returning %s", _r)
log.debug("handle_response() has seen %d 401 responses", num_401s)
num_401s += 1
return self.handle_response(_r, num_401s=num_401s, **kwargs)
elif response.status_code == 401 and num_401s >= 2:
# Still receiving 401 responses after attempting to handle them.
# Authentication has failed. Return the 401 response.
log.debug("handle_response(): returning 401 %s", response)
return response
else:
_r = self.handle_other(response)
log.debug("handle_response(): returning %s", _r)
return _r
def deregister(self, response):
"""Deregisters the response handler"""
response.request.deregister_hook('response', self.handle_response)
def wrap_winrm(self, host, message):
if not self.winrm_encryption_available:
raise NotImplementedError("WinRM encryption is not available on the installed version of pykerberos")
return kerberos.authGSSWinRMEncryptMessage(self.context[host], message)
def unwrap_winrm(self, host, message, header):
if not self.winrm_encryption_available:
raise NotImplementedError("WinRM encryption is not available on the installed version of pykerberos")
return kerberos.authGSSWinRMDecryptMessage(self.context[host], message, header)
def __call__(self, request):
if self.force_preemptive and not self.auth_done:
# add Authorization header before we receive a 401
# by the 401 handler
host = urlparse(request.url).hostname
# Initialize uniq key for the self.context dictionary
host_port_thread = "%s_%s_%s" % (urlparse(request.url).hostname,
urlparse(request.url).port,
threading.current_thread().ident)
auth_header = self.generate_request_header(None, host, host_port_thread=host_port_thread, is_preemptive=True)
log.debug("HTTPKerberosAuth: Preemptive Authorization header: {0}".format(auth_header))
request.headers['Authorization'] = auth_header
request.register_hook('response', self.handle_response)
try:
self.pos = request.body.tell()
except AttributeError:
# In the case of HTTPKerberosAuth being reused and the body
# of the previous request was a file-like object, pos has
# the file position of the previous body. Ensure it's set to
# None.
self.pos = None
return request
| apache-2.0 |
odoo-turkiye/odoo | addons/sale_margin/__init__.py | 441 | 1042 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# 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/>.
#
##############################################################################
import sale_margin
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
alihalabyah/flexx | flexx/react/functional.py | 21 | 1381 | """
Functions to allow *Functional* Reactive Programming. Each of these
functions produces a new signal.
"""
import sys
from .signals import Signal
from .signals import undefined
def merge(*signals):
""" Merge all signal values into a tuple.
"""
frame = sys._getframe(1)
def _merge(*values):
return values
return Signal(_merge, signals, frame)
def filter(func, signal):
""" Filter the values of a signal.
The given function receives the signal value as an argument. If the
function returns Truthy, the value is passed, otherwise not.
"""
frame = sys._getframe(1)
def _filter(value):
if func(value):
return value
return undefined
return Signal(_filter, [signal], frame)
def map(func, signal):
""" Map a function to the value of a signal.
"""
frame = sys._getframe(1)
def _map(value):
return func(value)
return Signal(_map, [signal], frame)
def reduce(func, signal, initval=None):
""" Accumulate values, similar to Python's reduce() function.
"""
frame = sys._getframe(1)
val = []
if initval is not None:
val.append(initval)
def _accumulate(value):
if not val:
val.append(value)
else:
val[0] = func(value, val[0])
return val[0]
return Signal(_accumulate, [signal], frame)
| bsd-2-clause |
haoran8899/cdnt-ud-lxde-vnc | noVNC/utils/websocket.py | 11 | 37699 | #!/usr/bin/env python
'''
Python WebSocket library with support for "wss://" encryption.
Copyright 2011 Joel Martin
Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
Supports following protocol versions:
- http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07
- http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10
- http://tools.ietf.org/html/rfc6455
You can make a cert/key with openssl using:
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
as taken from http://docs.python.org/dev/library/ssl.html#certificates
'''
import os, sys, time, errno, signal, socket, select, logging
import array, struct
from base64 import b64encode, b64decode
# Imports that vary by python version
# python 3.0 differences
if sys.hexversion > 0x3000000:
b2s = lambda buf: buf.decode('latin_1')
s2b = lambda s: s.encode('latin_1')
s2a = lambda s: s
else:
b2s = lambda buf: buf # No-op
s2b = lambda s: s # No-op
s2a = lambda s: [ord(c) for c in s]
try: from io import StringIO
except: from cStringIO import StringIO
try: from http.server import SimpleHTTPRequestHandler
except: from SimpleHTTPServer import SimpleHTTPRequestHandler
# python 2.6 differences
try: from hashlib import sha1
except: from sha import sha as sha1
# python 2.5 differences
try:
from struct import pack, unpack_from
except:
from struct import pack
def unpack_from(fmt, buf, offset=0):
slice = buffer(buf, offset, struct.calcsize(fmt))
return struct.unpack(fmt, slice)
# Degraded functionality if these imports are missing
for mod, msg in [('numpy', 'HyBi protocol will be slower'),
('ssl', 'TLS/SSL/wss is disabled'),
('multiprocessing', 'Multi-Processing is disabled'),
('resource', 'daemonizing is disabled')]:
try:
globals()[mod] = __import__(mod)
except ImportError:
globals()[mod] = None
print("WARNING: no '%s' module, %s" % (mod, msg))
if multiprocessing and sys.platform == 'win32':
# make sockets pickle-able/inheritable
import multiprocessing.reduction
# HTTP handler with WebSocket upgrade support
class WebSocketRequestHandler(SimpleHTTPRequestHandler):
"""
WebSocket Request Handler Class, derived from SimpleHTTPRequestHandler.
Must be sub-classed with new_websocket_client method definition.
The request handler can be configured by setting optional
attributes on the server object:
* only_upgrade: If true, SimpleHTTPRequestHandler will not be enabled,
only websocket is allowed.
* verbose: If true, verbose logging is activated.
* daemon: Running as daemon, do not write to console etc
* record: Record raw frame data as JavaScript array into specified filename
* run_once: Handle a single request
* handler_id: A sequence number for this connection, appended to record filename
"""
buffer_size = 65536
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
server_version = "WebSockify"
protocol_version = "HTTP/1.1"
# An exception while the WebSocket client was connected
class CClose(Exception):
pass
def __init__(self, req, addr, server):
# Retrieve a few configuration variables from the server
self.only_upgrade = getattr(server, "only_upgrade", False)
self.verbose = getattr(server, "verbose", False)
self.daemon = getattr(server, "daemon", False)
self.record = getattr(server, "record", False)
self.run_once = getattr(server, "run_once", False)
self.rec = None
self.handler_id = getattr(server, "handler_id", False)
self.file_only = getattr(server, "file_only", False)
self.traffic = getattr(server, "traffic", False)
self.logger = getattr(server, "logger", None)
if self.logger is None:
self.logger = WebSocketServer.get_logger()
SimpleHTTPRequestHandler.__init__(self, req, addr, server)
@staticmethod
def unmask(buf, hlen, plen):
pstart = hlen + 4
pend = pstart + plen
if numpy:
b = c = s2b('')
if plen >= 4:
mask = numpy.frombuffer(buf, dtype=numpy.dtype('<u4'),
offset=hlen, count=1)
data = numpy.frombuffer(buf, dtype=numpy.dtype('<u4'),
offset=pstart, count=int(plen / 4))
#b = numpy.bitwise_xor(data, mask).data
b = numpy.bitwise_xor(data, mask).tostring()
if plen % 4:
#self.msg("Partial unmask")
mask = numpy.frombuffer(buf, dtype=numpy.dtype('B'),
offset=hlen, count=(plen % 4))
data = numpy.frombuffer(buf, dtype=numpy.dtype('B'),
offset=pend - (plen % 4),
count=(plen % 4))
c = numpy.bitwise_xor(data, mask).tostring()
return b + c
else:
# Slower fallback
mask = buf[hlen:hlen+4]
data = array.array('B')
mask = s2a(mask)
data.fromstring(buf[pstart:pend])
for i in range(len(data)):
data[i] ^= mask[i % 4]
return data.tostring()
@staticmethod
def encode_hybi(buf, opcode, base64=False):
""" Encode a HyBi style WebSocket frame.
Optional opcode:
0x0 - continuation
0x1 - text frame (base64 encode buf)
0x2 - binary frame (use raw buf)
0x8 - connection close
0x9 - ping
0xA - pong
"""
if base64:
buf = b64encode(buf)
b1 = 0x80 | (opcode & 0x0f) # FIN + opcode
payload_len = len(buf)
if payload_len <= 125:
header = pack('>BB', b1, payload_len)
elif payload_len > 125 and payload_len < 65536:
header = pack('>BBH', b1, 126, payload_len)
elif payload_len >= 65536:
header = pack('>BBQ', b1, 127, payload_len)
#self.msg("Encoded: %s", repr(header + buf))
return header + buf, len(header), 0
@staticmethod
def decode_hybi(buf, base64=False, logger=None):
""" Decode HyBi style WebSocket packets.
Returns:
{'fin' : 0_or_1,
'opcode' : number,
'masked' : boolean,
'hlen' : header_bytes_number,
'length' : payload_bytes_number,
'payload' : decoded_buffer,
'left' : bytes_left_number,
'close_code' : number,
'close_reason' : string}
"""
f = {'fin' : 0,
'opcode' : 0,
'masked' : False,
'hlen' : 2,
'length' : 0,
'payload' : None,
'left' : 0,
'close_code' : 1000,
'close_reason' : ''}
if logger is None:
logger = WebSocketServer.get_logger()
blen = len(buf)
f['left'] = blen
if blen < f['hlen']:
return f # Incomplete frame header
b1, b2 = unpack_from(">BB", buf)
f['opcode'] = b1 & 0x0f
f['fin'] = (b1 & 0x80) >> 7
f['masked'] = (b2 & 0x80) >> 7
f['length'] = b2 & 0x7f
if f['length'] == 126:
f['hlen'] = 4
if blen < f['hlen']:
return f # Incomplete frame header
(f['length'],) = unpack_from('>xxH', buf)
elif f['length'] == 127:
f['hlen'] = 10
if blen < f['hlen']:
return f # Incomplete frame header
(f['length'],) = unpack_from('>xxQ', buf)
full_len = f['hlen'] + f['masked'] * 4 + f['length']
if blen < full_len: # Incomplete frame
return f # Incomplete frame header
# Number of bytes that are part of the next frame(s)
f['left'] = blen - full_len
# Process 1 frame
if f['masked']:
# unmask payload
f['payload'] = WebSocketRequestHandler.unmask(buf, f['hlen'],
f['length'])
else:
logger.debug("Unmasked frame: %s" % repr(buf))
f['payload'] = buf[(f['hlen'] + f['masked'] * 4):full_len]
if base64 and f['opcode'] in [1, 2]:
try:
f['payload'] = b64decode(f['payload'])
except:
logger.exception("Exception while b64decoding buffer: %s" %
(repr(buf)))
raise
if f['opcode'] == 0x08:
if f['length'] >= 2:
f['close_code'] = unpack_from(">H", f['payload'])[0]
if f['length'] > 3:
f['close_reason'] = f['payload'][2:]
return f
#
# WebSocketRequestHandler logging/output functions
#
def print_traffic(self, token="."):
""" Show traffic flow mode. """
if self.traffic:
sys.stdout.write(token)
sys.stdout.flush()
def msg(self, msg, *args, **kwargs):
""" Output message with handler_id prefix. """
prefix = "% 3d: " % self.handler_id
self.logger.log(logging.INFO, "%s%s" % (prefix, msg), *args, **kwargs)
def vmsg(self, msg, *args, **kwargs):
""" Same as msg() but as debug. """
prefix = "% 3d: " % self.handler_id
self.logger.log(logging.DEBUG, "%s%s" % (prefix, msg), *args, **kwargs)
def warn(self, msg, *args, **kwargs):
""" Same as msg() but as warning. """
prefix = "% 3d: " % self.handler_id
self.logger.log(logging.WARN, "%s%s" % (prefix, msg), *args, **kwargs)
#
# Main WebSocketRequestHandler methods
#
def send_frames(self, bufs=None):
""" Encode and send WebSocket frames. Any frames already
queued will be sent first. If buf is not set then only queued
frames will be sent. Returns the number of pending frames that
could not be fully sent. If returned pending frames is greater
than 0, then the caller should call again when the socket is
ready. """
tdelta = int(time.time()*1000) - self.start_time
if bufs:
for buf in bufs:
if self.base64:
encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=1, base64=True)
else:
encbuf, lenhead, lentail = self.encode_hybi(buf, opcode=2, base64=False)
if self.rec:
self.rec.write("%s,\n" %
repr("{%s{" % tdelta
+ encbuf[lenhead:len(encbuf)-lentail]))
self.send_parts.append(encbuf)
while self.send_parts:
# Send pending frames
buf = self.send_parts.pop(0)
sent = self.request.send(buf)
if sent == len(buf):
self.print_traffic("<")
else:
self.print_traffic("<.")
self.send_parts.insert(0, buf[sent:])
break
return len(self.send_parts)
def recv_frames(self):
""" Receive and decode WebSocket frames.
Returns:
(bufs_list, closed_string)
"""
closed = False
bufs = []
tdelta = int(time.time()*1000) - self.start_time
buf = self.request.recv(self.buffer_size)
if len(buf) == 0:
closed = {'code': 1000, 'reason': "Client closed abruptly"}
return bufs, closed
if self.recv_part:
# Add partially received frames to current read buffer
buf = self.recv_part + buf
self.recv_part = None
while buf:
frame = self.decode_hybi(buf, base64=self.base64,
logger=self.logger)
#self.msg("Received buf: %s, frame: %s", repr(buf), frame)
if frame['payload'] == None:
# Incomplete/partial frame
self.print_traffic("}.")
if frame['left'] > 0:
self.recv_part = buf[-frame['left']:]
break
else:
if frame['opcode'] == 0x8: # connection close
closed = {'code': frame['close_code'],
'reason': frame['close_reason']}
break
self.print_traffic("}")
if self.rec:
start = frame['hlen']
end = frame['hlen'] + frame['length']
if frame['masked']:
recbuf = WebSocketRequestHandler.unmask(buf, frame['hlen'],
frame['length'])
else:
recbuf = buf[frame['hlen']:frame['hlen'] +
frame['length']]
self.rec.write("%s,\n" %
repr("}%s}" % tdelta + recbuf))
bufs.append(frame['payload'])
if frame['left']:
buf = buf[-frame['left']:]
else:
buf = ''
return bufs, closed
def send_close(self, code=1000, reason=''):
""" Send a WebSocket orderly close frame. """
msg = pack(">H%ds" % len(reason), code, reason)
buf, h, t = self.encode_hybi(msg, opcode=0x08, base64=False)
self.request.send(buf)
def do_websocket_handshake(self):
h = self.headers
prot = 'WebSocket-Protocol'
protocols = h.get('Sec-'+prot, h.get(prot, '')).split(',')
ver = h.get('Sec-WebSocket-Version')
if ver:
# HyBi/IETF version of the protocol
# HyBi-07 report version 7
# HyBi-08 - HyBi-12 report version 8
# HyBi-13 reports version 13
if ver in ['7', '8', '13']:
self.version = "hybi-%02d" % int(ver)
else:
self.send_error(400, "Unsupported protocol version %s" % ver)
return False
key = h['Sec-WebSocket-Key']
# Choose binary if client supports it
if 'binary' in protocols:
self.base64 = False
elif 'base64' in protocols:
self.base64 = True
else:
self.send_error(400, "Client must support 'binary' or 'base64' protocol")
return False
# Generate the hash value for the accept header
accept = b64encode(sha1(s2b(key + self.GUID)).digest())
self.send_response(101, "Switching Protocols")
self.send_header("Upgrade", "websocket")
self.send_header("Connection", "Upgrade")
self.send_header("Sec-WebSocket-Accept", b2s(accept))
if self.base64:
self.send_header("Sec-WebSocket-Protocol", "base64")
else:
self.send_header("Sec-WebSocket-Protocol", "binary")
self.end_headers()
return True
else:
self.send_error(400, "Missing Sec-WebSocket-Version header. Hixie protocols not supported.")
return False
def handle_websocket(self):
"""Upgrade a connection to Websocket, if requested. If this succeeds,
new_websocket_client() will be called. Otherwise, False is returned.
"""
if (self.headers.get('upgrade') and
self.headers.get('upgrade').lower() == 'websocket'):
if not self.do_websocket_handshake():
return False
# Indicate to server that a Websocket upgrade was done
self.server.ws_connection = True
# Initialize per client settings
self.send_parts = []
self.recv_part = None
self.start_time = int(time.time()*1000)
# client_address is empty with, say, UNIX domain sockets
client_addr = ""
is_ssl = False
try:
client_addr = self.client_address[0]
is_ssl = self.client_address[2]
except IndexError:
pass
if is_ssl:
self.stype = "SSL/TLS (wss://)"
else:
self.stype = "Plain non-SSL (ws://)"
self.log_message("%s: %s WebSocket connection", client_addr,
self.stype)
self.log_message("%s: Version %s, base64: '%s'", client_addr,
self.version, self.base64)
if self.path != '/':
self.log_message("%s: Path: '%s'", client_addr, self.path)
if self.record:
# Record raw frame data as JavaScript array
fname = "%s.%s" % (self.record,
self.handler_id)
self.log_message("opening record file: %s", fname)
self.rec = open(fname, 'w+')
encoding = "binary"
if self.base64: encoding = "base64"
self.rec.write("var VNC_frame_encoding = '%s';\n"
% encoding)
self.rec.write("var VNC_frame_data = [\n")
try:
self.new_websocket_client()
except self.CClose:
# Close the client
_, exc, _ = sys.exc_info()
self.send_close(exc.args[0], exc.args[1])
return True
else:
return False
def do_GET(self):
"""Handle GET request. Calls handle_websocket(). If unsuccessful,
and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called."""
if not self.handle_websocket():
if self.only_upgrade:
self.send_error(405, "Method Not Allowed")
else:
SimpleHTTPRequestHandler.do_GET(self)
def list_directory(self, path):
if self.file_only:
self.send_error(404, "No such file")
else:
return SimpleHTTPRequestHandler.list_directory(self, path)
def new_websocket_client(self):
""" Do something with a WebSockets client connection. """
raise Exception("WebSocketRequestHandler.new_websocket_client() must be overloaded")
def do_HEAD(self):
if self.only_upgrade:
self.send_error(405, "Method Not Allowed")
else:
SimpleHTTPRequestHandler.do_HEAD(self)
def finish(self):
if self.rec:
self.rec.write("'EOF'];\n")
self.rec.close()
def handle(self):
# When using run_once, we have a single process, so
# we cannot loop in BaseHTTPRequestHandler.handle; we
# must return and handle new connections
if self.run_once:
self.handle_one_request()
else:
SimpleHTTPRequestHandler.handle(self)
def log_request(self, code='-', size='-'):
if self.verbose:
SimpleHTTPRequestHandler.log_request(self, code, size)
class WebSocketServer(object):
"""
WebSockets server class.
As an alternative, the standard library SocketServer can be used
"""
policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
log_prefix = "websocket"
# An exception before the WebSocket connection was established
class EClose(Exception):
pass
class Terminate(Exception):
pass
def __init__(self, RequestHandlerClass, listen_host='',
listen_port=None, source_is_ipv6=False,
verbose=False, cert='', key='', ssl_only=None,
daemon=False, record='', web='',
file_only=False,
run_once=False, timeout=0, idle_timeout=0, traffic=False,
tcp_keepalive=True, tcp_keepcnt=None, tcp_keepidle=None,
tcp_keepintvl=None):
# settings
self.RequestHandlerClass = RequestHandlerClass
self.verbose = verbose
self.listen_host = listen_host
self.listen_port = listen_port
self.prefer_ipv6 = source_is_ipv6
self.ssl_only = ssl_only
self.daemon = daemon
self.run_once = run_once
self.timeout = timeout
self.idle_timeout = idle_timeout
self.traffic = traffic
self.launch_time = time.time()
self.ws_connection = False
self.handler_id = 1
self.logger = self.get_logger()
self.tcp_keepalive = tcp_keepalive
self.tcp_keepcnt = tcp_keepcnt
self.tcp_keepidle = tcp_keepidle
self.tcp_keepintvl = tcp_keepintvl
# Make paths settings absolute
self.cert = os.path.abspath(cert)
self.key = self.web = self.record = ''
if key:
self.key = os.path.abspath(key)
if web:
self.web = os.path.abspath(web)
if record:
self.record = os.path.abspath(record)
if self.web:
os.chdir(self.web)
self.only_upgrade = not self.web
# Sanity checks
if not ssl and self.ssl_only:
raise Exception("No 'ssl' module and SSL-only specified")
if self.daemon and not resource:
raise Exception("Module 'resource' required to daemonize")
# Show configuration
self.msg("WebSocket server settings:")
self.msg(" - Listen on %s:%s",
self.listen_host, self.listen_port)
self.msg(" - Flash security policy server")
if self.web:
self.msg(" - Web server. Web root: %s", self.web)
if ssl:
if os.path.exists(self.cert):
self.msg(" - SSL/TLS support")
if self.ssl_only:
self.msg(" - Deny non-SSL/TLS connections")
else:
self.msg(" - No SSL/TLS support (no cert file)")
else:
self.msg(" - No SSL/TLS support (no 'ssl' module)")
if self.daemon:
self.msg(" - Backgrounding (daemon)")
if self.record:
self.msg(" - Recording to '%s.*'", self.record)
#
# WebSocketServer static methods
#
@staticmethod
def get_logger():
return logging.getLogger("%s.%s" % (
WebSocketServer.log_prefix,
WebSocketServer.__class__.__name__))
@staticmethod
def socket(host, port=None, connect=False, prefer_ipv6=False,
unix_socket=None, use_ssl=False, tcp_keepalive=True,
tcp_keepcnt=None, tcp_keepidle=None, tcp_keepintvl=None):
""" Resolve a host (and optional port) to an IPv4 or IPv6
address. Create a socket. Bind to it if listen is set,
otherwise connect to it. Return the socket.
"""
flags = 0
if host == '':
host = None
if connect and not (port or unix_socket):
raise Exception("Connect mode requires a port")
if use_ssl and not ssl:
raise Exception("SSL socket requested but Python SSL module not loaded.");
if not connect and use_ssl:
raise Exception("SSL only supported in connect mode (for now)")
if not connect:
flags = flags | socket.AI_PASSIVE
if not unix_socket:
addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
socket.IPPROTO_TCP, flags)
if not addrs:
raise Exception("Could not resolve host '%s'" % host)
addrs.sort(key=lambda x: x[0])
if prefer_ipv6:
addrs.reverse()
sock = socket.socket(addrs[0][0], addrs[0][1])
if tcp_keepalive:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if tcp_keepcnt:
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT,
tcp_keepcnt)
if tcp_keepidle:
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE,
tcp_keepidle)
if tcp_keepintvl:
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL,
tcp_keepintvl)
if connect:
sock.connect(addrs[0][4])
if use_ssl:
sock = ssl.wrap_socket(sock)
else:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addrs[0][4])
sock.listen(100)
else:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(unix_socket)
return sock
@staticmethod
def daemonize(keepfd=None, chdir='/'):
os.umask(0)
if chdir:
os.chdir(chdir)
else:
os.chdir('/')
os.setgid(os.getgid()) # relinquish elevations
os.setuid(os.getuid()) # relinquish elevations
# Double fork to daemonize
if os.fork() > 0: os._exit(0) # Parent exits
os.setsid() # Obtain new process group
if os.fork() > 0: os._exit(0) # Parent exits
# Signal handling
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
# Close open files
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY: maxfd = 256
for fd in reversed(range(maxfd)):
try:
if fd != keepfd:
os.close(fd)
except OSError:
_, exc, _ = sys.exc_info()
if exc.errno != errno.EBADF: raise
# Redirect I/O to /dev/null
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
def do_handshake(self, sock, address):
"""
do_handshake does the following:
- Peek at the first few bytes from the socket.
- If the connection is Flash policy request then answer it,
close the socket and return.
- If the connection is an HTTPS/SSL/TLS connection then SSL
wrap the socket.
- Read from the (possibly wrapped) socket.
- If we have received a HTTP GET request and the webserver
functionality is enabled, answer it, close the socket and
return.
- Assume we have a WebSockets connection, parse the client
handshake data.
- Send a WebSockets handshake server response.
- Return the socket for this WebSocket client.
"""
ready = select.select([sock], [], [], 3)[0]
if not ready:
raise self.EClose("ignoring socket not ready")
# Peek, but do not read the data so that we have a opportunity
# to SSL wrap the socket first
handshake = sock.recv(1024, socket.MSG_PEEK)
#self.msg("Handshake [%s]" % handshake)
if handshake == "":
raise self.EClose("ignoring empty handshake")
elif handshake.startswith(s2b("<policy-file-request/>")):
# Answer Flash policy request
handshake = sock.recv(1024)
sock.send(s2b(self.policy_response))
raise self.EClose("Sending flash policy response")
elif handshake[0] in ("\x16", "\x80", 22, 128):
# SSL wrap the connection
if not ssl:
raise self.EClose("SSL connection but no 'ssl' module")
if not os.path.exists(self.cert):
raise self.EClose("SSL connection but '%s' not found"
% self.cert)
retsock = None
try:
retsock = ssl.wrap_socket(
sock,
server_side=True,
certfile=self.cert,
keyfile=self.key)
except ssl.SSLError:
_, x, _ = sys.exc_info()
if x.args[0] == ssl.SSL_ERROR_EOF:
if len(x.args) > 1:
raise self.EClose(x.args[1])
else:
raise self.EClose("Got SSL_ERROR_EOF")
else:
raise
elif self.ssl_only:
raise self.EClose("non-SSL connection received but disallowed")
else:
retsock = sock
# If the address is like (host, port), we are extending it
# with a flag indicating SSL. Not many other options
# available...
if len(address) == 2:
address = (address[0], address[1], (retsock != sock))
self.RequestHandlerClass(retsock, address, self)
# Return the WebSockets socket which may be SSL wrapped
return retsock
#
# WebSocketServer logging/output functions
#
def msg(self, *args, **kwargs):
""" Output message as info """
self.logger.log(logging.INFO, *args, **kwargs)
def vmsg(self, *args, **kwargs):
""" Same as msg() but as debug. """
self.logger.log(logging.DEBUG, *args, **kwargs)
def warn(self, *args, **kwargs):
""" Same as msg() but as warning. """
self.logger.log(logging.WARN, *args, **kwargs)
#
# Events that can/should be overridden in sub-classes
#
def started(self):
""" Called after WebSockets startup """
self.vmsg("WebSockets server started")
def poll(self):
""" Run periodically while waiting for connections. """
#self.vmsg("Running poll()")
pass
def terminate(self):
raise self.Terminate()
def multiprocessing_SIGCHLD(self, sig, stack):
self.vmsg('Reaing zombies, active child count is %s', len(multiprocessing.active_children()))
def fallback_SIGCHLD(self, sig, stack):
# Reap zombies when using os.fork() (python 2.4)
self.vmsg("Got SIGCHLD, reaping zombies")
try:
result = os.waitpid(-1, os.WNOHANG)
while result[0]:
self.vmsg("Reaped child process %s" % result[0])
result = os.waitpid(-1, os.WNOHANG)
except (OSError):
pass
def do_SIGINT(self, sig, stack):
self.msg("Got SIGINT, exiting")
self.terminate()
def do_SIGTERM(self, sig, stack):
self.msg("Got SIGTERM, exiting")
self.terminate()
def top_new_client(self, startsock, address):
""" Do something with a WebSockets client connection. """
# handler process
client = None
try:
try:
client = self.do_handshake(startsock, address)
except self.EClose:
_, exc, _ = sys.exc_info()
# Connection was not a WebSockets connection
if exc.args[0]:
self.msg("%s: %s" % (address[0], exc.args[0]))
except WebSocketServer.Terminate:
raise
except Exception:
_, exc, _ = sys.exc_info()
self.msg("handler exception: %s" % str(exc))
self.vmsg("exception", exc_info=True)
finally:
if client and client != startsock:
# Close the SSL wrapped socket
# Original socket closed by caller
client.close()
def start_server(self):
"""
Daemonize if requested. Listen for for connections. Run
do_handshake() method for each connection. If the connection
is a WebSockets client then call new_websocket_client() method (which must
be overridden) for each new client connection.
"""
lsock = self.socket(self.listen_host, self.listen_port, False,
self.prefer_ipv6,
tcp_keepalive=self.tcp_keepalive,
tcp_keepcnt=self.tcp_keepcnt,
tcp_keepidle=self.tcp_keepidle,
tcp_keepintvl=self.tcp_keepintvl)
if self.daemon:
self.daemonize(keepfd=lsock.fileno(), chdir=self.web)
self.started() # Some things need to happen after daemonizing
# Allow override of signals
original_signals = {
signal.SIGINT: signal.getsignal(signal.SIGINT),
signal.SIGTERM: signal.getsignal(signal.SIGTERM),
signal.SIGCHLD: signal.getsignal(signal.SIGCHLD),
}
signal.signal(signal.SIGINT, self.do_SIGINT)
signal.signal(signal.SIGTERM, self.do_SIGTERM)
if not multiprocessing:
# os.fork() (python 2.4) child reaper
signal.signal(signal.SIGCHLD, self.fallback_SIGCHLD)
else:
# make sure that _cleanup is called when children die
# by calling active_children on SIGCHLD
signal.signal(signal.SIGCHLD, self.multiprocessing_SIGCHLD)
last_active_time = self.launch_time
try:
while True:
try:
try:
startsock = None
pid = err = 0
child_count = 0
if multiprocessing:
# Collect zombie child processes
child_count = len(multiprocessing.active_children())
time_elapsed = time.time() - self.launch_time
if self.timeout and time_elapsed > self.timeout:
self.msg('listener exit due to --timeout %s'
% self.timeout)
break
if self.idle_timeout:
idle_time = 0
if child_count == 0:
idle_time = time.time() - last_active_time
else:
idle_time = 0
last_active_time = time.time()
if idle_time > self.idle_timeout and child_count == 0:
self.msg('listener exit due to --idle-timeout %s'
% self.idle_timeout)
break
try:
self.poll()
ready = select.select([lsock], [], [], 1)[0]
if lsock in ready:
startsock, address = lsock.accept()
else:
continue
except self.Terminate:
raise
except Exception:
_, exc, _ = sys.exc_info()
if hasattr(exc, 'errno'):
err = exc.errno
elif hasattr(exc, 'args'):
err = exc.args[0]
else:
err = exc[0]
if err == errno.EINTR:
self.vmsg("Ignoring interrupted syscall")
continue
else:
raise
if self.run_once:
# Run in same process if run_once
self.top_new_client(startsock, address)
if self.ws_connection :
self.msg('%s: exiting due to --run-once'
% address[0])
break
elif multiprocessing:
self.vmsg('%s: new handler Process' % address[0])
p = multiprocessing.Process(
target=self.top_new_client,
args=(startsock, address))
p.start()
# child will not return
else:
# python 2.4
self.vmsg('%s: forking handler' % address[0])
pid = os.fork()
if pid == 0:
# child handler process
self.top_new_client(startsock, address)
break # child process exits
# parent process
self.handler_id += 1
except (self.Terminate, SystemExit, KeyboardInterrupt):
self.msg("In exit")
break
except Exception:
self.msg("handler exception: %s", str(exc))
self.vmsg("exception", exc_info=True)
finally:
if startsock:
startsock.close()
finally:
# Close listen port
self.vmsg("Closing socket listening at %s:%s",
self.listen_host, self.listen_port)
lsock.close()
# Restore signals
for sig, func in original_signals.items():
signal.signal(sig, func)
| apache-2.0 |
demisjohn/EMpy | EMpy/modesolvers/FD.py | 1 | 62139 | # pylint: disable=line-too-long,too-many-locals,too-many-statements,too-many-branches
# pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import
# pylint: disable=attribute-defined-outside-init,too-many-instance-attributes
# pylint: disable=arguments-differ,too-many-arguments
"""Finite Difference Modesolver.
@see: Fallahkhair, "Vector Finite Difference Modesolver for Anisotropic Dielectric Waveguides",
@see: JLT 2007 <http://www.photonics.umd.edu/wp-content/uploads/pubs/ja-20/Fallahkhair_JLT_26_1423_2008.pdf>}
@see: DOI of above reference <http://doi.org/10.1109/JLT.2008.923643>
@see: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=12734&objectType=FILE
"""
from __future__ import print_function
from builtins import zip
from builtins import str
from builtins import range
import numpy
import scipy
import scipy.optimize
import EMpy.utils
from EMpy.modesolvers.interface import *
class SVFDModeSolver(ModeSolver):
"""
This function calculates the modes of a dielectric waveguide
using the semivectorial finite difference method.
It is slightly faster than the full-vectorial VFDModeSolver,
but it does not accept non-isotropic permittivity. For example,
birefringent materials, which have
different refractive indices along different dimensions cannot be used.
It is adapted from the "svmodes.m" matlab code of Thomas Murphy and co-workers.
https://www.mathworks.com/matlabcentral/fileexchange/12734-waveguide-mode-solver/content/svmodes.m
Parameters
----------
wl : float
optical wavelength
units are arbitrary, but must be self-consistent.
I.e., just use micron for everything.
x : 1D array of floats
Array of x-values
y : 1D array of floats
Array of y-values
epsfunc : function
This is a function that provides the relative permittivity matrix
(square of the refractive index) as a function of its x and y
numpy.arrays (the function's input parameters). The function must be
of the form: ``myRelativePermittivity(x,y)``, where x and y are 2D
numpy "meshgrid" arrays that will be passed by this function.
The function returns a relative permittivity numpy.array of
shape( x.shape[0], y.shape[0] ) where each element of the array
is a single float, corresponding the an isotropic refractive index.
If an anisotropic refractive index is desired, the full-vectorial
VFDModeSolver function should be used.
boundary : str
This is a string that identifies the type of boundary conditions applied.
The following options are available:
'A' - Hx is antisymmetric, Hy is symmetric.
'S' - Hx is symmetric and, Hy is antisymmetric.
'0' - Hx and Hy are zero immediately outside of the boundary.
The string identifies all four boundary conditions, in the order:
North, south, east, west.
For example, boundary='000A'
method : str
must be 'Ex', 'Ey', or 'scalar'
this identifies the field that will be calculated.
Returns
-------
self : an instance of the SVFDModeSolver class
Typically self.solve() will be called in order to actually find the modes.
"""
def __init__(self, wl, x, y, epsfunc, boundary, method='Ex'):
self.wl = wl
self.x = x
self.y = y
self.epsfunc = epsfunc
self.boundary = boundary
self.method = method
def _get_eps(self, xc, yc):
eps = self.epsfunc(xc, yc)
eps = numpy.c_[eps[:, 0:1], eps, eps[:, -1:]]
eps = numpy.r_[eps[0:1, :], eps, eps[-1:, :]]
return eps
def build_matrix(self):
from scipy.sparse import coo_matrix
wl = self.wl
x = self.x
y = self.y
boundary = self.boundary
method = self.method
dx = numpy.diff(x)
dy = numpy.diff(y)
dx = numpy.r_[dx[0], dx, dx[-1]].reshape(-1, 1)
dy = numpy.r_[dy[0], dy, dy[-1]].reshape(1, -1)
xc = (x[:-1] + x[1:]) / 2
yc = (y[:-1] + y[1:]) / 2
eps = self._get_eps(xc, yc)
nx = len(xc)
ny = len(yc)
self.nx = nx
self.ny = ny
k = 2 * numpy.pi / wl
ones_nx = numpy.ones((nx, 1))
ones_ny = numpy.ones((1, ny))
n = numpy.dot(ones_nx, 0.5 * (dy[:, 2:] + dy[:, 1:-1])).flatten()
s = numpy.dot(ones_nx, 0.5 * (dy[:, 0:-2] + dy[:, 1:-1])).flatten()
e = numpy.dot(0.5 * (dx[2:, :] + dx[1:-1, :]), ones_ny).flatten()
w = numpy.dot(0.5 * (dx[0:-2, :] + dx[1:-1, :]), ones_ny).flatten()
p = numpy.dot(dx[1:-1, :], ones_ny).flatten()
q = numpy.dot(ones_nx, dy[:, 1:-1]).flatten()
en = eps[1:-1, 2:].flatten()
es = eps[1:-1, 0:-2].flatten()
ee = eps[2:, 1:-1].flatten()
ew = eps[0:-2, 1:-1].flatten()
ep = eps[1:-1, 1:-1].flatten()
# three methods: Ex, Ey and scalar
if method == 'Ex':
# Ex
An = 2 / n / (n + s)
As = 2 / s / (n + s)
Ae = 8 * (p * (ep - ew) + 2 * w * ew) * ee / \
((p * (ep - ee) + 2 * e * ee) * (p ** 2 * (ep - ew) + 4 * w ** 2 * ew) +
(p * (ep - ew) + 2 * w * ew) * (p ** 2 * (ep - ee) + 4 * e ** 2 * ee))
Aw = 8 * (p * (ep - ee) + 2 * e * ee) * ew / \
((p * (ep - ee) + 2 * e * ee) * (p ** 2 * (ep - ew) + 4 * w ** 2 * ew) +
(p * (ep - ew) + 2 * w * ew) * (p ** 2 * (ep - ee) + 4 * e ** 2 * ee))
Ap = ep * k ** 2 - An - As - Ae * ep / ee - Aw * ep / ew
elif method == 'Ey':
# Ey
An = 8 * (q * (ep - es) + 2 * s * es) * en / \
((q * (ep - en) + 2 * n * en) * (q ** 2 * (ep - es) + 4 * s ** 2 * es) +
(q * (ep - es) + 2 * s * es) * (q ** 2 * (ep - en) + 4 * n ** 2 * en))
As = 8 * (q * (ep - en) + 2 * n * en) * es / \
((q * (ep - en) + 2 * n * en) * (q ** 2 * (ep - es) + 4 * s ** 2 * es) +
(q * (ep - es) + 2 * s * es) * (q ** 2 * (ep - en) + 4 * n ** 2 * en))
Ae = 2 / e / (e + w)
Aw = 2 / w / (e + w)
Ap = ep * k ** 2 - An * ep / en - As * ep / es - Ae - Aw
elif method == 'scalar':
# scalar
An = 2 / n / (n + s)
As = 2 / s / (n + s)
Ae = 2 / e / (e + w)
Aw = 2 / w / (e + w)
Ap = ep * k ** 2 - An - As - Ae - Aw
else:
raise ValueError('unknown method')
ii = numpy.arange(nx * ny).reshape(nx, ny)
# north boundary
ib = ii[:, -1]
if boundary[0] == 'S':
Ap[ib] += An[ib]
elif boundary[0] == 'A':
Ap[ib] -= An[ib]
# else:
# raise ValueError('unknown boundary')
# south
ib = ii[:, 0]
if boundary[1] == 'S':
Ap[ib] += As[ib]
elif boundary[1] == 'A':
Ap[ib] -= As[ib]
# else:
# raise ValueError('unknown boundary')
# east
ib = ii[-1, :]
if boundary[2] == 'S':
Ap[ib] += Ae[ib]
elif boundary[2] == 'A':
Ap[ib] -= Ae[ib]
# else:
# raise ValueError('unknown boundary')
# west
ib = ii[0, :]
if boundary[3] == 'S':
Ap[ib] += Aw[ib]
elif boundary[3] == 'A':
Ap[ib] -= Aw[ib]
# else:
# raise ValueError('unknown boundary')
iall = ii.flatten()
i_n = ii[:, 1:].flatten()
i_s = ii[:, :-1].flatten()
i_e = ii[1:, :].flatten()
i_w = ii[:-1, :].flatten()
I = numpy.r_[iall, i_w, i_e, i_s, i_n]
J = numpy.r_[iall, i_e, i_w, i_n, i_s]
V = numpy.r_[Ap[iall], Ae[i_w], Aw[i_e], An[i_s], As[i_n]]
A = coo_matrix((V, (I, J))).tocsr()
return A
def solve(self, neigs, tol):
from scipy.sparse.linalg import eigen
self.nmodes = neigs
self.tol = tol
A = self.build_matrix()
[eigvals, eigvecs] = eigen.eigs(A,
k=neigs,
which='LR',
tol=tol,
ncv=10 * neigs,
return_eigenvectors=True)
neff = self.wl * scipy.sqrt(eigvals) / (2 * numpy.pi)
phi = []
for ieig in range(neigs):
tmp = eigvecs[:, ieig].reshape(self.nx, self.ny)
phi.append(tmp)
# sort and save the modes
idx = numpy.flipud(numpy.argsort(neff))
self.neff = neff[idx]
tmp = []
for i in idx:
tmp.append(phi[i])
if self.method == 'scalar':
self.phi = tmp
elif self.method == 'Ex':
self.Ex = tmp
if self.method == 'Ey':
self.Ey = tmp
return self
def __str__(self):
descr = (
'Semi-Vectorial Finite Difference Modesolver\n\tmethod: %s\n' %
self.method)
return descr
class VFDModeSolver(ModeSolver):
"""
The VFDModeSolver class computes the electric and magnetic fields
for modes of a dielectric waveguide using the "Vector Finite
Difference (VFD)" method, as described in A. B. Fallahkhair,
K. S. Li and T. E. Murphy, "Vector Finite Difference Modesolver
for Anisotropic Dielectric Waveguides", J. Lightwave
Technol. 26(11), 1423-1431, (2008).
Parameters
----------
wl : float
The wavelength of the optical radiation (units are arbitrary,
but must be self-consistent between all inputs. It is recommended to
just use microns for everthing)
x : 1D array of floats
Array of x-values
y : 1D array of floats
Array of y-values
epsfunc : function
This is a function that provides the relative permittivity
matrix (square of the refractive index) as a function of its x
and y numpy.arrays (the function's input parameters). The
function must be of the form: ``myRelativePermittivity(x,y)``
The function returns a relative permittivity numpy.array of either
shape( x.shape[0], y.shape[0] ) where each element of the
array can either be a single float, corresponding the an
isotropic refractive index, or (x.shape[0], y.shape[0], 5),
where the last dimension describes the relative permittivity in
the form (epsxx, epsxy, epsyx, epsyy, epszz).
boundary : str
This is a string that identifies the type of boundary
conditions applied.
The following options are available:
'A' - Hx is antisymmetric, Hy is symmetric.
'S' - Hx is symmetric and, Hy is antisymmetric.
'0' - Hx and Hy are zero immediately outside of the boundary.
The string identifies all four boundary conditions, in the
order: North, south, east, west. For example, boundary='000A'
Returns
-------
self : an instance of the VFDModeSolver class
Typically self.solve() will be called in order to actually
find the modes.
"""
def __init__(self, wl, x, y, epsfunc, boundary):
self.wl = wl
self.x = x
self.y = y
self.epsfunc = epsfunc
self.boundary = boundary
def _get_eps(self, xc, yc):
tmp = self.epsfunc(xc, yc)
def _reshape(tmp):
"""
pads the array by duplicating edge values
"""
tmp = numpy.c_[tmp[:, 0:1], tmp, tmp[:, -1:]]
tmp = numpy.r_[tmp[0:1, :], tmp, tmp[-1:, :]]
return tmp
if tmp.ndim == 2: # isotropic refractive index
tmp = _reshape(tmp)
epsxx = epsyy = epszz = tmp
epsxy = epsyx = numpy.zeros_like(epsxx)
elif tmp.ndim == 3: # anisotropic refractive index
assert tmp.shape[2] == 5, 'eps must be NxMx5'
epsxx = _reshape(tmp[:, :, 0])
epsxy = _reshape(tmp[:, :, 1])
epsyx = _reshape(tmp[:, :, 2])
epsyy = _reshape(tmp[:, :, 3])
epszz = _reshape(tmp[:, :, 4])
else:
raise ValueError('Invalid eps')
return epsxx, epsxy, epsyx, epsyy, epszz
def build_matrix(self):
from scipy.sparse import coo_matrix
wl = self.wl
x = self.x
y = self.y
boundary = self.boundary
dx = numpy.diff(x)
dy = numpy.diff(y)
dx = numpy.r_[dx[0], dx, dx[-1]].reshape(-1, 1)
dy = numpy.r_[dy[0], dy, dy[-1]].reshape(1, -1)
# Note: the permittivity is actually defined at the center of each
# region *between* the mesh points used for the H-field calculation.
# (See Fig. 1 of Fallahkhair and Murphy)
# In other words, eps is defined on (xc,yc) which is offset from
# (x,y), the grid where H is calculated, by
# "half a pixel" in the positive-x and positive-y directions.
xc = (x[:-1] + x[1:]) / 2
yc = (y[:-1] + y[1:]) / 2
epsxx, epsxy, epsyx, epsyy, epszz = self._get_eps(xc, yc)
nx = len(x)
ny = len(y)
self.nx = nx
self.ny = ny
k = 2 * numpy.pi / wl
ones_nx = numpy.ones((nx, 1))
ones_ny = numpy.ones((1, ny))
# distance of mesh points to nearest neighbor mesh point:
n = numpy.dot(ones_nx, dy[:, 1:]).flatten()
s = numpy.dot(ones_nx, dy[:, :-1]).flatten()
e = numpy.dot(dx[1:, :], ones_ny).flatten()
w = numpy.dot(dx[:-1, :], ones_ny).flatten()
# These define the permittivity (eps) tensor relative to each mesh point
# using the following geometry:
#
# NW------N------NE
# | | |
# | 1 n 4 |
# | | |
# W---w---P---e---E
# | | |
# | 2 s 3 |
# | | |
# SW------S------SE
exx1 = epsxx[:-1, 1:].flatten()
exx2 = epsxx[:-1, :-1].flatten()
exx3 = epsxx[1:, :-1].flatten()
exx4 = epsxx[1:, 1:].flatten()
eyy1 = epsyy[:-1, 1:].flatten()
eyy2 = epsyy[:-1, :-1].flatten()
eyy3 = epsyy[1:, :-1].flatten()
eyy4 = epsyy[1:, 1:].flatten()
exy1 = epsxy[:-1, 1:].flatten()
exy2 = epsxy[:-1, :-1].flatten()
exy3 = epsxy[1:, :-1].flatten()
exy4 = epsxy[1:, 1:].flatten()
eyx1 = epsyx[:-1, 1:].flatten()
eyx2 = epsyx[:-1, :-1].flatten()
eyx3 = epsyx[1:, :-1].flatten()
eyx4 = epsyx[1:, 1:].flatten()
ezz1 = epszz[:-1, 1:].flatten()
ezz2 = epszz[:-1, :-1].flatten()
ezz3 = epszz[1:, :-1].flatten()
ezz4 = epszz[1:, 1:].flatten()
ns21 = n * eyy2 + s * eyy1
ns34 = n * eyy3 + s * eyy4
ew14 = e * exx1 + w * exx4
ew23 = e * exx2 + w * exx3
# calculate the finite difference coefficients following
# Fallahkhair and Murphy, Appendix Eqs 21 though 37
axxn = ((2 * eyy4 * e - eyx4 * n) * (eyy3 / ezz4) / ns34 +
(2 * eyy1 * w + eyx1 * n) * (eyy2 / ezz1) / ns21) / (n * (e + w))
axxs = ((2 * eyy3 * e + eyx3 * s) * (eyy4 / ezz3) / ns34 +
(2 * eyy2 * w - eyx2 * s) * (eyy1 / ezz2) / ns21) / (s * (e + w))
ayye = (2 * n * exx4 - e * exy4) * exx1 / ezz4 / e / ew14 / \
(n + s) + (2 * s * exx3 + e * exy3) * \
exx2 / ezz3 / e / ew23 / (n + s)
ayyw = (2 * exx1 * n + exy1 * w) * exx4 / ezz1 / w / ew14 / \
(n + s) + (2 * exx2 * s - exy2 * w) * \
exx3 / ezz2 / w / ew23 / (n + s)
axxe = 2 / (e * (e + w)) + \
(eyy4 * eyx3 / ezz3 - eyy3 * eyx4 / ezz4) / (e + w) / ns34
axxw = 2 / (w * (e + w)) + \
(eyy2 * eyx1 / ezz1 - eyy1 * eyx2 / ezz2) / (e + w) / ns21
ayyn = 2 / (n * (n + s)) + \
(exx4 * exy1 / ezz1 - exx1 * exy4 / ezz4) / (n + s) / ew14
ayys = 2 / (s * (n + s)) + \
(exx2 * exy3 / ezz3 - exx3 * exy2 / ezz2) / (n + s) / ew23
axxne = +eyx4 * eyy3 / ezz4 / (e + w) / ns34
axxse = -eyx3 * eyy4 / ezz3 / (e + w) / ns34
axxnw = -eyx1 * eyy2 / ezz1 / (e + w) / ns21
axxsw = +eyx2 * eyy1 / ezz2 / (e + w) / ns21
ayyne = +exy4 * exx1 / ezz4 / (n + s) / ew14
ayyse = -exy3 * exx2 / ezz3 / (n + s) / ew23
ayynw = -exy1 * exx4 / ezz1 / (n + s) / ew14
ayysw = +exy2 * exx3 / ezz2 / (n + s) / ew23
axxp = -axxn - axxs - axxe - axxw - axxne - axxse - axxnw - axxsw + k ** 2 * \
(n + s) * \
(eyy4 * eyy3 * e / ns34 + eyy1 * eyy2 * w / ns21) / (e + w)
ayyp = -ayyn - ayys - ayye - ayyw - ayyne - ayyse - ayynw - ayysw + k ** 2 * \
(e + w) * \
(exx1 * exx4 * n / ew14 + exx2 * exx3 * s / ew23) / (n + s)
axyn = (eyy3 * eyy4 / ezz4 / ns34 - eyy2 * eyy1 / ezz1 /
ns21 + s * (eyy2 * eyy4 - eyy1 * eyy3) / ns21 / ns34) / (e + w)
axys = (eyy1 * eyy2 / ezz2 / ns21 - eyy4 * eyy3 / ezz3 /
ns34 + n * (eyy2 * eyy4 - eyy1 * eyy3) / ns21 / ns34) / (e + w)
ayxe = (exx1 * exx4 / ezz4 / ew14 - exx2 * exx3 / ezz3 /
ew23 + w * (exx2 * exx4 - exx1 * exx3) / ew23 / ew14) / (n + s)
ayxw = (exx3 * exx2 / ezz2 / ew23 - exx4 * exx1 / ezz1 /
ew14 + e * (exx4 * exx2 - exx1 * exx3) / ew23 / ew14) / (n + s)
axye = (eyy4 * (1 + eyy3 / ezz4) - eyy3 * (1 + eyy4 / ezz4)) / ns34 / (e + w) - \
(2 * eyx1 * eyy2 / ezz1 * n * w / ns21 +
2 * eyx2 * eyy1 / ezz2 * s * w / ns21 +
2 * eyx4 * eyy3 / ezz4 * n * e / ns34 +
2 * eyx3 * eyy4 / ezz3 * s * e / ns34 +
2 * eyy1 * eyy2 * (1. / ezz1 - 1. / ezz2) * w ** 2 / ns21) / e / (e + w) ** 2
axyw = (eyy2 * (1 + eyy1 / ezz2) - eyy1 * (1 + eyy2 / ezz2)) / ns21 / (e + w) - \
(2 * eyx1 * eyy2 / ezz1 * n * e / ns21 +
2 * eyx2 * eyy1 / ezz2 * s * e / ns21 +
2 * eyx4 * eyy3 / ezz4 * n * w / ns34 +
2 * eyx3 * eyy4 / ezz3 * s * w / ns34 +
2 * eyy3 * eyy4 * (1. / ezz3 - 1. / ezz4) * e ** 2 / ns34) / w / (e + w) ** 2
ayxn = (exx4 * (1 + exx1 / ezz4) - exx1 * (1 + exx4 / ezz4)) / ew14 / (n + s) - \
(2 * exy3 * exx2 / ezz3 * e * s / ew23 +
2 * exy2 * exx3 / ezz2 * w * n / ew23 +
2 * exy4 * exx1 / ezz4 * e * s / ew14 +
2 * exy1 * exx4 / ezz1 * w * n / ew14 +
2 * exx3 * exx2 * (1. / ezz3 - 1. / ezz2) * s ** 2 / ew23) / n / (n + s) ** 2
ayxs = (exx2 * (1 + exx3 / ezz2) - exx3 * (1 + exx2 / ezz2)) / ew23 / (n + s) - \
(2 * exy3 * exx2 / ezz3 * e * n / ew23 +
2 * exy2 * exx3 / ezz2 * w * n / ew23 +
2 * exy4 * exx1 / ezz4 * e * s / ew14 +
2 * exy1 * exx4 / ezz1 * w * s / ew14 +
2 * exx1 * exx4 * (1. / ezz1 - 1. / ezz4) * n ** 2 / ew14) / s / (n + s) ** 2
axyne = +eyy3 * (1 - eyy4 / ezz4) / (e + w) / ns34
axyse = -eyy4 * (1 - eyy3 / ezz3) / (e + w) / ns34
axynw = -eyy2 * (1 - eyy1 / ezz1) / (e + w) / ns21
axysw = +eyy1 * (1 - eyy2 / ezz2) / (e + w) / ns21
ayxne = +exx1 * (1 - exx4 / ezz4) / (n + s) / ew14
ayxse = -exx2 * (1 - exx3 / ezz3) / (n + s) / ew23
ayxnw = -exx4 * (1 - exx1 / ezz1) / (n + s) / ew14
ayxsw = +exx3 * (1 - exx2 / ezz2) / (n + s) / ew23
axyp = -(axyn + axys + axye + axyw + axyne + axyse + axynw + axysw) - k ** 2 * (w * (n * eyx1 *
eyy2 + s * eyx2 * eyy1) / ns21 + e * (s * eyx3 * eyy4 + n * eyx4 * eyy3) / ns34) / (e + w)
ayxp = -(ayxn + ayxs + ayxe + ayxw + ayxne + ayxse + ayxnw + ayxsw) - k ** 2 * (n * (w * exy1 *
exx4 + e * exy4 * exx1) / ew14 + s * (w * exy2 * exx3 + e * exy3 * exx2) / ew23) / (n + s)
ii = numpy.arange(nx * ny).reshape(nx, ny)
# NORTH boundary
ib = ii[:, -1]
if boundary[0] == 'S':
sign = 1
elif boundary[0] == 'A':
sign = -1
elif boundary[0] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
axxs[ib] += sign * axxn[ib]
axxse[ib] += sign * axxne[ib]
axxsw[ib] += sign * axxnw[ib]
ayxs[ib] += sign * ayxn[ib]
ayxse[ib] += sign * ayxne[ib]
ayxsw[ib] += sign * ayxnw[ib]
ayys[ib] -= sign * ayyn[ib]
ayyse[ib] -= sign * ayyne[ib]
ayysw[ib] -= sign * ayynw[ib]
axys[ib] -= sign * axyn[ib]
axyse[ib] -= sign * axyne[ib]
axysw[ib] -= sign * axynw[ib]
# SOUTH boundary
ib = ii[:, 0]
if boundary[1] == 'S':
sign = 1
elif boundary[1] == 'A':
sign = -1
elif boundary[1] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
axxn[ib] += sign * axxs[ib]
axxne[ib] += sign * axxse[ib]
axxnw[ib] += sign * axxsw[ib]
ayxn[ib] += sign * ayxs[ib]
ayxne[ib] += sign * ayxse[ib]
ayxnw[ib] += sign * ayxsw[ib]
ayyn[ib] -= sign * ayys[ib]
ayyne[ib] -= sign * ayyse[ib]
ayynw[ib] -= sign * ayysw[ib]
axyn[ib] -= sign * axys[ib]
axyne[ib] -= sign * axyse[ib]
axynw[ib] -= sign * axysw[ib]
# EAST boundary
ib = ii[-1, :]
if boundary[2] == 'S':
sign = 1
elif boundary[2] == 'A':
sign = -1
elif boundary[2] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
axxw[ib] += sign * axxe[ib]
axxnw[ib] += sign * axxne[ib]
axxsw[ib] += sign * axxse[ib]
ayxw[ib] += sign * ayxe[ib]
ayxnw[ib] += sign * ayxne[ib]
ayxsw[ib] += sign * ayxse[ib]
ayyw[ib] -= sign * ayye[ib]
ayynw[ib] -= sign * ayyne[ib]
ayysw[ib] -= sign * ayyse[ib]
axyw[ib] -= sign * axye[ib]
axynw[ib] -= sign * axyne[ib]
axysw[ib] -= sign * axyse[ib]
# WEST boundary
ib = ii[0, :]
if boundary[3] == 'S':
sign = 1
elif boundary[3] == 'A':
sign = -1
elif boundary[3] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
axxe[ib] += sign * axxw[ib]
axxne[ib] += sign * axxnw[ib]
axxse[ib] += sign * axxsw[ib]
ayxe[ib] += sign * ayxw[ib]
ayxne[ib] += sign * ayxnw[ib]
ayxse[ib] += sign * ayxsw[ib]
ayye[ib] -= sign * ayyw[ib]
ayyne[ib] -= sign * ayynw[ib]
ayyse[ib] -= sign * ayysw[ib]
axye[ib] -= sign * axyw[ib]
axyne[ib] -= sign * axynw[ib]
axyse[ib] -= sign * axysw[ib]
# Assemble sparse matrix
iall = ii.flatten()
i_s = ii[:, :-1].flatten()
i_n = ii[:, 1:].flatten()
i_e = ii[1:, :].flatten()
i_w = ii[:-1, :].flatten()
i_ne = ii[1:, 1:].flatten()
i_se = ii[1:, :-1].flatten()
i_sw = ii[:-1, :-1].flatten()
i_nw = ii[:-1, 1:].flatten()
Ixx = numpy.r_[iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw]
Jxx = numpy.r_[iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se]
Vxx = numpy.r_[axxp[iall], axxe[i_w], axxw[i_e], axxn[i_s], axxs[
i_n], axxsw[i_ne], axxnw[i_se], axxne[i_sw], axxse[i_nw]]
Ixy = numpy.r_[iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw]
Jxy = numpy.r_[
iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se] + nx * ny
Vxy = numpy.r_[axyp[iall], axye[i_w], axyw[i_e], axyn[i_s], axys[
i_n], axysw[i_ne], axynw[i_se], axyne[i_sw], axyse[i_nw]]
Iyx = numpy.r_[
iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw] + nx * ny
Jyx = numpy.r_[iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se]
Vyx = numpy.r_[ayxp[iall], ayxe[i_w], ayxw[i_e], ayxn[i_s], ayxs[
i_n], ayxsw[i_ne], ayxnw[i_se], ayxne[i_sw], ayxse[i_nw]]
Iyy = numpy.r_[
iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw] + nx * ny
Jyy = numpy.r_[
iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se] + nx * ny
Vyy = numpy.r_[ayyp[iall], ayye[i_w], ayyw[i_e], ayyn[i_s], ayys[
i_n], ayysw[i_ne], ayynw[i_se], ayyne[i_sw], ayyse[i_nw]]
I = numpy.r_[Ixx, Ixy, Iyx, Iyy]
J = numpy.r_[Jxx, Jxy, Jyx, Jyy]
V = numpy.r_[Vxx, Vxy, Vyx, Vyy]
A = coo_matrix((V, (I, J))).tocsr()
return A
def compute_other_fields(self, neffs, Hxs, Hys):
from scipy.sparse import coo_matrix
wl = self.wl
x = self.x
y = self.y
boundary = self.boundary
Hzs = []
Exs = []
Eys = []
Ezs = []
for neff, Hx, Hy in zip(neffs, Hxs, Hys):
dx = numpy.diff(x)
dy = numpy.diff(y)
dx = numpy.r_[dx[0], dx, dx[-1]].reshape(-1, 1)
dy = numpy.r_[dy[0], dy, dy[-1]].reshape(1, -1)
xc = (x[:-1] + x[1:]) / 2
yc = (y[:-1] + y[1:]) / 2
epsxx, epsxy, epsyx, epsyy, epszz = self._get_eps(xc, yc)
nx = len(x)
ny = len(y)
k = 2 * numpy.pi / wl
ones_nx = numpy.ones((nx, 1))
ones_ny = numpy.ones((1, ny))
n = numpy.dot(ones_nx, dy[:, 1:]).flatten()
s = numpy.dot(ones_nx, dy[:, :-1]).flatten()
e = numpy.dot(dx[1:, :], ones_ny).flatten()
w = numpy.dot(dx[:-1, :], ones_ny).flatten()
exx1 = epsxx[:-1, 1:].flatten()
exx2 = epsxx[:-1, :-1].flatten()
exx3 = epsxx[1:, :-1].flatten()
exx4 = epsxx[1:, 1:].flatten()
eyy1 = epsyy[:-1, 1:].flatten()
eyy2 = epsyy[:-1, :-1].flatten()
eyy3 = epsyy[1:, :-1].flatten()
eyy4 = epsyy[1:, 1:].flatten()
exy1 = epsxy[:-1, 1:].flatten()
exy2 = epsxy[:-1, :-1].flatten()
exy3 = epsxy[1:, :-1].flatten()
exy4 = epsxy[1:, 1:].flatten()
eyx1 = epsyx[:-1, 1:].flatten()
eyx2 = epsyx[:-1, :-1].flatten()
eyx3 = epsyx[1:, :-1].flatten()
eyx4 = epsyx[1:, 1:].flatten()
ezz1 = epszz[:-1, 1:].flatten()
ezz2 = epszz[:-1, :-1].flatten()
ezz3 = epszz[1:, :-1].flatten()
ezz4 = epszz[1:, 1:].flatten()
b = neff * k
bzxne = (0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * eyx4 / ezz4 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy3 * eyy1 * w * eyy2 +
0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (1 - exx4 / ezz4) / ezz3 / ezz2 / (w * exx3 + e * exx2) / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * exx1 * s) / b
bzxse = (-0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * eyx3 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy1 * w * eyy2 +
0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (1 - exx3 / ezz3) / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * n * exx1 * exx4) / b
bzxnw = (-0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * eyx1 / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy2 * e -
0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (1 - exx1 / ezz1) / ezz3 / ezz2 / (w * exx3 + e * exx2) / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * exx4 * s) / b
bzxsw = (0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * eyx2 / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * e -
0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (1 - exx2 / ezz2) / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx3 * n * exx1 * exx4) / b
bzxn = ((0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * n * ezz1 * ezz2 / eyy1 * (2 * eyy1 / ezz1 / n ** 2 + eyx1 / ezz1 / n / w) + 0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * n * ezz4 * ezz3 / eyy4 * (2 * eyy4 / ezz4 / n ** 2 - eyx4 / ezz4 / n / e)) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + ((ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (0.5 * ezz4 * ((1 - exx1 / ezz1) / n / w - exy1 / ezz1 *
(2. / n ** 2 - 2 / n ** 2 * s / (n + s))) / exx1 * ezz1 * w + (ezz4 - ezz1) * s / n / (n + s) + 0.5 * ezz1 * (-(1 - exx4 / ezz4) / n / e - exy4 / ezz4 * (2. / n ** 2 - 2 / n ** 2 * s / (n + s))) / exx4 * ezz4 * e) - (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (-ezz3 * exy2 / n / (n + s) / exx2 * w + (ezz3 - ezz2) * s / n / (n + s) - ezz2 * exy3 / n / (n + s) / exx3 * e)) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzxs = ((0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * s * ezz2 * ezz1 / eyy2 * (2 * eyy2 / ezz2 / s ** 2 - eyx2 / ezz2 / s / w) + 0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * s * ezz3 * ezz4 / eyy3 * (2 * eyy3 / ezz3 / s ** 2 + eyx3 / ezz3 / s / e)) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + ((ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (-ezz4 * exy1 / s / (n + s) / exx1 * w - (ezz4 - ezz1)
* n / s / (n + s) - ezz1 * exy4 / s / (n + s) / exx4 * e) - (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (0.5 * ezz3 * (-(1 - exx2 / ezz2) / s / w - exy2 / ezz2 * (2. / s ** 2 - 2 / s ** 2 * n / (n + s))) / exx2 * ezz2 * w - (ezz3 - ezz2) * n / s / (n + s) + 0.5 * ezz2 * ((1 - exx3 / ezz3) / s / e - exy3 / ezz3 * (2. / s ** 2 - 2 / s ** 2 * n / (n + s))) / exx3 * ezz3 * e)) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzxe = ((n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (0.5 * n * ezz4 * ezz3 / eyy4 * (2. / e ** 2 - eyx4 / ezz4 / n / e) + 0.5 * s * ezz3 * ezz4 / eyy3 * (2. / e ** 2 + eyx3 / ezz3 / s / e)) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e +
(-0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * ezz1 * (1 - exx4 / ezz4) / n / exx4 * ezz4 - 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * ezz2 * (1 - exx3 / ezz3) / s / exx3 * ezz3) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzxw = ((-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (0.5 * n * ezz1 * ezz2 / eyy1 * (2. / w ** 2 + eyx1 / ezz1 / n / w) + 0.5 * s * ezz2 * ezz1 / eyy2 * (2. / w ** 2 - eyx2 / ezz2 / s / w)) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e +
(0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * ezz4 * (1 - exx1 / ezz1) / n / exx1 * ezz1 + 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * ezz3 * (1 - exx2 / ezz2) / s / exx2 * ezz2) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzxp = (((-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (0.5 * n * ezz1 * ezz2 / eyy1 * (-2. / w ** 2 - 2 * eyy1 / ezz1 / n ** 2 + k ** 2 * eyy1 - eyx1 / ezz1 / n / w) + 0.5 * s * ezz2 * ezz1 / eyy2 * (-2. / w ** 2 - 2 * eyy2 / ezz2 / s ** 2 + k ** 2 * eyy2 + eyx2 / ezz2 / s / w)) + (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (0.5 * n * ezz4 * ezz3 / eyy4 * (-2. / e ** 2 - 2 * eyy4 / ezz4 / n ** 2 + k ** 2 * eyy4 + eyx4 / ezz4 / n / e) + 0.5 * s * ezz3 * ezz4 / eyy3 * (-2. / e ** 2 - 2 * eyy3 / ezz3 / s ** 2 + k ** 2 * eyy3 - eyx3 / ezz3 / s / e))) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + ((ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (0.5 * ezz4 * (-k **
2 * exy1 - (1 - exx1 / ezz1) / n / w - exy1 / ezz1 * (-2. / n ** 2 - 2 / n ** 2 * (n - s) / s)) / exx1 * ezz1 * w + (ezz4 - ezz1) * (n - s) / n / s + 0.5 * ezz1 * (-k ** 2 * exy4 + (1 - exx4 / ezz4) / n / e - exy4 / ezz4 * (-2. / n ** 2 - 2 / n ** 2 * (n - s) / s)) / exx4 * ezz4 * e) - (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (0.5 * ezz3 * (-k ** 2 * exy2 + (1 - exx2 / ezz2) / s / w - exy2 / ezz2 * (-2. / s ** 2 + 2 / s ** 2 * (n - s) / n)) / exx2 * ezz2 * w + (ezz3 - ezz2) * (n - s) / n / s + 0.5 * ezz2 * (-k ** 2 * exy3 - (1 - exx3 / ezz3) / s / e - exy3 / ezz3 * (-2. / s ** 2 + 2 / s ** 2 * (n - s) / n)) / exx3 * ezz3 * e)) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzyne = (0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (1 - eyy4 / ezz4) / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy3 * eyy1 * w *
eyy2 + 0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * exy4 / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * exx1 * s) / b
bzyse = (-0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (1 - eyy3 / ezz3) / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy1 * w *
eyy2 + 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * exy3 / ezz3 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * n * exx1 * exx4) / b
bzynw = (-0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (1 - eyy1 / ezz1) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 *
eyy2 * e - 0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * exy1 / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * exx4 * s) / b
bzysw = (0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (1 - eyy2 / ezz2) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 *
e - 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * exy2 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx3 * n * exx1 * exx4) / b
bzyn = ((0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * ezz1 * ezz2 / eyy1 * (1 - eyy1 / ezz1) / w - 0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * ezz4 * ezz3 / eyy4 * (1 - eyy4 / ezz4) / e) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w *
eyy2 * e + (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (0.5 * ezz4 * (2. / n ** 2 + exy1 / ezz1 / n / w) / exx1 * ezz1 * w + 0.5 * ezz1 * (2. / n ** 2 - exy4 / ezz4 / n / e) / exx4 * ezz4 * e) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzys = ((-0.5 * (-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * ezz2 * ezz1 / eyy2 * (1 - eyy2 / ezz2) / w + 0.5 * (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * ezz3 * ezz4 / eyy3 * (1 - eyy3 / ezz3) / e) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w *
eyy2 * e - (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (0.5 * ezz3 * (2. / s ** 2 - exy2 / ezz2 / s / w) / exx2 * ezz2 * w + 0.5 * ezz2 * (2. / s ** 2 + exy3 / ezz3 / s / e) / exx3 * ezz3 * e) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzye = (((-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (-n * ezz2 / eyy1 * eyx1 / e / (e + w) + (ezz1 - ezz2) * w / e / (e + w) - s * ezz1 / eyy2 * eyx2 / e / (e + w)) + (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (0.5 * n * ezz4 * ezz3 / eyy4 * (-(1 - eyy4 / ezz4) / n / e - eyx4 / ezz4 * (2. / e ** 2 - 2 / e ** 2 * w / (e + w))) + 0.5 * s * ezz3 * ezz4 / eyy3 * ((1 - eyy3 / ezz3) / s / e - eyx3 / ezz3 * (2. / e ** 2 - 2 / e ** 2 * w / (e + w))) + (ezz4 - ezz3) * w / e / (e + w))) / ezz4 /
ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + (0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * ezz1 * (2 * exx4 / ezz4 / e ** 2 - exy4 / ezz4 / n / e) / exx4 * ezz4 * e - 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * ezz2 * (2 * exx3 / ezz3 / e ** 2 + exy3 / ezz3 / s / e) / exx3 * ezz3 * e) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzyw = (((-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (0.5 * n * ezz1 * ezz2 / eyy1 * ((1 - eyy1 / ezz1) / n / w - eyx1 / ezz1 * (2. / w ** 2 - 2 / w ** 2 * e / (e + w))) - (ezz1 - ezz2) * e / w / (e + w) + 0.5 * s * ezz2 * ezz1 / eyy2 * (-(1 - eyy2 / ezz2) / s / w - eyx2 / ezz2 * (2. / w ** 2 - 2 / w ** 2 * e / (e + w)))) + (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (-n * ezz3 / eyy4 * eyx4 / w / (e + w) - s * ezz4 / eyy3 * eyx3 / w / (e + w) - (ezz4 - ezz3) * e / w / (e + w))) / ezz4 /
ezz3 / (n * eyy3 + s * eyy4) / ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + (0.5 * (ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * ezz4 * (2 * exx1 / ezz1 / w ** 2 + exy1 / ezz1 / n / w) / exx1 * ezz1 * w - 0.5 * (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * ezz3 * (2 * exx2 / ezz2 / w ** 2 - exy2 / ezz2 / s / w) / exx2 * ezz2 * w) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
bzyp = (((-n * ezz4 * ezz3 / eyy4 - s * ezz3 * ezz4 / eyy3) * (0.5 * n * ezz1 * ezz2 / eyy1 * (-k ** 2 * eyx1 - (1 - eyy1 / ezz1) / n / w - eyx1 / ezz1 * (-2. / w ** 2 + 2 / w ** 2 * (e - w) / e)) + (ezz1 - ezz2) * (e - w) / e / w + 0.5 * s * ezz2 * ezz1 / eyy2 * (-k ** 2 * eyx2 + (1 - eyy2 / ezz2) / s / w - eyx2 / ezz2 * (-2. / w ** 2 + 2 / w ** 2 * (e - w) / e))) + (n * ezz1 * ezz2 / eyy1 + s * ezz2 * ezz1 / eyy2) * (0.5 * n * ezz4 * ezz3 / eyy4 * (-k ** 2 * eyx4 + (1 - eyy4 / ezz4) / n / e - eyx4 / ezz4 * (-2. / e ** 2 - 2 / e ** 2 * (e - w) / w)) + 0.5 * s * ezz3 * ezz4 / eyy3 * (-k ** 2 * eyx3 - (1 - eyy3 / ezz3) / s / e - eyx3 / ezz3 * (-2. / e ** 2 - 2 / e ** 2 * (e - w) / w)) + (ezz4 - ezz3) * (e - w) / e / w)) / ezz4 / ezz3 / (n * eyy3 + s * eyy4) /
ezz2 / ezz1 / (n * eyy2 + s * eyy1) / (e + w) * eyy4 * eyy3 * eyy1 * w * eyy2 * e + ((ezz3 / exx2 * ezz2 * w + ezz2 / exx3 * ezz3 * e) * (0.5 * ezz4 * (-2. / n ** 2 - 2 * exx1 / ezz1 / w ** 2 + k ** 2 * exx1 - exy1 / ezz1 / n / w) / exx1 * ezz1 * w + 0.5 * ezz1 * (-2. / n ** 2 - 2 * exx4 / ezz4 / e ** 2 + k ** 2 * exx4 + exy4 / ezz4 / n / e) / exx4 * ezz4 * e) - (ezz4 / exx1 * ezz1 * w + ezz1 / exx4 * ezz4 * e) * (0.5 * ezz3 * (-2. / s ** 2 - 2 * exx2 / ezz2 / w ** 2 + k ** 2 * exx2 + exy2 / ezz2 / s / w) / exx2 * ezz2 * w + 0.5 * ezz2 * (-2. / s ** 2 - 2 * exx3 / ezz3 / e ** 2 + k ** 2 * exx3 - exy3 / ezz3 / s / e) / exx3 * ezz3 * e)) / ezz3 / ezz2 / (w * exx3 + e * exx2) / ezz4 / ezz1 / (w * exx4 + e * exx1) / (n + s) * exx2 * exx3 * n * exx1 * exx4 * s) / b
ii = numpy.arange(nx * ny).reshape(nx, ny)
# NORTH boundary
ib = ii[:, -1]
if boundary[0] == 'S':
sign = 1
elif boundary[0] == 'A':
sign = -1
elif boundary[0] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
bzxs[ib] += sign * bzxn[ib]
bzxse[ib] += sign * bzxne[ib]
bzxsw[ib] += sign * bzxnw[ib]
bzys[ib] -= sign * bzyn[ib]
bzyse[ib] -= sign * bzyne[ib]
bzysw[ib] -= sign * bzynw[ib]
# SOUTH boundary
ib = ii[:, 0]
if boundary[1] == 'S':
sign = 1
elif boundary[1] == 'A':
sign = -1
elif boundary[1] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
bzxn[ib] += sign * bzxs[ib]
bzxne[ib] += sign * bzxse[ib]
bzxnw[ib] += sign * bzxsw[ib]
bzyn[ib] -= sign * bzys[ib]
bzyne[ib] -= sign * bzyse[ib]
bzynw[ib] -= sign * bzysw[ib]
# EAST boundary
ib = ii[-1, :]
if boundary[2] == 'S':
sign = 1
elif boundary[2] == 'A':
sign = -1
elif boundary[2] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
bzxw[ib] += sign * bzxe[ib]
bzxnw[ib] += sign * bzxne[ib]
bzxsw[ib] += sign * bzxse[ib]
bzyw[ib] -= sign * bzye[ib]
bzynw[ib] -= sign * bzyne[ib]
bzysw[ib] -= sign * bzyse[ib]
# WEST boundary
ib = ii[0, :]
if boundary[3] == 'S':
sign = 1
elif boundary[3] == 'A':
sign = -1
elif boundary[3] == '0':
sign = 0
else:
raise ValueError('unknown boundary conditions')
bzxe[ib] += sign * bzxw[ib]
bzxne[ib] += sign * bzxnw[ib]
bzxse[ib] += sign * bzxsw[ib]
bzye[ib] -= sign * bzyw[ib]
bzyne[ib] -= sign * bzynw[ib]
bzyse[ib] -= sign * bzysw[ib]
# Assemble sparse matrix
iall = ii.flatten()
i_s = ii[:, :-1].flatten()
i_n = ii[:, 1:].flatten()
i_e = ii[1:, :].flatten()
i_w = ii[:-1, :].flatten()
i_ne = ii[1:, 1:].flatten()
i_se = ii[1:, :-1].flatten()
i_sw = ii[:-1, :-1].flatten()
i_nw = ii[:-1, 1:].flatten()
Izx = numpy.r_[iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw]
Jzx = numpy.r_[iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se]
Vzx = numpy.r_[bzxp[iall], bzxe[i_w], bzxw[i_e], bzxn[i_s], bzxs[
i_n], bzxsw[i_ne], bzxnw[i_se], bzxne[i_sw], bzxse[i_nw]]
Izy = numpy.r_[iall, i_w, i_e, i_s, i_n, i_ne, i_se, i_sw, i_nw]
Jzy = numpy.r_[
iall, i_e, i_w, i_n, i_s, i_sw, i_nw, i_ne, i_se] + nx * ny
Vzy = numpy.r_[bzyp[iall], bzye[i_w], bzyw[i_e], bzyn[i_s], bzys[
i_n], bzysw[i_ne], bzynw[i_se], bzyne[i_sw], bzyse[i_nw]]
I = numpy.r_[Izx, Izy]
J = numpy.r_[Jzx, Jzy]
V = numpy.r_[Vzx, Vzy]
B = coo_matrix((V, (I, J))).tocsr()
HxHy = numpy.r_[Hx, Hy]
Hz = B * HxHy.ravel() / 1j
Hz = Hz.reshape(Hx.shape)
# in xc e yc
exx = epsxx[1:-1, 1:-1]
exy = epsxy[1:-1, 1:-1]
eyx = epsyx[1:-1, 1:-1]
eyy = epsyy[1:-1, 1:-1]
ezz = epszz[1:-1, 1:-1]
edet = (exx * eyy - exy * eyx)
h = e.reshape(nx, ny)[:-1, :-1]
v = n.reshape(nx, ny)[:-1, :-1]
# in xc e yc
Dx = neff * EMpy.utils.centered2d(Hy) + (
Hz[:-1, 1:] + Hz[1:, 1:] - Hz[:-1, :-1] - Hz[1:, :-1]) / (2j * k * v)
Dy = -neff * EMpy.utils.centered2d(Hx) - (
Hz[1:, :-1] + Hz[1:, 1:] - Hz[:-1, 1:] - Hz[:-1, :-1]) / (2j * k * h)
Dz = ((Hy[1:, :-1] + Hy[1:, 1:] - Hy[:-1, 1:] - Hy[:-1, :-1]) / (2 * h) -
(Hx[:-1, 1:] + Hx[1:, 1:] - Hx[:-1, :-1] - Hx[1:, :-1]) / (2 * v)) / (1j * k)
Ex = (eyy * Dx - exy * Dy) / edet
Ey = (exx * Dy - eyx * Dx) / edet
Ez = Dz / ezz
Hzs.append(Hz)
Exs.append(Ex)
Eys.append(Ey)
Ezs.append(Ez)
return (Hzs, Exs, Eys, Ezs)
def solve(self, neigs=4, tol=0, guess=None):
"""
This function finds the eigenmodes.
Parameters
----------
neigs : int
number of eigenmodes to find
tol : float
Relative accuracy for eigenvalues.
The default value of 0 implies machine precision.
guess : float
A guess for the refractive index.
The modesolver will only finds eigenvectors with an
effective refrative index higher than this value.
Returns
-------
self : an instance of the VFDModeSolver class
obtain the fields of interest for specific modes using, for example:
solver = EMpy.modesolvers.FD.VFDModeSolver(wavelength, x, y, epsf, boundary).solve()
Ex = solver.modes[0].Ex
Ey = solver.modes[0].Ey
Ez = solver.modes[0].Ez
"""
from scipy.sparse.linalg import eigen
self.nmodes = neigs
self.tol = tol
A = self.build_matrix()
if guess is not None:
# calculate shift for eigs function
k = 2 * numpy.pi / self.wl
shift = (guess * k) ** 2
else:
shift = None
# Here is where the actual mode-solving takes place!
[eigvals, eigvecs] = eigen.eigs(A,
k=neigs,
which='LR',
tol=tol,
ncv=10*neigs,
return_eigenvectors=True,
sigma=shift)
neffs = self.wl * scipy.sqrt(eigvals) / (2 * numpy.pi)
Hxs = []
Hys = []
nx = self.nx
ny = self.ny
for ieig in range(neigs):
Hxs.append(eigvecs[:nx * ny, ieig].reshape(nx, ny))
Hys.append(eigvecs[nx * ny:, ieig].reshape(nx, ny))
# sort the modes
idx = numpy.flipud(numpy.argsort(neffs))
neffs = neffs[idx]
tmpx = []
tmpy = []
for i in idx:
tmpx.append(Hxs[i])
tmpy.append(Hys[i])
Hxs = tmpx
Hys = tmpy
[Hzs, Exs, Eys, Ezs] = self.compute_other_fields(neffs, Hxs, Hys)
self.modes = []
for (neff, Hx, Hy, Hz, Ex, Ey, Ez) in zip(neffs, Hxs, Hys, Hzs, Exs, Eys, Ezs):
self.modes.append(
FDMode(self.wl, self.x, self.y, neff, Ex, Ey, Ez, Hx, Hy, Hz).normalize())
return self
def save_modes_for_FDTD(self, x=None, y=None):
for im, m in enumerate(self.modes):
m.save_for_FDTD(str(im), x, y)
def __str__(self):
descr = 'Vectorial Finite Difference Modesolver\n'
return descr
class FDMode(Mode):
def __init__(self, wl, x, y, neff, Ex, Ey, Ez, Hx, Hy, Hz):
self.wl = wl
self.x = x
self.y = y
self.neff = neff
self.Ex = Ex
self.Ey = Ey
self.Ez = Ez
self.Hx = Hx
self.Hy = Hy
self.Hz = Hz
def get_x(self, n=None):
if n is None:
return self.x
return numpy.linspace(self.x[0], self.x[-1], n)
def get_y(self, n=None):
if n is None:
return self.y
return numpy.linspace(self.y[0], self.y[-1], n)
def get_field(self, fname, x=None, y=None):
if fname == 'Ex':
f = self.Ex
centered = True
elif fname == 'Ey':
f = self.Ey
centered = True
elif fname == 'Ez':
f = self.Ez
centered = True
elif fname == 'Hx':
f = self.Hx
centered = False
elif fname == 'Hy':
f = self.Hy
centered = False
elif fname == 'Hz':
f = self.Hz
centered = False
if (x is None) and (y is None):
return f
if centered:
# magnetic fields are not centered
x0 = self.x
y0 = self.y
else:
# electric fields and intensity are centered
x0 = EMpy.utils.centered1d(self.x)
y0 = EMpy.utils.centered1d(self.y)
return EMpy.utils.interp2(x, y, x0, y0, f)
def intensityTETM(self, x=None, y=None):
I_TE = self.Ex * EMpy.utils.centered2d(numpy.conj(self.Hy)) / 2.
I_TM = -self.Ey * EMpy.utils.centered2d(numpy.conj(self.Hx)) / 2.
if x is None and y is None:
return (I_TE, I_TM)
else:
x0 = EMpy.utils.centered1d(self.x)
y0 = EMpy.utils.centered1d(self.y)
I_TE_ = EMpy.utils.interp2(x, y, x0, y0, I_TE)
I_TM_ = EMpy.utils.interp2(x, y, x0, y0, I_TM)
return (I_TE_, I_TM_)
def intensity(self, x=None, y=None):
I_TE, I_TM = self.intensityTETM(x, y)
return I_TE + I_TM
def TEfrac(self, x_=None, y_=None):
if x_ is None:
x = EMpy.utils.centered1d(self.x)
else:
x = x_
if y_ is None:
y = EMpy.utils.centered1d(self.y)
else:
y = y_
STE, STM = self.intensityTETM(x_, y_)
num = EMpy.utils.trapz2(numpy.abs(STE), x=x, y=y)
den = EMpy.utils.trapz2(numpy.abs(STE) + numpy.abs(STM), x=x, y=y)
return num / den
def norm(self):
x = EMpy.utils.centered1d(self.x)
y = EMpy.utils.centered1d(self.y)
return scipy.sqrt(EMpy.utils.trapz2(self.intensity(), x=x, y=y))
def normalize(self):
n = self.norm()
self.Ex /= n
self.Ey /= n
self.Ez /= n
self.Hx /= n
self.Hy /= n
self.Hz /= n
return self
def overlap(self, m, x=None, y=None):
x1 = EMpy.utils.centered1d(self.x)
y1 = EMpy.utils.centered1d(self.y)
x2 = EMpy.utils.centered1d(m.x)
y2 = EMpy.utils.centered1d(m.y)
if x is None:
x = x2
if y is None:
y = y2
# Interpolates m1 onto m2 grid:
Ex1 = EMpy.utils.interp2(x, y, x1, y1, self.Ex)
Ey1 = EMpy.utils.interp2(x, y, x1, y1, self.Ey)
Hx2 = EMpy.utils.interp2(x, y, x2, y2, m.Hx)
Hy2 = EMpy.utils.interp2(x, y, x2, y2, m.Hy)
intensity = (Ex1 * EMpy.utils.centered2d(numpy.conj(Hy2)) -
Ey1 * EMpy.utils.centered2d(numpy.conj(Hx2))) / 2.
return EMpy.utils.trapz2(intensity, x=x, y=y)
def get_fields_for_FDTD(self, x=None, y=None):
"""Get mode's field on a staggered grid.
Note: ignores some fields on the boudaries.
"""
if x is None:
x = self.x
if y is None:
y = self.y
# Ex: ignores y = 0, max
x_Ex = EMpy.utils.centered1d(self.x)
y_Ex = EMpy.utils.centered1d(self.y)
x_Ex_FDTD = EMpy.utils.centered1d(x)
y_Ex_FDTD = y[1:-1]
Ex_FDTD = EMpy.utils.interp2(x_Ex_FDTD, y_Ex_FDTD, x_Ex, y_Ex, self.Ex)
# Ey: ignores x = 0, max
x_Ey = EMpy.utils.centered1d(self.x)
y_Ey = EMpy.utils.centered1d(self.y)
x_Ey_FDTD = x[1:-1]
y_Ey_FDTD = EMpy.utils.centered1d(y)
Ey_FDTD = EMpy.utils.interp2(x_Ey_FDTD, y_Ey_FDTD, x_Ey, y_Ey, self.Ey)
# Ez: ignores x, y = 0, max
x_Ez = EMpy.utils.centered1d(self.x)
y_Ez = EMpy.utils.centered1d(self.y)
x_Ez_FDTD = x[1:-1]
y_Ez_FDTD = y[1:-1]
Ez_FDTD = EMpy.utils.interp2(x_Ez_FDTD, y_Ez_FDTD, x_Ez, y_Ez, self.Ez)
# Hx: ignores x = 0, max, /120pi, reverse direction
x_Hx = self.x
y_Hx = self.y
x_Hx_FDTD = x[1:-1]
y_Hx_FDTD = EMpy.utils.centered1d(y)
Hx_FDTD = EMpy.utils.interp2(
x_Hx_FDTD, y_Hx_FDTD, x_Hx, y_Hx, self.Hx) / (-120. * numpy.pi)
# Hy: ignores y = 0, max, /120pi, reverse direction
x_Hy = self.x
y_Hy = self.y
x_Hy_FDTD = EMpy.utils.centered1d(x)
y_Hy_FDTD = y[1:-1]
Hy_FDTD = EMpy.utils.interp2(
x_Hy_FDTD, y_Hy_FDTD, x_Hy, y_Hy, self.Hy) / (-120. * numpy.pi)
# Hz: /120pi, reverse direction
x_Hz = self.x
y_Hz = self.y
x_Hz_FDTD = EMpy.utils.centered1d(x)
y_Hz_FDTD = EMpy.utils.centered1d(y)
Hz_FDTD = EMpy.utils.interp2(
x_Hz_FDTD, y_Hz_FDTD, x_Hz, y_Hz, self.Hz) / (-120. * numpy.pi)
return (Ex_FDTD, Ey_FDTD, Ez_FDTD, Hx_FDTD, Hy_FDTD, Hz_FDTD)
@staticmethod
def plot_field(x, y, field):
try:
import pylab
except ImportError:
print('no pylab installed')
return
pylab.hot()
pylab.contour(x, y, numpy.abs(field.T), 16)
pylab.axis('image')
def plot_Ex(self, x=None, y=None):
if x is None:
x = EMpy.utils.centered1d(self.x)
if y is None:
y = EMpy.utils.centered1d(self.y)
Ex = self.get_field('Ex', x, y)
self.plot_field(x, y, Ex)
def plot_Ey(self, x=None, y=None):
if x is None:
x = EMpy.utils.centered1d(self.x)
if y is None:
y = EMpy.utils.centered1d(self.y)
Ey = self.get_field('Ey', x, y)
self.plot_field(x, y, Ey)
def plot_Ez(self, x=None, y=None):
if x is None:
x = EMpy.utils.centered1d(self.x)
if y is None:
y = EMpy.utils.centered1d(self.y)
Ez = self.get_field('Ez', x, y)
self.plot_field(x, y, Ez)
def plot_Hx(self, x=None, y=None):
if x is None:
x = self.x
if y is None:
y = self.y
Hx = self.get_field('Hx', x, y)
self.plot_field(x, y, Hx)
def plot_Hy(self, x=None, y=None):
if x is None:
x = self.x
if y is None:
y = self.y
Hy = self.get_field('Hy', x, y)
self.plot_field(x, y, Hy)
def plot_Hz(self, x=None, y=None):
if x is None:
x = self.x
if y is None:
y = self.y
Hz = self.get_field('Hz', x, y)
self.plot_field(x, y, Hz)
def plot_intensity(self):
x = EMpy.utils.centered1d(self.x)
y = EMpy.utils.centered1d(self.y)
I = self.intensity(x, y)
self.plot_field(x, y, I)
def plot(self):
"""Plot the mode's fields."""
try:
import pylab
except ImportError:
print('no pylab installed')
return
pylab.figure()
pylab.subplot(2, 3, 1)
self.plot_Ex()
pylab.title('Ex')
pylab.subplot(2, 3, 2)
self.plot_Ey()
pylab.title('Ey')
pylab.subplot(2, 3, 3)
self.plot_Ez()
pylab.title('Ez')
pylab.subplot(2, 3, 4)
self.plot_Hx()
pylab.title('Hx')
pylab.subplot(2, 3, 5)
self.plot_Hy()
pylab.title('Hy')
pylab.subplot(2, 3, 6)
self.plot_Hz()
pylab.title('Hz')
def stretchmesh(x, y, nlayers, factor, method='PPPP'):
# OKKIO: check me!
# This function can be used to continuously stretch the grid
# spacing at the edges of the computation window for
# finite-difference calculations. This is useful when you would
# like to increase the size of the computation window without
# increasing the total number of points in the computational
# domain. The program implements four different expansion
# methods: uniform, linear, parabolic (the default) and
# geometric. The first three methods also allow for complex
# coordinate stretching, which is useful for creating
# perfectly-matched non-reflective boundaries.
#
# USAGE:
#
# [x,y] = stretchmesh(x,y,nlayers,factor);
# [x,y] = stretchmesh(x,y,nlayers,factor,method);
# [x,y,xc,yc] = stretchmesh(x,y,nlayers,factor);
# [x,y,xc,yc] = stretchmesh(x,y,nlayers,factor,method);
# [x,y,xc,yc,dx,dy] = stretchmesh(x,y,nlayers,factor);
# [x,y,xc,yc,dx,dy] = stretchmesh(x,y,nlayers,factor,method);
#
# INPUT:
#
# x,y - vectors that specify the vertices of the original
# grid, which are usually linearly spaced.
# nlayers - vector that specifies how many layers of the grid
# you would like to expand:
# nlayers(1) = # of layers on the north boundary to stretch
# nlayers(2) = # of layers on the south boundary to stretch
# nlayers(3) = # of layers on the east boundary to stretch
# nlayers(4) = # of layers on the west boundary to stretch
# factor - cumulative factor by which the layers are to be
# expanded. As with nlayers, this can be a 4-vector.
# method - 4-letter string specifying the method of
# stretching for each of the four boundaries. Four different
# methods are supported: uniform, linear, parabolic (default)
# and geometric. For example, method = 'LLLG' will use linear
# expansion for the north, south and east boundaries and
# geometric expansion for the west boundary.
#
# OUTPUT:
#
# x,y - the vertices of the new stretched grid
# xc,yc (optional) - the center cell coordinates of the
# stretched grid
# dx,dy (optional) - the grid spacing (dx = diff(x))
xx = x.astype(complex)
yy = y.astype(complex)
nlayers *= numpy.ones(4)
factor *= numpy.ones(4)
for idx, (n, f, m) in enumerate(zip(nlayers, factor, method.upper())):
if n > 0 and f != 1:
if idx == 0:
# north boundary
kv = numpy.arange(len(y) - 1 - n, len(y))
z = yy
q1 = z[-1 - n]
q2 = z[-1]
elif idx == 1:
# south boundary
kv = numpy.arange(0, n)
z = yy
q1 = z[n]
q2 = z[0]
elif idx == 2:
# east boundary
kv = numpy.arange(len(x) - 1 - n, len(x))
z = xx
q1 = z[-1 - n]
q2 = z[-1]
elif idx == 3:
# west boundary
kv = numpy.arange(0, n)
z = xx
q1 = z[n]
q2 = z[0]
kv = kv.astype(int)
if m == 'U':
c = numpy.polyfit([q1, q2], [q1, q1 + f * (q2 - q1)], 1)
z[kv] = numpy.polyval(c, z[kv])
elif m == 'L':
c = (f - 1) / (q2 - q1)
b = 1 - 2 * c * q1
a = q1 - b * q1 - c * q1 ** 2
z[kv] = a + b * z[kv] + c * z[kv] ** 2
elif m == 'P':
z[kv] = z[kv] + (f - 1) * (z[kv] - q1) ** 3 / (q2 - q1) ** 2
elif m == 'G':
b = scipy.optimize.newton(
lambda s: numpy.exp(s) - 1 - f * s, f)
a = (q2 - q1) / b
z[kv] = q1 + a * (numpy.exp((z[kv] - q1) / a) - 1)
xx = xx.real + 1j * numpy.abs(xx.imag)
yy = yy.real + 1j * numpy.abs(yy.imag)
xc = (xx[:-1] + xx[1:]) / 2.
yc = (yy[:-1] + yy[1:]) / 2.
dx = numpy.diff(xx)
dy = numpy.diff(yy)
return (xx, yy, xc, yc, dx, dy)
| mit |
drawks/ansible | lib/ansible/modules/utilities/logic/fail.py | 45 | 1287 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dag Wieers <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: fail
short_description: Fail with custom message
description:
- This module fails the progress with a custom message.
- It can be useful for bailing out when a certain condition is met using C(when).
- This module is also supported for Windows targets.
version_added: "0.8"
options:
msg:
description:
- The customized message used for failing execution.
- If omitted, fail will simply bail out with a generic message.
type: str
default: Failed as requested from task
notes:
- This module is also supported for Windows targets.
seealso:
- module: assert
- module: debug
- module: meta
author:
- Dag Wieers (@dagwieers)
'''
EXAMPLES = r'''
# Example playbook using fail and when together
- fail:
msg: The system may not be provisioned according to the CMDB status.
when: cmdb_status != "to-be-staged"
'''
| gpl-3.0 |
pkill-nine/qutebrowser | qutebrowser/mainwindow/statusbar/bar.py | 1 | 13144 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""The main statusbar widget."""
from PyQt5.QtCore import pyqtSignal, pyqtSlot, pyqtProperty, Qt, QSize, QTimer
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QStackedLayout, QSizePolicy
from qutebrowser.browser import browsertab
from qutebrowser.config import config, style
from qutebrowser.utils import usertypes, log, objreg, utils
from qutebrowser.mainwindow.statusbar import (backforward, command, progress,
keystring, percentage, url,
tabindex)
from qutebrowser.mainwindow.statusbar import text as textwidget
class ColorFlags:
"""Flags which change the appearance of the statusbar.
Attributes:
prompt: If we're currently in prompt-mode.
insert: If we're currently in insert mode.
command: If we're currently in command mode.
mode: The current caret mode (CaretMode.off/.on/.selection).
private: Whether this window is in private browsing mode.
"""
CaretMode = usertypes.enum('CaretMode', ['off', 'on', 'selection'])
def __init__(self):
self.prompt = False
self.insert = False
self.command = False
self.caret = self.CaretMode.off
self.private = False
def to_stringlist(self):
"""Get a string list of set flags used in the stylesheet.
This also combines flags in ways they're used in the sheet.
"""
strings = []
if self.prompt:
strings.append('prompt')
if self.insert:
strings.append('insert')
if self.command:
strings.append('command')
if self.private:
strings.append('private')
if self.private and self.command:
strings.append('private-command')
if self.caret == self.CaretMode.on:
strings.append('caret')
elif self.caret == self.CaretMode.selection:
strings.append('caret-selection')
else:
assert self.caret == self.CaretMode.off
return strings
def _generate_stylesheet():
flags = [
('private', 'statusbar.{}.private'),
('caret', 'statusbar.{}.caret'),
('caret-selection', 'statusbar.{}.caret-selection'),
('prompt', 'prompts.{}'),
('insert', 'statusbar.{}.insert'),
('command', 'statusbar.{}.command'),
('private-command', 'statusbar.{}.command.private'),
]
stylesheet = """
QWidget#StatusBar,
QWidget#StatusBar QLabel,
QWidget#StatusBar QLineEdit {
font: {{ font['statusbar'] }};
background-color: {{ color['statusbar.bg'] }};
color: {{ color['statusbar.fg'] }};
}
"""
for flag, option in flags:
stylesheet += """
QWidget#StatusBar[color_flags~="%s"],
QWidget#StatusBar[color_flags~="%s"] QLabel,
QWidget#StatusBar[color_flags~="%s"] QLineEdit {
color: {{ color['%s'] }};
background-color: {{ color['%s'] }};
}
""" % (flag, flag, flag, # flake8: disable=S001
option.format('fg'), option.format('bg'))
return stylesheet
class StatusBar(QWidget):
"""The statusbar at the bottom of the mainwindow.
Attributes:
txt: The Text widget in the statusbar.
keystring: The KeyString widget in the statusbar.
percentage: The Percentage widget in the statusbar.
url: The UrlText widget in the statusbar.
prog: The Progress widget in the statusbar.
cmd: The Command widget in the statusbar.
_hbox: The main QHBoxLayout.
_stack: The QStackedLayout with cmd/txt widgets.
_win_id: The window ID the statusbar is associated with.
Signals:
resized: Emitted when the statusbar has resized, so the completion
widget can adjust its size to it.
arg: The new size.
moved: Emitted when the statusbar has moved, so the completion widget
can move to the right position.
arg: The new position.
"""
resized = pyqtSignal('QRect')
moved = pyqtSignal('QPoint')
_severity = None
_color_flags = []
STYLESHEET = _generate_stylesheet()
def __init__(self, *, win_id, private, parent=None):
super().__init__(parent)
objreg.register('statusbar', self, scope='window', window=win_id)
self.setObjectName(self.__class__.__name__)
self.setAttribute(Qt.WA_StyledBackground)
style.set_register_stylesheet(self)
self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
self._win_id = win_id
self._color_flags = ColorFlags()
self._color_flags.private = private
self._hbox = QHBoxLayout(self)
self._set_hbox_padding()
self._hbox.setSpacing(5)
self._stack = QStackedLayout()
self._stack.setContentsMargins(0, 0, 0, 0)
self.cmd = command.Command(private=private, win_id=win_id)
self._stack.addWidget(self.cmd)
objreg.register('status-command', self.cmd, scope='window',
window=win_id)
self.cmd.show_cmd.connect(self._show_cmd_widget)
self.cmd.hide_cmd.connect(self._hide_cmd_widget)
self.txt = textwidget.Text()
self._hbox.addWidget(self.txt)
self.url = url.UrlText()
self._stack.addWidget(self.url)
self._hbox.addLayout(self._stack)
self._hide_cmd_widget()
self.keystring = keystring.KeyString()
self._hbox.addWidget(self.keystring)
#self.percentage = percentage.Percentage()
#self._hbox.addWidget(self.percentage)
self.backforward = backforward.Backforward()
self._hbox.addWidget(self.backforward)
self.tabindex = tabindex.TabIndex()
self._hbox.addWidget(self.tabindex)
# We add a parent to Progress here because it calls self.show() based
# on some signals, and if that happens before it's added to the layout,
# it will quickly blink up as independent window.
self.prog = progress.Progress(self)
self._hbox.addWidget(self.prog)
objreg.get('config').changed.connect(self._on_config_changed)
QTimer.singleShot(0, self.maybe_hide)
def __repr__(self):
return utils.get_repr(self)
@pyqtSlot(str, str)
def _on_config_changed(self, section, option):
if section != 'ui':
return
if option == 'hide-statusbar':
self.maybe_hide()
elif option == 'statusbar-pdading':
self._set_hbox_padding()
@pyqtSlot()
def maybe_hide(self):
"""Hide the statusbar if it's configured to do so."""
hide = config.get('ui', 'hide-statusbar')
tab = self._current_tab()
if hide or (tab is not None and tab.data.fullscreen):
self.hide()
else:
self.show()
def _set_hbox_padding(self):
padding = config.get('ui', 'statusbar-padding')
self._hbox.setContentsMargins(padding.left, 0, padding.right, 0)
@pyqtProperty('QStringList')
def color_flags(self):
"""Getter for self.color_flags, so it can be used as Qt property."""
return self._color_flags.to_stringlist()
def _current_tab(self):
"""Get the currently displayed tab."""
window = objreg.get('tabbed-browser', scope='window',
window=self._win_id)
return window.currentWidget()
def set_mode_active(self, mode, val):
"""Setter for self.{insert,command,caret}_active.
Re-set the stylesheet after setting the value, so everything gets
updated by Qt properly.
"""
if mode == usertypes.KeyMode.insert:
log.statusbar.debug("Setting insert flag to {}".format(val))
self._color_flags.insert = val
if mode == usertypes.KeyMode.command:
log.statusbar.debug("Setting command flag to {}".format(val))
self._color_flags.command = val
elif mode in [usertypes.KeyMode.prompt, usertypes.KeyMode.yesno]:
log.statusbar.debug("Setting prompt flag to {}".format(val))
self._color_flags.prompt = val
elif mode == usertypes.KeyMode.caret:
tab = self._current_tab()
log.statusbar.debug("Setting caret flag - val {}, selection "
"{}".format(val, tab.caret.selection_enabled))
if val:
if tab.caret.selection_enabled:
self._set_mode_text("{} selection".format(mode.name))
self._color_flags.caret = ColorFlags.CaretMode.selection
else:
self._set_mode_text(mode.name)
self._color_flags.caret = ColorFlags.CaretMode.on
else:
self._color_flags.caret = ColorFlags.CaretMode.off
self.setStyleSheet(style.get_stylesheet(self.STYLESHEET))
def _set_mode_text(self, mode):
"""Set the mode text."""
text = "-- {} MODE --".format(mode.upper())
self.txt.set_text(self.txt.Text.normal, text)
def _show_cmd_widget(self):
"""Show command widget instead of temporary text."""
self.txt.hide()
self._stack.setCurrentWidget(self.cmd)
self.show()
def _hide_cmd_widget(self):
"""Show temporary text instead of command widget."""
log.statusbar.debug("Hiding cmd widget")
self.txt.show()
self._stack.setCurrentWidget(self.url)
self.maybe_hide()
@pyqtSlot(str)
def set_text(self, val):
"""Set a normal (persistent) text in the status bar."""
self.txt.set_text(self.txt.Text.normal, val)
@pyqtSlot(usertypes.KeyMode)
def on_mode_entered(self, mode):
"""Mark certain modes in the commandline."""
keyparsers = objreg.get('keyparsers', scope='window',
window=self._win_id)
if keyparsers[mode].passthrough:
self._set_mode_text(mode.name)
if mode in [usertypes.KeyMode.insert,
usertypes.KeyMode.command,
usertypes.KeyMode.caret,
usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
self.set_mode_active(mode, True)
@pyqtSlot(usertypes.KeyMode, usertypes.KeyMode)
def on_mode_left(self, old_mode, new_mode):
"""Clear marked mode."""
keyparsers = objreg.get('keyparsers', scope='window',
window=self._win_id)
if keyparsers[old_mode].passthrough:
if keyparsers[new_mode].passthrough:
self._set_mode_text(new_mode.name)
else:
self.txt.set_text(self.txt.Text.normal, '')
if old_mode in [usertypes.KeyMode.insert,
usertypes.KeyMode.command,
usertypes.KeyMode.caret,
usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
self.set_mode_active(old_mode, False)
@pyqtSlot(browsertab.AbstractTab)
def on_tab_changed(self, tab):
"""Notify sub-widgets when the tab has been changed."""
self.url.on_tab_changed(tab)
self.prog.on_tab_changed(tab)
#self.percentage.on_tab_changed(tab)
self.backforward.on_tab_changed(tab)
self.maybe_hide()
assert tab.private == self._color_flags.private
def resizeEvent(self, e):
"""Extend resizeEvent of QWidget to emit a resized signal afterwards.
Args:
e: The QResizeEvent.
"""
super().resizeEvent(e)
self.resized.emit(self.geometry())
def moveEvent(self, e):
"""Extend moveEvent of QWidget to emit a moved signal afterwards.
Args:
e: The QMoveEvent.
"""
super().moveEvent(e)
self.moved.emit(e.pos())
def minimumSizeHint(self):
"""Set the minimum height to the text height plus some padding."""
padding = config.get('ui', 'statusbar-padding')
width = super().minimumSizeHint().width()
height = self.fontMetrics().height() + padding.top + padding.bottom
return QSize(width, height)
| gpl-3.0 |
romain-dartigues/ansible | test/units/modules/network/dellos6/test_dellos6_config.py | 68 | 6262 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.dellos6 import dellos6_config
from units.modules.utils import set_module_args
from .dellos6_module import TestDellos6Module, load_fixture
class TestDellos6ConfigModule(TestDellos6Module):
module = dellos6_config
def setUp(self):
super(TestDellos6ConfigModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.dellos6.dellos6_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.dellos6.dellos6_config.load_config')
self.load_config = self.mock_load_config.start()
self.mock_run_commands = patch('ansible.modules.network.dellos6.dellos6_config.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestDellos6ConfigModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
config_file = 'dellos6_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_dellos6_config_unchanged(self):
src = load_fixture('dellos6_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_dellos6_config_src(self):
src = load_fixture('dellos6_config_src.cfg')
set_module_args(dict(src=src))
commands = ['hostname foo', 'exit', 'interface Te1/0/2',
'shutdown', 'exit']
self.execute_module(changed=True, commands=commands)
def test_dellos6_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_dellos6_config_save(self):
set_module_args(dict(save=True))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertDictContainsSubset({'command': 'copy running-config startup-config'}, args[0])
# self.assertIn('copy running-config startup-config\r', args)
def test_dellos6_config_lines_wo_parents(self):
set_module_args(dict(lines=['hostname foo']))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands)
def test_dellos6_config_lines_w_parents(self):
set_module_args(dict(lines=['description "teest"', 'exit'], parents=['interface Te1/0/2']))
commands = ['interface Te1/0/2', 'description "teest"', 'exit']
self.execute_module(changed=True, commands=commands)
def test_dellos6_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['snmp-server contact bar']))
commands = ['snmp-server contact bar', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False)
def test_dellos6_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['snmp-server contact bar']))
commands = ['hostname foo', 'snmp-server contact bar']
self.execute_module(changed=True, commands=commands, sort=False)
def test_dellos6_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'],
before=['snmp-server contact bar'],
after=['snmp-server location chennai']))
self.execute_module()
def test_dellos6_config_config(self):
config = 'hostname localhost'
set_module_args(dict(lines=['hostname router'], config=config))
commands = ['hostname router']
self.execute_module(changed=True, commands=commands)
def test_dellos6_config_replace_block(self):
lines = ['description test string', 'shutdown']
parents = ['interface Te1/0/2']
set_module_args(dict(lines=lines, replace='block', parents=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands)
def test_dellos6_config_match_none(self):
lines = ['hostname router']
set_module_args(dict(lines=lines, match='none'))
self.execute_module(changed=True, commands=lines)
def test_dellos6_config_match_none(self):
lines = ['description test string', 'shutdown']
parents = ['interface Te1/0/2']
set_module_args(dict(lines=lines, parents=parents, match='none'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_dellos6_config_match_strict(self):
lines = ['description "test_string"',
'shutdown']
parents = ['interface Te1/0/1']
set_module_args(dict(lines=lines, parents=parents, match='strict'))
commands = parents + ['shutdown']
self.execute_module(changed=True, commands=commands, sort=False)
def test_dellos6_config_match_exact(self):
lines = ['description test_string', 'shutdown']
parents = ['interface Te1/0/1']
set_module_args(dict(lines=lines, parents=parents, match='exact'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
| gpl-3.0 |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/test/test_builtin.py | 1 | 60127 | # Python test set -- built-in functions
import ast
import builtins
import collections
import io
import locale
import os
import pickle
import platform
import random
import sys
import traceback
import types
import unittest
import warnings
from operator import neg
from test.support import TESTFN, unlink, run_unittest, check_warnings
from test.support.script_helper import assert_python_ok
try:
import pty, signal
except ImportError:
pty = signal = None
class Squares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self): return len(self.sofar)
def __getitem__(self, i):
if not 0 <= i < self.max: raise IndexError
n = len(self.sofar)
while n <= i:
self.sofar.append(n*n)
n += 1
return self.sofar[i]
class StrSquares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self):
return len(self.sofar)
def __getitem__(self, i):
if not 0 <= i < self.max:
raise IndexError
n = len(self.sofar)
while n <= i:
self.sofar.append(str(n*n))
n += 1
return self.sofar[i]
class BitBucket:
def write(self, line):
pass
test_conv_no_sign = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
(' \t\t 314 \t\t ', 314),
(repr(sys.maxsize), sys.maxsize),
(' 1x', ValueError),
(' 1 ', 1),
(' 1\02 ', ValueError),
('', ValueError),
(' ', ValueError),
(' \t\t ', ValueError),
(str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
(chr(0x200), ValueError),
]
test_conv_sign = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', ValueError),
('314 ', 314),
(' \t\t 314 \t\t ', ValueError),
(repr(sys.maxsize), sys.maxsize),
(' 1x', ValueError),
(' 1 ', ValueError),
(' 1\02 ', ValueError),
('', ValueError),
(' ', ValueError),
(' \t\t ', ValueError),
(str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
(chr(0x200), ValueError),
]
class TestFailingBool:
def __bool__(self):
raise RuntimeError
class TestFailingIter:
def __iter__(self):
raise RuntimeError
def filter_char(arg):
return ord(arg) > ord("d")
def map_char(arg):
return chr(ord(arg)+1)
class BuiltinTest(unittest.TestCase):
# Helper to check picklability
def check_iter_pickle(self, it, seq, proto):
itorg = it
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(type(itorg), type(it))
self.assertEqual(list(it), seq)
#test the iterator after dropping one from it
it = pickle.loads(d)
try:
next(it)
except StopIteration:
return
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(list(it), seq[1:])
def test_import(self):
__import__('sys')
__import__('time')
__import__('string')
__import__(name='sys')
__import__(name='time', level=0)
self.assertRaises(ImportError, __import__, 'spamspam')
self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
self.assertRaises(ValueError, __import__, '')
self.assertRaises(TypeError, __import__, 'sys', name='sys')
def test_abs(self):
# int
self.assertEqual(abs(0), 0)
self.assertEqual(abs(1234), 1234)
self.assertEqual(abs(-1234), 1234)
self.assertTrue(abs(-sys.maxsize-1) > 0)
# float
self.assertEqual(abs(0.0), 0.0)
self.assertEqual(abs(3.14), 3.14)
self.assertEqual(abs(-3.14), 3.14)
# str
self.assertRaises(TypeError, abs, 'a')
# bool
self.assertEqual(abs(True), 1)
self.assertEqual(abs(False), 0)
# other
self.assertRaises(TypeError, abs)
self.assertRaises(TypeError, abs, None)
class AbsClass(object):
def __abs__(self):
return -5
self.assertEqual(abs(AbsClass()), -5)
def test_all(self):
self.assertEqual(all([2, 4, 6]), True)
self.assertEqual(all([2, None, 6]), False)
self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
self.assertRaises(RuntimeError, all, TestFailingIter())
self.assertRaises(TypeError, all, 10) # Non-iterable
self.assertRaises(TypeError, all) # No args
self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
self.assertEqual(all([]), True) # Empty iterator
self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
S = [50, 60]
self.assertEqual(all(x > 42 for x in S), True)
S = [50, 40, 60]
self.assertEqual(all(x > 42 for x in S), False)
def test_any(self):
self.assertEqual(any([None, None, None]), False)
self.assertEqual(any([None, 4, None]), True)
self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
self.assertRaises(RuntimeError, any, TestFailingIter())
self.assertRaises(TypeError, any, 10) # Non-iterable
self.assertRaises(TypeError, any) # No args
self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
self.assertEqual(any([]), False) # Empty iterator
self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
S = [40, 60, 30]
self.assertEqual(any(x > 42 for x in S), True)
S = [10, 20, 30]
self.assertEqual(any(x > 42 for x in S), False)
def test_ascii(self):
self.assertEqual(ascii(''), '\'\'')
self.assertEqual(ascii(0), '0')
self.assertEqual(ascii(()), '()')
self.assertEqual(ascii([]), '[]')
self.assertEqual(ascii({}), '{}')
a = []
a.append(a)
self.assertEqual(ascii(a), '[[...]]')
a = {}
a[0] = a
self.assertEqual(ascii(a), '{0: {...}}')
# Advanced checks for unicode strings
def _check_uni(s):
self.assertEqual(ascii(s), repr(s))
_check_uni("'")
_check_uni('"')
_check_uni('"\'')
_check_uni('\0')
_check_uni('\r\n\t .')
# Unprintable non-ASCII characters
_check_uni('\x85')
_check_uni('\u1fff')
_check_uni('\U00012fff')
# Lone surrogates
_check_uni('\ud800')
_check_uni('\udfff')
# Issue #9804: surrogates should be joined even for printable
# wide characters (UCS-2 builds).
self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
# All together
s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
self.assertEqual(ascii(s),
r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
def test_neg(self):
x = -sys.maxsize-1
self.assertTrue(isinstance(x, int))
self.assertEqual(-x, sys.maxsize+1)
def test_callable(self):
self.assertTrue(callable(len))
self.assertFalse(callable("a"))
self.assertTrue(callable(callable))
self.assertTrue(callable(lambda x, y: x + y))
self.assertFalse(callable(__builtins__))
def f(): pass
self.assertTrue(callable(f))
class C1:
def meth(self): pass
self.assertTrue(callable(C1))
c = C1()
self.assertTrue(callable(c.meth))
self.assertFalse(callable(c))
# __call__ is looked up on the class, not the instance
c.__call__ = None
self.assertFalse(callable(c))
c.__call__ = lambda self: 0
self.assertFalse(callable(c))
del c.__call__
self.assertFalse(callable(c))
class C2(object):
def __call__(self): pass
c2 = C2()
self.assertTrue(callable(c2))
c2.__call__ = None
self.assertTrue(callable(c2))
class C3(C2): pass
c3 = C3()
self.assertTrue(callable(c3))
def test_chr(self):
self.assertEqual(chr(32), ' ')
self.assertEqual(chr(65), 'A')
self.assertEqual(chr(97), 'a')
self.assertEqual(chr(0xff), '\xff')
self.assertRaises(ValueError, chr, 1<<24)
self.assertEqual(chr(sys.maxunicode),
str('\\U0010ffff'.encode("ascii"), 'unicode-escape'))
self.assertRaises(TypeError, chr)
self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
self.assertEqual(chr(0x00010000), "\U00010000")
self.assertEqual(chr(0x00010001), "\U00010001")
self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
self.assertEqual(chr(0x00100000), "\U00100000")
self.assertEqual(chr(0x00100001), "\U00100001")
self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
self.assertRaises(ValueError, chr, -1)
self.assertRaises(ValueError, chr, 0x00110000)
self.assertRaises((OverflowError, ValueError), chr, 2**32)
def test_cmp(self):
self.assertTrue(not hasattr(builtins, "cmp"))
def test_compile(self):
compile('print(1)\n', '', 'exec')
bom = b'\xef\xbb\xbf'
compile(bom + b'print(1)\n', '', 'exec')
compile(source='pass', filename='?', mode='exec')
compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
compile('pass', '?', dont_inherit=1, mode='exec')
compile(memoryview(b"text"), "name", "exec")
self.assertRaises(TypeError, compile)
self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
mode='eval', source='0', filename='tmp')
compile('print("\xe5")\n', '', 'exec')
self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
# test the optimize argument
codestr = '''def f():
"""doc"""
try:
assert False
except AssertionError:
return (True, f.__doc__)
else:
return (False, f.__doc__)
'''
def f(): """doc"""
values = [(-1, __debug__, f.__doc__),
(0, True, 'doc'),
(1, False, 'doc'),
(2, False, None)]
for optval, debugval, docstring in values:
# test both direct compilation and compilation via AST
codeobjs = []
codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
tree = ast.parse(codestr)
codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
for code in codeobjs:
ns = {}
exec(code, ns)
rv = ns['f']()
self.assertEqual(rv, (debugval, docstring))
def test_delattr(self):
sys.spam = 1
delattr(sys, 'spam')
self.assertRaises(TypeError, delattr)
def test_dir(self):
# dir(wrong number of arguments)
self.assertRaises(TypeError, dir, 42, 42)
# dir() - local scope
local_var = 1
self.assertIn('local_var', dir())
# dir(module)
self.assertIn('exit', dir(sys))
# dir(module_with_invalid__dict__)
class Foo(types.ModuleType):
__dict__ = 8
f = Foo("foo")
self.assertRaises(TypeError, dir, f)
# dir(type)
self.assertIn("strip", dir(str))
self.assertNotIn("__mro__", dir(str))
# dir(obj)
class Foo(object):
def __init__(self):
self.x = 7
self.y = 8
self.z = 9
f = Foo()
self.assertIn("y", dir(f))
# dir(obj_no__dict__)
class Foo(object):
__slots__ = []
f = Foo()
self.assertIn("__repr__", dir(f))
# dir(obj_no__class__with__dict__)
# (an ugly trick to cause getattr(f, "__class__") to fail)
class Foo(object):
__slots__ = ["__class__", "__dict__"]
def __init__(self):
self.bar = "wow"
f = Foo()
self.assertNotIn("__repr__", dir(f))
self.assertIn("bar", dir(f))
# dir(obj_using __dir__)
class Foo(object):
def __dir__(self):
return ["kan", "ga", "roo"]
f = Foo()
self.assertTrue(dir(f) == ["ga", "kan", "roo"])
# dir(obj__dir__tuple)
class Foo(object):
def __dir__(self):
return ("b", "c", "a")
res = dir(Foo())
self.assertIsInstance(res, list)
self.assertTrue(res == ["a", "b", "c"])
# dir(obj__dir__not_sequence)
class Foo(object):
def __dir__(self):
return 7
f = Foo()
self.assertRaises(TypeError, dir, f)
# dir(traceback)
try:
raise IndexError
except:
self.assertEqual(len(dir(sys.exc_info()[2])), 4)
# test that object has a __dir__()
self.assertEqual(sorted([].__dir__()), dir([]))
def test_divmod(self):
self.assertEqual(divmod(12, 7), (1, 5))
self.assertEqual(divmod(-12, 7), (-2, 2))
self.assertEqual(divmod(12, -7), (-2, -2))
self.assertEqual(divmod(-12, -7), (1, -5))
self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
(-3.25, 1.0, (-4.0, 0.75)),
(3.25, -1.0, (-4.0, -0.75)),
(-3.25, -1.0, (3.0, -0.25))]:
result = divmod(num, denom)
self.assertAlmostEqual(result[0], exp_result[0])
self.assertAlmostEqual(result[1], exp_result[1])
self.assertRaises(TypeError, divmod)
def test_eval(self):
self.assertEqual(eval('1+1'), 2)
self.assertEqual(eval(' 1+1\n'), 2)
globals = {'a': 1, 'b': 2}
locals = {'b': 200, 'c': 300}
self.assertEqual(eval('a', globals) , 1)
self.assertEqual(eval('a', globals, locals), 1)
self.assertEqual(eval('b', globals, locals), 200)
self.assertEqual(eval('c', globals, locals), 300)
globals = {'a': 1, 'b': 2}
locals = {'b': 200, 'c': 300}
bom = b'\xef\xbb\xbf'
self.assertEqual(eval(bom + b'a', globals, locals), 1)
self.assertEqual(eval('"\xe5"', globals), "\xe5")
self.assertRaises(TypeError, eval)
self.assertRaises(TypeError, eval, ())
self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
class X:
def __getitem__(self, key):
raise ValueError
self.assertRaises(ValueError, eval, "foo", {}, X())
def test_general_eval(self):
# Tests that general mappings can be used for the locals argument
class M:
"Test mapping interface versus possible calls from eval()."
def __getitem__(self, key):
if key == 'a':
return 12
raise KeyError
def keys(self):
return list('xyz')
m = M()
g = globals()
self.assertEqual(eval('a', g, m), 12)
self.assertRaises(NameError, eval, 'b', g, m)
self.assertEqual(eval('dir()', g, m), list('xyz'))
self.assertEqual(eval('globals()', g, m), g)
self.assertEqual(eval('locals()', g, m), m)
self.assertRaises(TypeError, eval, 'a', m)
class A:
"Non-mapping"
pass
m = A()
self.assertRaises(TypeError, eval, 'a', g, m)
# Verify that dict subclasses work as well
class D(dict):
def __getitem__(self, key):
if key == 'a':
return 12
return dict.__getitem__(self, key)
def keys(self):
return list('xyz')
d = D()
self.assertEqual(eval('a', g, d), 12)
self.assertRaises(NameError, eval, 'b', g, d)
self.assertEqual(eval('dir()', g, d), list('xyz'))
self.assertEqual(eval('globals()', g, d), g)
self.assertEqual(eval('locals()', g, d), d)
# Verify locals stores (used by list comps)
eval('[locals() for i in (2,3)]', g, d)
eval('[locals() for i in (2,3)]', g, collections.UserDict())
class SpreadSheet:
"Sample application showing nested, calculated lookups."
_cells = {}
def __setitem__(self, key, formula):
self._cells[key] = formula
def __getitem__(self, key):
return eval(self._cells[key], globals(), self)
ss = SpreadSheet()
ss['a1'] = '5'
ss['a2'] = 'a1*6'
ss['a3'] = 'a2*7'
self.assertEqual(ss['a3'], 210)
# Verify that dir() catches a non-list returned by eval
# SF bug #1004669
class C:
def __getitem__(self, item):
raise KeyError(item)
def keys(self):
return 1 # used to be 'a' but that's no longer an error
self.assertRaises(TypeError, eval, 'dir()', globals(), C())
def test_exec(self):
g = {}
exec('z = 1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 1})
exec('z = 1+1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 2})
g = {}
l = {}
with check_warnings():
warnings.filterwarnings("ignore", "global statement",
module="<string>")
exec('global a; a = 1; b = 2', g, l)
if '__builtins__' in g:
del g['__builtins__']
if '__builtins__' in l:
del l['__builtins__']
self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
def test_exec_globals(self):
code = compile("print('Hello World!')", "", "exec")
# no builtin function
self.assertRaisesRegex(NameError, "name 'print' is not defined",
exec, code, {'__builtins__': {}})
# __builtins__ must be a mapping type
self.assertRaises(TypeError,
exec, code, {'__builtins__': 123})
# no __build_class__ function
code = compile("class A: pass", "", "exec")
self.assertRaisesRegex(NameError, "__build_class__ not found",
exec, code, {'__builtins__': {}})
class frozendict_error(Exception):
pass
class frozendict(dict):
def __setitem__(self, key, value):
raise frozendict_error("frozendict is readonly")
# read-only builtins
if isinstance(__builtins__, types.ModuleType):
frozen_builtins = frozendict(__builtins__.__dict__)
else:
frozen_builtins = frozendict(__builtins__)
code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
self.assertRaises(frozendict_error,
exec, code, {'__builtins__': frozen_builtins})
# read-only globals
namespace = frozendict({})
code = compile("x=1", "test", "exec")
self.assertRaises(frozendict_error,
exec, code, namespace)
def test_exec_redirected(self):
savestdout = sys.stdout
sys.stdout = None # Whatever that cannot flush()
try:
# Used to raise SystemError('error return without exception set')
exec('a')
except NameError:
pass
finally:
sys.stdout = savestdout
def test_filter(self):
self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
def identity(item):
return 1
filter(identity, Squares(5))
self.assertRaises(TypeError, filter)
class BadSeq(object):
def __getitem__(self, index):
if index<4:
return 42
raise ValueError
self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
def badfunc():
pass
self.assertRaises(TypeError, list, filter(badfunc, range(5)))
# test bltinmodule.c::filtertuple()
self.assertEqual(list(filter(None, (1, 2))), [1, 2])
self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
self.assertRaises(TypeError, list, filter(42, (1, 2)))
def test_filter_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
f1 = filter(filter_char, "abcdeabcde")
f2 = filter(filter_char, "abcdeabcde")
self.check_iter_pickle(f1, list(f2), proto)
def test_getattr(self):
self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
self.assertRaises(TypeError, getattr, sys, 1)
self.assertRaises(TypeError, getattr, sys, 1, "foo")
self.assertRaises(TypeError, getattr)
self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
# unicode surrogates are not encodable to the default encoding (utf8)
self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
def test_hasattr(self):
self.assertTrue(hasattr(sys, 'stdout'))
self.assertRaises(TypeError, hasattr, sys, 1)
self.assertRaises(TypeError, hasattr)
self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
# Check that hasattr propagates all exceptions outside of
# AttributeError.
class A:
def __getattr__(self, what):
raise SystemExit
self.assertRaises(SystemExit, hasattr, A(), "b")
class B:
def __getattr__(self, what):
raise ValueError
self.assertRaises(ValueError, hasattr, B(), "b")
def test_hash(self):
hash(None)
self.assertEqual(hash(1), hash(1))
self.assertEqual(hash(1), hash(1.0))
hash('spam')
self.assertEqual(hash('spam'), hash(b'spam'))
hash((0,1,2,3))
def f(): pass
self.assertRaises(TypeError, hash, [])
self.assertRaises(TypeError, hash, {})
# Bug 1536021: Allow hash to return long objects
class X:
def __hash__(self):
return 2**100
self.assertEqual(type(hash(X())), int)
class Z(int):
def __hash__(self):
return self
self.assertEqual(hash(Z(42)), hash(42))
def test_hex(self):
self.assertEqual(hex(16), '0x10')
self.assertEqual(hex(-16), '-0x10')
self.assertRaises(TypeError, hex, {})
def test_id(self):
id(None)
id(1)
id(1.0)
id('spam')
id((0,1,2,3))
id([0,1,2,3])
id({'spam': 1, 'eggs': 2, 'ham': 3})
# Test input() later, alphabetized as if it were raw_input
def test_iter(self):
self.assertRaises(TypeError, iter)
self.assertRaises(TypeError, iter, 42, 42)
lists = [("1", "2"), ["1", "2"], "12"]
for l in lists:
i = iter(l)
self.assertEqual(next(i), '1')
self.assertEqual(next(i), '2')
self.assertRaises(StopIteration, next, i)
def test_isinstance(self):
class C:
pass
class D(C):
pass
class E:
pass
c = C()
d = D()
e = E()
self.assertTrue(isinstance(c, C))
self.assertTrue(isinstance(d, C))
self.assertTrue(not isinstance(e, C))
self.assertTrue(not isinstance(c, D))
self.assertTrue(not isinstance('foo', E))
self.assertRaises(TypeError, isinstance, E, 'foo')
self.assertRaises(TypeError, isinstance)
def test_issubclass(self):
class C:
pass
class D(C):
pass
class E:
pass
c = C()
d = D()
e = E()
self.assertTrue(issubclass(D, C))
self.assertTrue(issubclass(C, C))
self.assertTrue(not issubclass(C, D))
self.assertRaises(TypeError, issubclass, 'foo', E)
self.assertRaises(TypeError, issubclass, E, 'foo')
self.assertRaises(TypeError, issubclass)
def test_len(self):
self.assertEqual(len('123'), 3)
self.assertEqual(len(()), 0)
self.assertEqual(len((1, 2, 3, 4)), 4)
self.assertEqual(len([1, 2, 3, 4]), 4)
self.assertEqual(len({}), 0)
self.assertEqual(len({'a':1, 'b': 2}), 2)
class BadSeq:
def __len__(self):
raise ValueError
self.assertRaises(ValueError, len, BadSeq())
class InvalidLen:
def __len__(self):
return None
self.assertRaises(TypeError, len, InvalidLen())
class FloatLen:
def __len__(self):
return 4.5
self.assertRaises(TypeError, len, FloatLen())
class HugeLen:
def __len__(self):
return sys.maxsize + 1
self.assertRaises(OverflowError, len, HugeLen())
class NoLenMethod(object): pass
self.assertRaises(TypeError, len, NoLenMethod())
def test_map(self):
self.assertEqual(
list(map(lambda x: x*x, range(1,4))),
[1, 4, 9]
)
try:
from math import sqrt
except ImportError:
def sqrt(x):
return pow(x, 0.5)
self.assertEqual(
list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
[[4.0, 2.0], [9.0, 3.0]]
)
self.assertEqual(
list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
[10, 4, 6]
)
def plus(*v):
accu = 0
for i in v: accu = accu + i
return accu
self.assertEqual(
list(map(plus, [1, 3, 7])),
[1, 3, 7]
)
self.assertEqual(
list(map(plus, [1, 3, 7], [4, 9, 2])),
[1+4, 3+9, 7+2]
)
self.assertEqual(
list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
[1+4+1, 3+9+1, 7+2+0]
)
self.assertEqual(
list(map(int, Squares(10))),
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
)
def Max(a, b):
if a is None:
return b
if b is None:
return a
return max(a, b)
self.assertEqual(
list(map(Max, Squares(3), Squares(2))),
[0, 1]
)
self.assertRaises(TypeError, map)
self.assertRaises(TypeError, map, lambda x: x, 42)
class BadSeq:
def __iter__(self):
raise ValueError
yield None
self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
def badfunc(x):
raise RuntimeError
self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
def test_map_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
m1 = map(map_char, "Is this the real life?")
m2 = map(map_char, "Is this the real life?")
self.check_iter_pickle(m1, list(m2), proto)
def test_max(self):
self.assertEqual(max('123123'), '3')
self.assertEqual(max(1, 2, 3), 3)
self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
self.assertEqual(max(1, 2, 3.0), 3.0)
self.assertEqual(max(1, 2.0, 3), 3)
self.assertEqual(max(1.0, 2, 3), 3)
self.assertRaises(TypeError, max)
self.assertRaises(TypeError, max, 42)
self.assertRaises(ValueError, max, ())
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, max, BadSeq())
for stmt in (
"max(key=int)", # no args
"max(default=None)",
"max(1, 2, default=None)", # require container for default
"max(default=None, key=int)",
"max(1, key=int)", # single arg not iterable
"max(1, 2, keystone=int)", # wrong keyword
"max(1, 2, key=int, abc=int)", # two many keywords
"max(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt, globals())
except TypeError:
pass
else:
self.fail(stmt)
self.assertEqual(max((1,), key=neg), 1) # one elem iterable
self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
self.assertEqual(max(1, 2, key=neg), 1) # two elems
self.assertEqual(max((), default=None), None) # zero elem iterable
self.assertEqual(max((1,), default=None), 1) # one elem iterable
self.assertEqual(max((1,2), default=None), 2) # two elem iterable
self.assertEqual(max((), default=1, key=neg), 1)
self.assertEqual(max((1, 2), default=3, key=neg), 1)
data = [random.randrange(200) for i in range(100)]
keys = dict((elem, random.randrange(50)) for elem in data)
f = keys.__getitem__
self.assertEqual(max(data, key=f),
sorted(reversed(data), key=f)[-1])
def test_min(self):
self.assertEqual(min('123123'), '1')
self.assertEqual(min(1, 2, 3), 1)
self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
self.assertEqual(min(1, 2, 3.0), 1)
self.assertEqual(min(1, 2.0, 3), 1)
self.assertEqual(min(1.0, 2, 3), 1.0)
self.assertRaises(TypeError, min)
self.assertRaises(TypeError, min, 42)
self.assertRaises(ValueError, min, ())
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, min, BadSeq())
for stmt in (
"min(key=int)", # no args
"min(default=None)",
"min(1, 2, default=None)", # require container for default
"min(default=None, key=int)",
"min(1, key=int)", # single arg not iterable
"min(1, 2, keystone=int)", # wrong keyword
"min(1, 2, key=int, abc=int)", # two many keywords
"min(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt, globals())
except TypeError:
pass
else:
self.fail(stmt)
self.assertEqual(min((1,), key=neg), 1) # one elem iterable
self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
self.assertEqual(min(1, 2, key=neg), 2) # two elems
self.assertEqual(min((), default=None), None) # zero elem iterable
self.assertEqual(min((1,), default=None), 1) # one elem iterable
self.assertEqual(min((1,2), default=None), 1) # two elem iterable
self.assertEqual(min((), default=1, key=neg), 1)
self.assertEqual(min((1, 2), default=1, key=neg), 2)
data = [random.randrange(200) for i in range(100)]
keys = dict((elem, random.randrange(50)) for elem in data)
f = keys.__getitem__
self.assertEqual(min(data, key=f),
sorted(data, key=f)[0])
def test_next(self):
it = iter(range(2))
self.assertEqual(next(it), 0)
self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it)
self.assertRaises(StopIteration, next, it)
self.assertEqual(next(it, 42), 42)
class Iter(object):
def __iter__(self):
return self
def __next__(self):
raise StopIteration
it = iter(Iter())
self.assertEqual(next(it, 42), 42)
self.assertRaises(StopIteration, next, it)
def gen():
yield 1
return
it = gen()
self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it)
self.assertEqual(next(it, 42), 42)
def test_oct(self):
self.assertEqual(oct(100), '0o144')
self.assertEqual(oct(-100), '-0o144')
self.assertRaises(TypeError, oct, ())
def write_testfile(self):
# NB the first 4 lines are also used to test input, below
fp = open(TESTFN, 'w')
self.addCleanup(unlink, TESTFN)
with fp:
fp.write('1+1\n')
fp.write('The quick brown fox jumps over the lazy dog')
fp.write('.\n')
fp.write('Dear John\n')
fp.write('XXX'*100)
fp.write('YYY'*100)
def test_open(self):
self.write_testfile()
fp = open(TESTFN, 'r')
with fp:
self.assertEqual(fp.readline(4), '1+1\n')
self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
self.assertEqual(fp.readline(4), 'Dear')
self.assertEqual(fp.readline(100), ' John\n')
self.assertEqual(fp.read(300), 'XXX'*100)
self.assertEqual(fp.read(1000), 'YYY'*100)
def test_open_default_encoding(self):
old_environ = dict(os.environ)
try:
# try to get a user preferred encoding different than the current
# locale encoding to check that open() uses the current locale
# encoding and not the user preferred encoding
for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
if key in os.environ:
del os.environ[key]
self.write_testfile()
current_locale_encoding = locale.getpreferredencoding(False)
fp = open(TESTFN, 'w')
with fp:
self.assertEqual(fp.encoding, current_locale_encoding)
finally:
os.environ.clear()
os.environ.update(old_environ)
def test_open_non_inheritable(self):
fileobj = open(__file__)
with fileobj:
self.assertFalse(os.get_inheritable(fileobj.fileno()))
def test_ord(self):
self.assertEqual(ord(' '), 32)
self.assertEqual(ord('A'), 65)
self.assertEqual(ord('a'), 97)
self.assertEqual(ord('\x80'), 128)
self.assertEqual(ord('\xff'), 255)
self.assertEqual(ord(b' '), 32)
self.assertEqual(ord(b'A'), 65)
self.assertEqual(ord(b'a'), 97)
self.assertEqual(ord(b'\x80'), 128)
self.assertEqual(ord(b'\xff'), 255)
self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
self.assertRaises(TypeError, ord, 42)
self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
self.assertEqual(ord("\U00010000"), 0x00010000)
self.assertEqual(ord("\U00010001"), 0x00010001)
self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
self.assertEqual(ord("\U00100000"), 0x00100000)
self.assertEqual(ord("\U00100001"), 0x00100001)
self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)
def test_pow(self):
self.assertEqual(pow(0,0), 1)
self.assertEqual(pow(0,1), 0)
self.assertEqual(pow(1,0), 1)
self.assertEqual(pow(1,1), 1)
self.assertEqual(pow(2,0), 1)
self.assertEqual(pow(2,10), 1024)
self.assertEqual(pow(2,20), 1024*1024)
self.assertEqual(pow(2,30), 1024*1024*1024)
self.assertEqual(pow(-2,0), 1)
self.assertEqual(pow(-2,1), -2)
self.assertEqual(pow(-2,2), 4)
self.assertEqual(pow(-2,3), -8)
self.assertAlmostEqual(pow(0.,0), 1.)
self.assertAlmostEqual(pow(0.,1), 0.)
self.assertAlmostEqual(pow(1.,0), 1.)
self.assertAlmostEqual(pow(1.,1), 1.)
self.assertAlmostEqual(pow(2.,0), 1.)
self.assertAlmostEqual(pow(2.,10), 1024.)
self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
self.assertAlmostEqual(pow(-2.,0), 1.)
self.assertAlmostEqual(pow(-2.,1), -2.)
self.assertAlmostEqual(pow(-2.,2), 4.)
self.assertAlmostEqual(pow(-2.,3), -8.)
for x in 2, 2.0:
for y in 10, 10.0:
for z in 1000, 1000.0:
if isinstance(x, float) or \
isinstance(y, float) or \
isinstance(z, float):
self.assertRaises(TypeError, pow, x, y, z)
else:
self.assertAlmostEqual(pow(x, y, z), 24.0)
self.assertAlmostEqual(pow(-1, 0.5), 1j)
self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
self.assertRaises(ValueError, pow, -1, -2, 3)
self.assertRaises(ValueError, pow, 1, 2, 0)
self.assertRaises(TypeError, pow)
def test_input(self):
self.write_testfile()
fp = open(TESTFN, 'r')
savestdin = sys.stdin
savestdout = sys.stdout # Eats the echo
try:
sys.stdin = fp
sys.stdout = BitBucket()
self.assertEqual(input(), "1+1")
self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
self.assertEqual(input('testing\n'), 'Dear John')
# SF 1535165: don't segfault on closed stdin
# sys.stdout must be a regular file for triggering
sys.stdout = savestdout
sys.stdin.close()
self.assertRaises(ValueError, input)
sys.stdout = BitBucket()
sys.stdin = io.StringIO("NULL\0")
self.assertRaises(TypeError, input, 42, 42)
sys.stdin = io.StringIO(" 'whitespace'")
self.assertEqual(input(), " 'whitespace'")
sys.stdin = io.StringIO()
self.assertRaises(EOFError, input)
del sys.stdout
self.assertRaises(RuntimeError, input, 'prompt')
del sys.stdin
self.assertRaises(RuntimeError, input, 'prompt')
finally:
sys.stdin = savestdin
sys.stdout = savestdout
fp.close()
# test_int(): see test_int.py for tests of built-in function int().
def test_repr(self):
self.assertEqual(repr(''), '\'\'')
self.assertEqual(repr(0), '0')
self.assertEqual(repr(()), '()')
self.assertEqual(repr([]), '[]')
self.assertEqual(repr({}), '{}')
a = []
a.append(a)
self.assertEqual(repr(a), '[[...]]')
a = {}
a[0] = a
self.assertEqual(repr(a), '{0: {...}}')
def test_round(self):
self.assertEqual(round(0.0), 0.0)
self.assertEqual(type(round(0.0)), int)
self.assertEqual(round(1.0), 1.0)
self.assertEqual(round(10.0), 10.0)
self.assertEqual(round(1000000000.0), 1000000000.0)
self.assertEqual(round(1e20), 1e20)
self.assertEqual(round(-1.0), -1.0)
self.assertEqual(round(-10.0), -10.0)
self.assertEqual(round(-1000000000.0), -1000000000.0)
self.assertEqual(round(-1e20), -1e20)
self.assertEqual(round(0.1), 0.0)
self.assertEqual(round(1.1), 1.0)
self.assertEqual(round(10.1), 10.0)
self.assertEqual(round(1000000000.1), 1000000000.0)
self.assertEqual(round(-1.1), -1.0)
self.assertEqual(round(-10.1), -10.0)
self.assertEqual(round(-1000000000.1), -1000000000.0)
self.assertEqual(round(0.9), 1.0)
self.assertEqual(round(9.9), 10.0)
self.assertEqual(round(999999999.9), 1000000000.0)
self.assertEqual(round(-0.9), -1.0)
self.assertEqual(round(-9.9), -10.0)
self.assertEqual(round(-999999999.9), -1000000000.0)
self.assertEqual(round(-8.0, -1), -10.0)
self.assertEqual(type(round(-8.0, -1)), float)
self.assertEqual(type(round(-8.0, 0)), float)
self.assertEqual(type(round(-8.0, 1)), float)
# Check even / odd rounding behaviour
self.assertEqual(round(5.5), 6)
self.assertEqual(round(6.5), 6)
self.assertEqual(round(-5.5), -6)
self.assertEqual(round(-6.5), -6)
# Check behavior on ints
self.assertEqual(round(0), 0)
self.assertEqual(round(8), 8)
self.assertEqual(round(-8), -8)
self.assertEqual(type(round(0)), int)
self.assertEqual(type(round(-8, -1)), int)
self.assertEqual(type(round(-8, 0)), int)
self.assertEqual(type(round(-8, 1)), int)
# test new kwargs
self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
self.assertRaises(TypeError, round)
# test generic rounding delegation for reals
class TestRound:
def __round__(self):
return 23
class TestNoRound:
pass
self.assertEqual(round(TestRound()), 23)
self.assertRaises(TypeError, round, 1, 2, 3)
self.assertRaises(TypeError, round, TestNoRound())
t = TestNoRound()
t.__round__ = lambda *args: args
self.assertRaises(TypeError, round, t)
self.assertRaises(TypeError, round, t, 0)
# Some versions of glibc for alpha have a bug that affects
# float -> integer rounding (floor, ceil, rint, round) for
# values in the range [2**52, 2**53). See:
#
# http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
#
# We skip this test on Linux/alpha if it would fail.
linux_alpha = (platform.system().startswith('Linux') and
platform.machine().startswith('alpha'))
system_round_bug = round(5e15+1) != 5e15+1
@unittest.skipIf(linux_alpha and system_round_bug,
"test will fail; failure is probably due to a "
"buggy system round function")
def test_round_large(self):
# Issue #1869: integral floats should remain unchanged
self.assertEqual(round(5e15-1), 5e15-1)
self.assertEqual(round(5e15), 5e15)
self.assertEqual(round(5e15+1), 5e15+1)
self.assertEqual(round(5e15+2), 5e15+2)
self.assertEqual(round(5e15+3), 5e15+3)
def test_setattr(self):
setattr(sys, 'spam', 1)
self.assertEqual(sys.spam, 1)
self.assertRaises(TypeError, setattr, sys, 1, 'spam')
self.assertRaises(TypeError, setattr)
# test_str(): see test_unicode.py and test_bytes.py for str() tests.
def test_sum(self):
self.assertEqual(sum([]), 0)
self.assertEqual(sum(list(range(2,8))), 27)
self.assertEqual(sum(iter(list(range(2,8)))), 27)
self.assertEqual(sum(Squares(10)), 285)
self.assertEqual(sum(iter(Squares(10))), 285)
self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
self.assertRaises(TypeError, sum)
self.assertRaises(TypeError, sum, 42)
self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
values = [bytearray(b'a'), bytearray(b'b')]
self.assertRaises(TypeError, sum, values, bytearray(b''))
self.assertRaises(TypeError, sum, [[1], [2], [3]])
self.assertRaises(TypeError, sum, [{2:3}])
self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, sum, BadSeq())
empty = []
sum(([x] for x in range(10)), empty)
self.assertEqual(empty, [])
def test_type(self):
self.assertEqual(type(''), type('123'))
self.assertNotEqual(type(''), type(()))
# We don't want self in vars(), so these are static methods
@staticmethod
def get_vars_f0():
return vars()
@staticmethod
def get_vars_f2():
BuiltinTest.get_vars_f0()
a = 1
b = 2
return vars()
class C_get_vars(object):
def getDict(self):
return {'a':2}
__dict__ = property(fget=getDict)
def test_vars(self):
self.assertEqual(set(vars()), set(dir()))
self.assertEqual(set(vars(sys)), set(dir(sys)))
self.assertEqual(self.get_vars_f0(), {})
self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
self.assertRaises(TypeError, vars, 42, 42)
self.assertRaises(TypeError, vars, 42)
self.assertEqual(vars(self.C_get_vars()), {'a':2})
def test_zip(self):
a = (1, 2, 3)
b = (4, 5, 6)
t = [(1, 4), (2, 5), (3, 6)]
self.assertEqual(list(zip(a, b)), t)
b = [4, 5, 6]
self.assertEqual(list(zip(a, b)), t)
b = (4, 5, 6, 7)
self.assertEqual(list(zip(a, b)), t)
class I:
def __getitem__(self, i):
if i < 0 or i > 2: raise IndexError
return i + 4
self.assertEqual(list(zip(a, I())), t)
self.assertEqual(list(zip()), [])
self.assertEqual(list(zip(*[])), [])
self.assertRaises(TypeError, zip, None)
class G:
pass
self.assertRaises(TypeError, zip, a, G())
self.assertRaises(RuntimeError, zip, a, TestFailingIter())
# Make sure zip doesn't try to allocate a billion elements for the
# result list when one of its arguments doesn't say how long it is.
# A MemoryError is the most likely failure mode.
class SequenceWithoutALength:
def __getitem__(self, i):
if i == 5:
raise IndexError
else:
return i
self.assertEqual(
list(zip(SequenceWithoutALength(), range(2**30))),
list(enumerate(range(5)))
)
class BadSeq:
def __getitem__(self, i):
if i == 5:
raise ValueError
else:
return i
self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
def test_zip_pickle(self):
a = (1, 2, 3)
b = (4, 5, 6)
t = [(1, 4), (2, 5), (3, 6)]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z1 = zip(a, b)
self.check_iter_pickle(z1, t, proto)
def test_format(self):
# Test the basic machinery of the format() builtin. Don't test
# the specifics of the various formatters
self.assertEqual(format(3, ''), '3')
# Returns some classes to use for various tests. There's
# an old-style version, and a new-style version
def classes_new():
class A(object):
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromA(A):
pass
class Simple(object): pass
class DerivedFromSimple(Simple):
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromSimple2(DerivedFromSimple): pass
return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
self.assertEqual(format(A(3), 'spec'), '3spec')
self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
'10abcdef')
class_test(*classes_new())
def empty_format_spec(value):
# test that:
# format(x, '') == str(x)
# format(x) == str(x)
self.assertEqual(format(value, ""), str(value))
self.assertEqual(format(value), str(value))
# for builtin types, format(x, "") == str(x)
empty_format_spec(17**13)
empty_format_spec(1.0)
empty_format_spec(3.1415e104)
empty_format_spec(-3.1415e104)
empty_format_spec(3.1415e-104)
empty_format_spec(-3.1415e-104)
empty_format_spec(object)
empty_format_spec(None)
# TypeError because self.__format__ returns the wrong type
class BadFormatResult:
def __format__(self, format_spec):
return 1.0
self.assertRaises(TypeError, format, BadFormatResult(), "")
# TypeError because format_spec is not unicode or str
self.assertRaises(TypeError, format, object(), 4)
self.assertRaises(TypeError, format, object(), object())
# tests for object.__format__ really belong elsewhere, but
# there's no good place to put them
x = object().__format__('')
self.assertTrue(x.startswith('<object object at'))
# first argument to object.__format__ must be string
self.assertRaises(TypeError, object().__format__, 3)
self.assertRaises(TypeError, object().__format__, object())
self.assertRaises(TypeError, object().__format__, None)
# --------------------------------------------------------------------
# Issue #7994: object.__format__ with a non-empty format string is
# deprecated
def test_deprecated_format_string(obj, fmt_str, should_raise):
if should_raise:
self.assertRaises(TypeError, format, obj, fmt_str)
else:
format(obj, fmt_str)
fmt_strs = ['', 's']
class A:
def __format__(self, fmt_str):
return format('', fmt_str)
for fmt_str in fmt_strs:
test_deprecated_format_string(A(), fmt_str, False)
class B:
pass
class C(object):
pass
for cls in [object, B, C]:
for fmt_str in fmt_strs:
test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)
# --------------------------------------------------------------------
# make sure we can take a subclass of str as a format spec
class DerivedFromStr(str): pass
self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
def test_bin(self):
self.assertEqual(bin(0), '0b0')
self.assertEqual(bin(1), '0b1')
self.assertEqual(bin(-1), '-0b1')
self.assertEqual(bin(2**65), '0b1' + '0' * 65)
self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
def test_bytearray_translate(self):
x = bytearray(b"abc")
self.assertRaises(ValueError, x.translate, b"1", 1)
self.assertRaises(TypeError, x.translate, b"1"*256, 1)
def test_construct_singletons(self):
for const in None, Ellipsis, NotImplemented:
tp = type(const)
self.assertIs(tp(), const)
self.assertRaises(TypeError, tp, 1, 2)
self.assertRaises(TypeError, tp, a=1, b=2)
@unittest.skipUnless(pty, "the pty and signal modules must be available")
class PtyTests(unittest.TestCase):
"""Tests that use a pseudo terminal to guarantee stdin and stdout are
terminals in the test environment"""
def run_child(self, child, terminal_input):
r, w = os.pipe() # Pipe test results from child back to parent
try:
pid, fd = pty.fork()
except (OSError, AttributeError) as e:
os.close(r)
os.close(w)
self.skipTest("pty.fork() raised {}".format(e))
raise
if pid == 0:
# Child
try:
# Make sure we don't get stuck if there's a problem
signal.alarm(2)
os.close(r)
with open(w, "w") as wpipe:
child(wpipe)
except:
traceback.print_exc()
finally:
# We don't want to return to unittest...
os._exit(0)
# Parent
os.close(w)
os.write(fd, terminal_input)
# Get results from the pipe
with open(r, "r") as rpipe:
lines = []
while True:
line = rpipe.readline().strip()
if line == "":
# The other end was closed => the child exited
break
lines.append(line)
# Check the result was got and corresponds to the user's terminal input
if len(lines) != 2:
# Something went wrong, try to get at stderr
# Beware of Linux raising EIO when the slave is closed
child_output = bytearray()
while True:
try:
chunk = os.read(fd, 3000)
except OSError: # Assume EIO
break
if not chunk:
break
child_output.extend(chunk)
os.close(fd)
child_output = child_output.decode("ascii", "ignore")
self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
% (len(lines), child_output))
os.close(fd)
return lines
def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
if not sys.stdin.isatty() or not sys.stdout.isatty():
self.skipTest("stdin and stdout must be ttys")
def child(wpipe):
# Check the error handlers are accounted for
if stdio_encoding:
sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
encoding=stdio_encoding,
errors='surrogateescape')
sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
encoding=stdio_encoding,
errors='replace')
print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
print(ascii(input(prompt)), file=wpipe)
lines = self.run_child(child, terminal_input + b"\r\n")
# Check we did exercise the GNU readline path
self.assertIn(lines[0], {'tty = True', 'tty = False'})
if lines[0] != 'tty = True':
self.skipTest("standard IO in should have been a tty")
input_result = eval(lines[1]) # ascii() -> eval() roundtrip
if stdio_encoding:
expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
else:
expected = terminal_input.decode(sys.stdin.encoding) # what else?
self.assertEqual(input_result, expected)
def test_input_tty(self):
# Test input() functionality when wired to a tty (the code path
# is different and invokes GNU readline if available).
self.check_input_tty("prompt", b"quux")
def test_input_tty_non_ascii(self):
# Check stdin/stdout encoding is used when invoking GNU readline
self.check_input_tty("prompté", b"quux\xe9", "utf-8")
def test_input_tty_non_ascii_unicode_errors(self):
# Check stdin/stdout error handler is used when invoking GNU readline
self.check_input_tty("prompté", b"quux\xe9", "ascii")
def test_input_no_stdout_fileno(self):
# Issue #24402: If stdin is the original terminal but stdout.fileno()
# fails, do not use the original stdout file descriptor
def child(wpipe):
print("stdin.isatty():", sys.stdin.isatty(), file=wpipe)
sys.stdout = io.StringIO() # Does not support fileno()
input("prompt")
print("captured:", ascii(sys.stdout.getvalue()), file=wpipe)
lines = self.run_child(child, b"quux\r")
expected = (
"stdin.isatty(): True",
"captured: 'prompt'",
)
self.assertSequenceEqual(lines, expected)
class TestSorted(unittest.TestCase):
def test_basic(self):
data = list(range(100))
copy = data[:]
random.shuffle(copy)
self.assertEqual(data, sorted(copy))
self.assertNotEqual(data, copy)
data.reverse()
random.shuffle(copy)
self.assertEqual(data, sorted(copy, key=lambda x: -x))
self.assertNotEqual(data, copy)
random.shuffle(copy)
self.assertEqual(data, sorted(copy, reverse=1))
self.assertNotEqual(data, copy)
def test_inputtypes(self):
s = 'abracadabra'
types = [list, tuple, str]
for T in types:
self.assertEqual(sorted(s), sorted(T(s)))
s = ''.join(set(s)) # unique letters only
types = [str, set, frozenset, list, tuple, dict.fromkeys]
for T in types:
self.assertEqual(sorted(s), sorted(T(s)))
def test_baddecorator(self):
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
class ShutdownTest(unittest.TestCase):
def test_cleanup(self):
# Issue #19255: builtins are still available at shutdown
code = """if 1:
import builtins
import sys
class C:
def __del__(self):
print("before")
# Check that builtins still exist
len(())
print("after")
c = C()
# Make this module survive until builtins and sys are cleaned
builtins.here = sys.modules[__name__]
sys.here = sys.modules[__name__]
# Create a reference loop so that this module needs to go
# through a GC phase.
here = sys.modules[__name__]
"""
# Issue #20599: Force ASCII encoding to get a codec implemented in C,
# otherwise the codec may be unloaded before C.__del__() is called, and
# so print("before") fails because the codec cannot be used to encode
# "before" to sys.stdout.encoding. For example, on Windows,
# sys.stdout.encoding is the OEM code page and these code pages are
# implemented in Python
rc, out, err = assert_python_ok("-c", code,
PYTHONIOENCODING="ascii")
self.assertEqual(["before", "after"], out.decode().splitlines())
def load_tests(loader, tests, pattern):
from doctest import DocTestSuite
tests.addTest(DocTestSuite(builtins))
return tests
if __name__ == "__main__":
unittest.main()
| gpl-3.0 |
koomik/CouchPotatoServer | libs/requests/packages/charade/charsetgroupprober.py | 2929 | 3791 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from . import constants
import sys
from .charsetprober import CharSetProber
class CharSetGroupProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mActiveNum = 0
self._mProbers = []
self._mBestGuessProber = None
def reset(self):
CharSetProber.reset(self)
self._mActiveNum = 0
for prober in self._mProbers:
if prober:
prober.reset()
prober.active = True
self._mActiveNum += 1
self._mBestGuessProber = None
def get_charset_name(self):
if not self._mBestGuessProber:
self.get_confidence()
if not self._mBestGuessProber:
return None
# self._mBestGuessProber = self._mProbers[0]
return self._mBestGuessProber.get_charset_name()
def feed(self, aBuf):
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
continue
st = prober.feed(aBuf)
if not st:
continue
if st == constants.eFoundIt:
self._mBestGuessProber = prober
return self.get_state()
elif st == constants.eNotMe:
prober.active = False
self._mActiveNum -= 1
if self._mActiveNum <= 0:
self._mState = constants.eNotMe
return self.get_state()
return self.get_state()
def get_confidence(self):
st = self.get_state()
if st == constants.eFoundIt:
return 0.99
elif st == constants.eNotMe:
return 0.01
bestConf = 0.0
self._mBestGuessProber = None
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
if constants._debug:
sys.stderr.write(prober.get_charset_name()
+ ' not active\n')
continue
cf = prober.get_confidence()
if constants._debug:
sys.stderr.write('%s confidence = %s\n' %
(prober.get_charset_name(), cf))
if bestConf < cf:
bestConf = cf
self._mBestGuessProber = prober
if not self._mBestGuessProber:
return 0.0
return bestConf
# else:
# self._mBestGuessProber = self._mProbers[0]
# return self._mBestGuessProber.get_confidence()
| gpl-3.0 |
skylifewww/pangolin-fog | ckeditor_uploader/utils.py | 9 | 2111 | from __future__ import absolute_import
import mimetypes
import os.path
import random
import re
import string
from django.conf import settings
from django.core.files.storage import default_storage
from django.template.defaultfilters import slugify
from django.utils.encoding import force_text
# Non-image file icons, matched from top to bottom
fileicons_path = '{0}/file-icons/'.format(getattr(settings, 'CKEDITOR_FILEICONS_PATH', '/static/ckeditor'))
CKEDITOR_FILEICONS = getattr(settings, 'CKEDITOR_FILEICONS', [
('\.pdf$', fileicons_path + 'pdf.png'),
('\.doc$|\.docx$|\.odt$', fileicons_path + 'doc.png'),
('\.txt$', fileicons_path + 'txt.png'),
('\.ppt$', fileicons_path + 'ppt.png'),
('\.xls$', fileicons_path + 'xls.png'),
('.*', fileicons_path + 'file.png'), # Default
])
class NotAnImageException(Exception):
pass
def slugify_filename(filename):
""" Slugify filename """
name, ext = os.path.splitext(filename)
slugified = get_slugified_name(name)
return slugified + ext
def get_slugified_name(filename):
slugified = slugify(filename)
return slugified or get_random_string()
def get_random_string():
return ''.join(random.sample(string.ascii_lowercase * 6, 6))
def get_icon_filename(file_name):
"""
Return the path to a file icon that matches the file name.
"""
for regex, iconpath in CKEDITOR_FILEICONS:
if re.search(regex, file_name, re.I):
return iconpath
def get_thumb_filename(file_name):
"""
Generate thumb filename by adding _thumb to end of
filename before . (if present)
"""
return force_text('{0}_thumb{1}').format(*os.path.splitext(file_name))
def get_image_format(extension):
mimetypes.init()
return mimetypes.types_map[extension.lower()]
def get_media_url(path):
"""
Determine system file's media URL.
"""
return default_storage.url(path)
def is_valid_image_extension(file_path):
valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']
_, extension = os.path.splitext(file_path)
return extension.lower() in valid_extensions
| mit |
Varriount/Colliberation | libs/twisted/web/twcgi.py | 1 | 10785 | # -*- test-case-name: twisted.web.test.test_cgi -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
I hold resource classes and helper classes that deal with CGI scripts.
"""
# System Imports
import string
import os
import urllib
# Twisted Imports
from twisted.web import http
from twisted.internet import reactor, protocol
from twisted.spread import pb
from twisted.python import log, filepath
from twisted.web import resource, server, static
class CGIDirectory(resource.Resource, filepath.FilePath):
def __init__(self, pathname):
resource.Resource.__init__(self)
filepath.FilePath.__init__(self, pathname)
def getChild(self, path, request):
fnp = self.child(path)
if not fnp.exists():
return static.File.childNotFound
elif fnp.isdir():
return CGIDirectory(fnp.path)
else:
return CGIScript(fnp.path)
return resource.NoResource()
def render(self, request):
notFound = resource.NoResource(
"CGI directories do not support directory listing.")
return notFound.render(request)
class CGIScript(resource.Resource):
"""
L{CGIScript} is a resource which runs child processes according to the CGI
specification.
The implementation is complex due to the fact that it requires asynchronous
IPC with an external process with an unpleasant protocol.
"""
isLeaf = 1
def __init__(self, filename, registry=None):
"""
Initialize, with the name of a CGI script file.
"""
self.filename = filename
def render(self, request):
"""
Do various things to conform to the CGI specification.
I will set up the usual slew of environment variables, then spin off a
process.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
"""
script_name = "/"+string.join(request.prepath, '/')
serverName = string.split(request.getRequestHostname(), ':')[0]
env = {"SERVER_SOFTWARE": server.version,
"SERVER_NAME": serverName,
"GATEWAY_INTERFACE": "CGI/1.1",
"SERVER_PROTOCOL": request.clientproto,
"SERVER_PORT": str(request.getHost().port),
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": script_name, # XXX
"SCRIPT_FILENAME": self.filename,
"REQUEST_URI": request.uri,
}
client = request.getClient()
if client is not None:
env['REMOTE_HOST'] = client
ip = request.getClientIP()
if ip is not None:
env['REMOTE_ADDR'] = ip
pp = request.postpath
if pp:
env["PATH_INFO"] = "/"+string.join(pp, '/')
if hasattr(request, "content"):
# request.content is either a StringIO or a TemporaryFile, and
# the file pointer is sitting at the beginning (seek(0,0))
request.content.seek(0,2)
length = request.content.tell()
request.content.seek(0,0)
env['CONTENT_LENGTH'] = str(length)
qindex = string.find(request.uri, '?')
if qindex != -1:
qs = env['QUERY_STRING'] = request.uri[qindex+1:]
if '=' in qs:
qargs = []
else:
qargs = [urllib.unquote(x) for x in qs.split('+')]
else:
env['QUERY_STRING'] = ''
qargs = []
# Propogate HTTP headers
for title, header in request.getAllHeaders().items():
envname = string.upper(string.replace(title, '-', '_'))
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = header
# Propogate our environment
for key, value in os.environ.items():
if not env.has_key(key):
env[key] = value
# And they're off!
self.runProcess(env, request, qargs)
return server.NOT_DONE_YET
def runProcess(self, env, request, qargs=[]):
"""
Run the cgi script.
@type env: A C{dict} of C{str}, or C{None}
@param env: The environment variables to pass to the processs that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more
information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A C{list} of C{str}
@param qargs: The command line arguments to pass to the process that
will get spawned.
"""
p = CGIProcessProtocol(request)
reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env,
os.path.dirname(self.filename))
class FilteredScript(CGIScript):
"""
I am a special version of a CGI script, that uses a specific executable.
This is useful for interfacing with other scripting languages that adhere to
the CGI standard. My C{filter} attribute specifies what executable to run,
and my C{filename} init parameter describes which script to pass to the
first argument of that script.
To customize me for a particular location of a CGI interpreter, override
C{filter}.
@type filter: C{str}
@ivar filter: The absolute path to the executable.
"""
filter = '/usr/bin/cat'
def runProcess(self, env, request, qargs=[]):
"""
Run a script through the C{filter} executable.
@type env: A C{dict} of C{str}, or C{None}
@param env: The environment variables to pass to the processs that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more
information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A C{list} of C{str}
@param qargs: The command line arguments to pass to the process that
will get spawned.
"""
p = CGIProcessProtocol(request)
reactor.spawnProcess(p, self.filter,
[self.filter, self.filename] + qargs, env,
os.path.dirname(self.filename))
class CGIProcessProtocol(protocol.ProcessProtocol, pb.Viewable):
handling_headers = 1
headers_written = 0
headertext = ''
errortext = ''
# Remotely relay producer interface.
def view_resumeProducing(self, issuer):
self.resumeProducing()
def view_pauseProducing(self, issuer):
self.pauseProducing()
def view_stopProducing(self, issuer):
self.stopProducing()
def resumeProducing(self):
self.transport.resumeProducing()
def pauseProducing(self):
self.transport.pauseProducing()
def stopProducing(self):
self.transport.loseConnection()
def __init__(self, request):
self.request = request
def connectionMade(self):
self.request.registerProducer(self, 1)
self.request.content.seek(0, 0)
content = self.request.content.read()
if content:
self.transport.write(content)
self.transport.closeStdin()
def errReceived(self, error):
self.errortext = self.errortext + error
def outReceived(self, output):
"""
Handle a chunk of input
"""
# First, make sure that the headers from the script are sorted
# out (we'll want to do some parsing on these later.)
if self.handling_headers:
text = self.headertext + output
headerEnds = []
for delimiter in '\n\n','\r\n\r\n','\r\r', '\n\r\n':
headerend = text.find(delimiter)
if headerend != -1:
headerEnds.append((headerend, delimiter))
if headerEnds:
# The script is entirely in control of response headers; disable the
# default Content-Type value normally provided by
# twisted.web.server.Request.
self.request.defaultContentType = None
headerEnds.sort()
headerend, delimiter = headerEnds[0]
self.headertext = text[:headerend]
# This is a final version of the header text.
linebreak = delimiter[:len(delimiter)/2]
headers = self.headertext.split(linebreak)
for header in headers:
br = header.find(': ')
if br == -1:
log.msg( 'ignoring malformed CGI header: %s' % header )
else:
headerName = header[:br].lower()
headerText = header[br+2:]
if headerName == 'location':
self.request.setResponseCode(http.FOUND)
if headerName == 'status':
try:
statusNum = int(headerText[:3]) #"XXX <description>" sometimes happens.
except:
log.msg( "malformed status header" )
else:
self.request.setResponseCode(statusNum)
else:
# Don't allow the application to control these required headers.
if headerName.lower() not in ('server', 'date'):
self.request.responseHeaders.addRawHeader(headerName, headerText)
output = text[headerend+len(delimiter):]
self.handling_headers = 0
if self.handling_headers:
self.headertext = text
if not self.handling_headers:
self.request.write(output)
def processEnded(self, reason):
if reason.value.exitCode != 0:
log.msg("CGI %s exited with exit code %s" %
(self.request.uri, reason.value.exitCode))
if self.errortext:
log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext))
if self.handling_headers:
log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext))
self.request.write(
resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
"CGI Script Error",
"Premature end of script headers.").render(self.request))
self.request.unregisterProducer()
self.request.finish()
| mit |
thomasboevith/ddo-cli | ddo.py | 1 | 16048 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import docopt
import itertools
import logging
import os
import re
import requests
import sys
import time
import urllib
version = '0.1'
__doc__ = """
ddo.py {version} --- look up words in Den Danske Ordbog
A command-line interface for looking up words in the Danish online dictionary
Den Danske Ordbog which can be found at http://ordnet.dk/ddo
Usage:
{filename} [-S] [-s ...] [-v ...] [-i] <word>
{filename} (-h | --help)
{filename} --version
Options:
-S Very short output (same as -ssss)
-s Short output (add up to four s'es for shorter output).
-i Print word and its inflections only.
-h, --help Show this screen.
--version Show version.
-v Print info (-vv for printing lots of info (debug)).
Examples:
{filename} behændig
Copyright (C) 2016 Thomas Boevith
License: GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it. There is NO
WARRANTY, to the extent permitted by law.
""".format(filename=os.path.basename(__file__), version=version)
class Word:
"""A word class."""
def __init__(self, word, senses=[], numsenses=0):
self.word = word
self.senses = senses
self.numsenses = numsenses
self.download()
def download(self):
"""Retrieves dictionary word entry from a word page."""
page = get_page(word=args['<word>'])
if page is None:
log.debug('Page is empty')
sys.exit(1)
else:
log.debug('Got page for word: %s' % args['<word>'])
# Get all senses of headword from wordpage
senseurls = getsenseurls(page)
self.numsenses = len(senseurls)
for senseurl in senseurls:
log.debug('senseurl: %s' % (senseurl))
sensepage = get_page(url=senseurl)
sense = get_sense(sensepage, headword=self)
if sense is not None:
sense.prettyprint()
self.senses.append(sense)
class Sense:
"""A word sense class."""
newid = itertools.count().next
def __init__(self, headword=None, sense=None, sensenum=None,
sensenumstring=None, senseurl=None, comment=None,
pronounciation=None, inflection=None, part_of_speech=None,
meanings=None, etymology=None, synonyms=None,
examples=None, wordformations=None):
self.headword = headword
self.id = Sense.newid()
self.sense = sense
self.sensenum = sensenum
self.sensenumstring = sensenumstring
self.senseurl = senseurl
self.comment = comment
self.pronounciation = pronounciation
self.inflection = inflection
self.part_of_speech = part_of_speech
self.meanings = meanings
self.etymology = etymology
self.wordformations = wordformations
def prettyprint(self):
"""Prints word sense to standard out."""
if self.sense is None:
return
if args['-i']:
printu(self.sense)
for i in self.inflection.split(','):
if 'eller' in i.strip():
for a in i.split('eller'):
printu("%s%s" % (self.sense, a.strip().strip('-')))
elif i.strip()[0] == '-':
printu("%s%s" % (self.sense, i.strip().strip('-')))
else:
printu(i.strip())
return
printun(self.sense)
if self.sensenumstring is not None:
printun(self.sensenumstring)
elif self.sensenum is not None:
printun(self.sensenum)
if self.pronounciation is not None:
printun(self.pronounciation)
if self.part_of_speech is not None:
printun(self.part_of_speech)
print
if args['-s'] > 3:
return
if self.comment is not None:
printu(self.comment)
if self.inflection is not None:
print('Bøjning:'),
printu(self.inflection)
if args['-s'] > 2:
print
return
if self.etymology is not None:
printun('Oprindelse:')
printu(self.etymology)
if args['-s'] > 1:
print
return
if self.meanings != []:
print
printu('Betydninger:')
for i, meaning in enumerate(self.meanings):
if meaning['id'] is not None:
if len(meaning['id']) == 1:
printun(str(meaning['id'][0]) + '.')
elif len(meaning['id']) == 2:
printun(str(meaning['id'][0]) + '.'
+ chr(int(meaning['id'][1]) + ord('a')))
else:
printun('.'.join(meaning['id']))
if meaning['topic'] is not None:
printun(meaning['topic'].upper())
printu(meaning['meaning'])
if meaning['onyms'] is not None:
for j, onym in enumerate(meaning['onyms']):
printu(onym)
if i < len(self.meanings) - 1:
print
if self.wordformations != []:
print
printu('Orddannelser:')
for i, formation in enumerate(self.wordformations):
printu(formation)
if self.id < self.headword.numsenses - 1:
printu('-' * 79)
def gettext(soupfind):
"""Get the text of an element, stripping off white space."""
if soupfind is not None:
try:
return soupfind.get_text().strip()
except:
return None
def supernumeral(num, encoding='utf-8'):
"""Convert integer to superscript integer."""
if encoding == 'utf-8':
superscripts = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']
superdigit = ''
for digit in str(int(num)):
superdigit += superscripts[int(digit)]
return superdigit
else:
return '(' + str(num) + ')'
def getsenseurls(page):
"""Retrieve all URLS for the senses of a word."""
soup = BeautifulSoup(page, 'lxml')
senseurls = []
try:
queryresult = soup.find('dl', {'id': 'search-panel'}).find('dd',
class_='portletResult')
except:
e = sys.exc_info()[0]
log.error('Could not get query results (error: %s)' % e)
sys.exit(1)
for resultatbox in queryresult.find_all('div', class_='searchResultBox'):
links = resultatbox.find_all('a')
for link in links:
# Convert URL to accepted ASCII encoding
url = (link.get('href')).encode('latin-1')
senseurls.append(url)
return senseurls
def printu(s):
print("%s" % s.encode('utf-8'))
def printun(s):
print("%s" % s.encode('utf-8')),
def get_page(word=None, url=None):
"""Download page for a word using either the word or the complete url."""
if url is not None:
url = url
else:
url = 'http://ordnet.dk/ddo/ordbog?query=' + word
url = urllib.quote(url, safe=',.:=&/?:')
r = requests.get(url)
status_code = r.status_code
content = r.content
if status_code == 200:
log.debug('status code: %s OK' % status_code)
return content
if status_code == 404:
if word is not None:
print('Ingen resultater i Den Danske Ordbog for: %s' % word)
log.debug('status code: %s Not Found' % status_code)
soup = BeautifulSoup(content, 'lxml')
subwarning = gettext(soup.find('div', class_="subWarning"))
if subwarning is not None:
print(subwarning),
try:
for tag in soup.find_all('li', class_='visFlere'):
tag.replaceWith('')
for suggestion in soup.find('div',
class_='nomatch').find('ul',
{'id': 'more-alike-list-long'}).find_all('a'):
print(gettext(suggestion)),
except:
return None
return None
else:
log.debug('request status_code: %s:' % status_code)
return None
def get_sense(sensepage, headword):
"""Extract elements of a word sense by parsning the HTML page."""
if sensepage is None:
log.error('Page is empty: %s' % senseurl)
return None
soup = BeautifulSoup(sensepage, 'lxml')
s = Sense(headword=headword)
artikel = soup.find('div', class_='artikel')
if artikel is None:
log.error('Could not retrieve artikel for: %s' % senseurl)
return None
sense = artikel.find('div', class_='definitionBoxTop').find('span',
class_='match')
s.sense = sense.find(text=True, recursive=False)
s.sensenum = gettext(sense.find(text=False, recursive=False))
s.part_of_speech = gettext(artikel.find('div',
class_='definitionBoxTop').find('span',
class_='tekstmedium allow-glossing'))
inflection = artikel.find('div', {'id': 'id-boj'})
if inflection is not None:
inflection = inflection.find('span',
class_='tekstmedium allow-glossing')
dividerdouble = inflection.find_all('span',
class_='dividerDouble')
if dividerdouble is not None:
for e in dividerdouble:
e.string = '||'
if inflection is not None:
s.inflection = inflection.get_text()
comment = artikel.find('div', class_='definitionBox').find('span',
class_='tekst')
if comment is not None:
s.comment = comment.get_text()
pronounciation = artikel.find('div', {'id': 'id-udt'})
if pronounciation is not None:
pronounciation = pronounciation.find('span',
class_='lydskrift')
s.pronounciation = pronounciation.get_text().strip()
etymology = artikel.find('div', {'id': 'id-ety'})
if etymology is not None:
for link in etymology.find_all('a'):
link.insert_before('_')
link.insert_after('_')
etymology = etymology.find('span',
class_='tekstmedium allow-glossing')
ordform = etymology.find_all('span', class_='ordform')
if ordform is not None:
for e in ordform:
e.string = '/' + e.string + '/'
dividerdot = etymology.find_all('span', class_='dividerDot')
if dividerdot is not None:
for e in dividerdot:
e.string = ' * '
if etymology is not None:
s.etymology = etymology.get_text().strip()
s.meanings = []
meanings = artikel.find('div', {'id': 'content-betydninger'})
if meanings is not None:
for i, b in enumerate(meanings.find_all('div',
class_='definitionIndent', recursive=False)):
meaningdict = {}
onyms = []
meaningdict['topic'] = None
for c in b.find_all('div', class_='definitionBox'):
dividerstroke = c.find_all('span', class_='dividerStroke')
if dividerstroke is not None:
for e in dividerstroke:
e.string = ' * '
if c.find('span', class_='stempelNoBorder') is not None:
meaningdict['topic'] = gettext(c.find('span',
class_='stempelNoBorder'))
if ('id' in c.attrs and
re.compile(r'^betydning-[-0-9]+$').match(c.attrs['id'])):
meaningdict['id'] = c.attrs['id'][10:].split('-')
meaningdict['meaning'] = c.find('span',
class_='definition').get_text().strip()
if 'onym' in c.attrs['class']:
for link in c.find_all('a'):
link.insert_before('_')
link.insert_after('_')
onymname = gettext(c.find('span', class_='stempel'))
onymwords = c.find('span', class_='inlineList')
dividersmall = onymwords.find_all('span',
class_='dividerSmall')
if dividersmall is not None:
for e in dividersmall:
e.string = '|'
onyms.append(onymname.upper() + ': ' + gettext(onymwords))
if 'details' in c.attrs['class']:
detailsname = gettext(c.find('span', class_='stempel'))
detailswords = c.find('span', class_='inlineList')
dividersmall = detailswords.find_all('span',
class_='dividerSmall')
if dividersmall is not None:
for e in dividersmall:
e.string = '|'
onyms.append(detailsname.upper() + ': '
+ gettext(detailswords))
citater = c.find_all('div', class_='rc-box-citater-body')
for citat in citater:
for link in citat.find_all('span', class_='kilde'):
link.insert_after('-- ')
link.extract()
onyms.append(citat.get_text().strip())
meaningdict['onyms'] = onyms
s.meanings.append(meaningdict)
s.wordformations = []
wordformations = artikel.find('div', {'id': 'content-orddannelser'})
if wordformations is not None:
for c in wordformations.find_all('div', class_='definitionBox'):
for link in c.find_all('a'):
link.insert_before('_')
# Ensure white space after links if necessary
if str(link.next.next) == ' ':
link.insert_after('_')
else:
link.insert_after('_ ')
wordformationname = gettext(c.find('span', class_='stempel'))
formation = c.find('span', class_='inlineList')
dividersmall = formation.find_all('span', class_='dividerSmall')
if dividersmall is not None:
for e in dividersmall:
e.string = '|'
dividerdouble = formation.find_all('span', class_='dividerDouble')
if dividerdouble is not None:
for e in dividerdouble:
e.string = '||'
s.wordformations.append(wordformationname.upper() + ': '
+ gettext(formation))
return s
if __name__ == '__main__':
start_time = time.time()
args = docopt.docopt(__doc__, version=str(version))
log = logging.getLogger(os.path.basename(__file__))
formatstr = '%(asctime)-15s %(name)-17s %(levelname)-5s %(message)s'
if args['-v'] >= 2:
logging.basicConfig(level=logging.DEBUG, format=formatstr)
elif args['-v'] == 1:
logging.basicConfig(level=logging.INFO, format=formatstr)
else:
logging.basicConfig(level=logging.WARNING, format=formatstr)
if args['-S']:
args['-s'] = 4
log.debug('%s started' % os.path.basename(__file__))
log.debug('docopt args=%s' % str(args).replace('\n', ''))
log.info('Looking up: %s' % args['<word>'])
word = Word('<word>')
log.debug('Processing time={0:.2f} s'.format(time.time() - start_time))
log.debug('%s ended' % os.path.basename(__file__))
| gpl-3.0 |
andfoy/margffoy-tuay-server | env/lib/python2.7/site-packages/redis/client.py | 21 | 99838 | from __future__ import with_statement
from itertools import chain
import datetime
import sys
import warnings
import threading
import time as mod_time
from redis._compat import (b, basestring, bytes, imap, iteritems, iterkeys,
itervalues, izip, long, nativestr, unicode)
from redis.connection import (ConnectionPool, UnixDomainSocketConnection,
SSLConnection, Token)
from redis.lock import Lock, LuaLock
from redis.exceptions import (
ConnectionError,
DataError,
ExecAbortError,
NoScriptError,
PubSubError,
RedisError,
ResponseError,
TimeoutError,
WatchError,
)
SYM_EMPTY = b('')
def list_or_args(keys, args):
# returns a single list combining keys and args
try:
iter(keys)
# a string or bytes instance can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, (basestring, bytes)):
keys = [keys]
except TypeError:
keys = [keys]
if args:
keys.extend(args)
return keys
def timestamp_to_datetime(response):
"Converts a unix timestamp to a Python datetime object"
if not response:
return None
try:
response = int(response)
except ValueError:
return None
return datetime.datetime.fromtimestamp(response)
def string_keys_to_dict(key_string, callback):
return dict.fromkeys(key_string.split(), callback)
def dict_merge(*dicts):
merged = {}
[merged.update(d) for d in dicts]
return merged
def parse_debug_object(response):
"Parse the results of Redis's DEBUG OBJECT command into a Python dict"
# The 'type' of the object is the first item in the response, but isn't
# prefixed with a name
response = nativestr(response)
response = 'type:' + response
response = dict([kv.split(':') for kv in response.split()])
# parse some expected int values from the string response
# note: this cmd isn't spec'd so these may not appear in all redis versions
int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle')
for field in int_fields:
if field in response:
response[field] = int(response[field])
return response
def parse_object(response, infotype):
"Parse the results of an OBJECT command"
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_info(response):
"Parse the result of Redis's INFO command into a Python dict"
info = {}
response = nativestr(response)
def get_value(value):
if ',' not in value or '=' not in value:
try:
if '.' in value:
return float(value)
else:
return int(value)
except ValueError:
return value
else:
sub_dict = {}
for item in value.split(','):
k, v = item.rsplit('=', 1)
sub_dict[k] = get_value(v)
return sub_dict
for line in response.splitlines():
if line and not line.startswith('#'):
if line.find(':') != -1:
key, value = line.split(':', 1)
info[key] = get_value(value)
else:
# if the line isn't splittable, append it to the "__raw__" key
info.setdefault('__raw__', []).append(line)
return info
SENTINEL_STATE_TYPES = {
'can-failover-its-master': int,
'config-epoch': int,
'down-after-milliseconds': int,
'failover-timeout': int,
'info-refresh': int,
'last-hello-message': int,
'last-ok-ping-reply': int,
'last-ping-reply': int,
'last-ping-sent': int,
'master-link-down-time': int,
'master-port': int,
'num-other-sentinels': int,
'num-slaves': int,
'o-down-time': int,
'pending-commands': int,
'parallel-syncs': int,
'port': int,
'quorum': int,
'role-reported-time': int,
's-down-time': int,
'slave-priority': int,
'slave-repl-offset': int,
'voted-leader-epoch': int
}
def parse_sentinel_state(item):
result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES)
flags = set(result['flags'].split(','))
for name, flag in (('is_master', 'master'), ('is_slave', 'slave'),
('is_sdown', 's_down'), ('is_odown', 'o_down'),
('is_sentinel', 'sentinel'),
('is_disconnected', 'disconnected'),
('is_master_down', 'master_down')):
result[name] = flag in flags
return result
def parse_sentinel_master(response):
return parse_sentinel_state(imap(nativestr, response))
def parse_sentinel_masters(response):
result = {}
for item in response:
state = parse_sentinel_state(imap(nativestr, item))
result[state['name']] = state
return result
def parse_sentinel_slaves_and_sentinels(response):
return [parse_sentinel_state(imap(nativestr, item)) for item in response]
def parse_sentinel_get_master(response):
return response and (response[0], int(response[1])) or None
def pairs_to_dict(response):
"Create a dict given a list of key/value pairs"
it = iter(response)
return dict(izip(it, it))
def pairs_to_dict_typed(response, type_info):
it = iter(response)
result = {}
for key, value in izip(it, it):
if key in type_info:
try:
value = type_info[key](value)
except:
# if for some reason the value can't be coerced, just use
# the string value
pass
result[key] = value
return result
def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response or not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(response)
return list(izip(it, imap(score_cast_func, it)))
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(izip(*[response[i::n] for i in range(n)]))
def int_or_none(response):
if response is None:
return None
return int(response)
def float_or_none(response):
if response is None:
return None
return float(response)
def bool_ok(response):
return nativestr(response) == 'OK'
def parse_client_list(response, **options):
clients = []
for c in nativestr(response).splitlines():
clients.append(dict([pair.split('=') for pair in c.split(' ')]))
return clients
def parse_config_get(response, **options):
response = [nativestr(i) if i is not None else None for i in response]
return response and pairs_to_dict(response) or {}
def parse_scan(response, **options):
cursor, r = response
return long(cursor), r
def parse_hscan(response, **options):
cursor, r = response
return long(cursor), r and pairs_to_dict(r) or {}
def parse_zscan(response, **options):
score_cast_func = options.get('score_cast_func', float)
cursor, r = response
it = iter(r)
return long(cursor), list(izip(it, imap(score_cast_func, it)))
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
'command': b(' ').join(item[3])
} for item in response]
class StrictRedis(object):
"""
Implementation of the Redis protocol.
This abstract class provides a Python interface to all Redis commands
and an implementation of the Redis protocol.
Connection and Pipeline derive from this, implementing how
the commands are sent and received to the Redis server
"""
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'AUTH EXISTS EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST '
'PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
bool
),
string_keys_to_dict(
'BITCOUNT BITPOS DECRBY DEL GETBIT HDEL HLEN INCRBY LINSERT LLEN '
'LPUSHX PFADD PFCOUNT RPUSHX SADD SCARD SDIFFSTORE SETBIT '
'SETRANGE SINTERSTORE SREM STRLEN SUNIONSTORE ZADD ZCARD '
'ZLEXCOUNT ZREM ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCORE',
int
),
string_keys_to_dict('INCRBYFLOAT HINCRBYFLOAT', float),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
'LPUSH RPUSH',
lambda r: isinstance(r, long) and r or nativestr(r) == 'OK'
),
string_keys_to_dict('SORT', sort_return_tuples),
string_keys_to_dict('ZSCORE ZINCRBY', float_or_none),
string_keys_to_dict(
'FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE RENAME '
'SAVE SELECT SHUTDOWN SLAVEOF WATCH UNWATCH',
bool_ok
),
string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
string_keys_to_dict(
'SDIFF SINTER SMEMBERS SUNION',
lambda r: r and set(r) or set()
),
string_keys_to_dict(
'ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
zset_score_pairs
),
string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True),
{
'CLIENT GETNAME': lambda r: r and nativestr(r),
'CLIENT KILL': bool_ok,
'CLIENT LIST': parse_client_list,
'CLIENT SETNAME': bool_ok,
'CONFIG GET': parse_config_get,
'CONFIG RESETSTAT': bool_ok,
'CONFIG SET': bool_ok,
'DEBUG OBJECT': parse_debug_object,
'HGETALL': lambda r: r and pairs_to_dict(r) or {},
'HSCAN': parse_hscan,
'INFO': parse_info,
'LASTSAVE': timestamp_to_datetime,
'OBJECT': parse_object,
'PING': lambda r: nativestr(r) == 'PONG',
'RANDOMKEY': lambda r: r and r or None,
'SCAN': parse_scan,
'SCRIPT EXISTS': lambda r: list(imap(bool, r)),
'SCRIPT FLUSH': bool_ok,
'SCRIPT KILL': bool_ok,
'SCRIPT LOAD': nativestr,
'SENTINEL GET-MASTER-ADDR-BY-NAME': parse_sentinel_get_master,
'SENTINEL MASTER': parse_sentinel_master,
'SENTINEL MASTERS': parse_sentinel_masters,
'SENTINEL MONITOR': bool_ok,
'SENTINEL REMOVE': bool_ok,
'SENTINEL SENTINELS': parse_sentinel_slaves_and_sentinels,
'SENTINEL SET': bool_ok,
'SENTINEL SLAVES': parse_sentinel_slaves_and_sentinels,
'SET': lambda r: r and nativestr(r) == 'OK',
'SLOWLOG GET': parse_slowlog_get,
'SLOWLOG LEN': int,
'SLOWLOG RESET': bool_ok,
'SSCAN': parse_scan,
'TIME': lambda x: (int(x[0]), int(x[1])),
'ZSCAN': parse_zscan
}
)
@classmethod
def from_url(cls, url, db=None, **kwargs):
"""
Return a Redis client object configured from the given URL.
For example::
redis://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?db=0
There are several ways to specify a database number. The parse function
will return the first specified option:
1. A ``db`` querystring option, e.g. redis://localhost?db=0
2. If using the redis:// scheme, the path argument of the url, e.g.
redis://localhost/0
3. The ``db`` argument to this function.
If none of these options are specified, db=0 is used.
Any additional querystring arguments and keyword arguments will be
passed along to the ConnectionPool class's initializer. In the case
of conflicting arguments, querystring arguments always win.
"""
connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)
return cls(connection_pool=connection_pool)
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
socket_connect_timeout=None,
socket_keepalive=None, socket_keepalive_options=None,
connection_pool=None, unix_socket_path=None,
encoding='utf-8', encoding_errors='strict',
charset=None, errors=None,
decode_responses=False, retry_on_timeout=False,
ssl=False, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None):
if not connection_pool:
if charset is not None:
warnings.warn(DeprecationWarning(
'"charset" is deprecated. Use "encoding" instead'))
encoding = charset
if errors is not None:
warnings.warn(DeprecationWarning(
'"errors" is deprecated. Use "encoding_errors" instead'))
encoding_errors = errors
kwargs = {
'db': db,
'password': password,
'socket_timeout': socket_timeout,
'encoding': encoding,
'encoding_errors': encoding_errors,
'decode_responses': decode_responses,
'retry_on_timeout': retry_on_timeout
}
# based on input, setup appropriate connection args
if unix_socket_path is not None:
kwargs.update({
'path': unix_socket_path,
'connection_class': UnixDomainSocketConnection
})
else:
# TCP specific options
kwargs.update({
'host': host,
'port': port,
'socket_connect_timeout': socket_connect_timeout,
'socket_keepalive': socket_keepalive,
'socket_keepalive_options': socket_keepalive_options,
})
if ssl:
kwargs.update({
'connection_class': SSLConnection,
'ssl_keyfile': ssl_keyfile,
'ssl_certfile': ssl_certfile,
'ssl_cert_reqs': ssl_cert_reqs,
'ssl_ca_certs': ssl_ca_certs,
})
connection_pool = ConnectionPool(**kwargs)
self.connection_pool = connection_pool
self._use_lua_lock = None
self.response_callbacks = self.__class__.RESPONSE_CALLBACKS.copy()
def __repr__(self):
return "%s<%s>" % (type(self).__name__, repr(self.connection_pool))
def set_response_callback(self, command, callback):
"Set a custom Response Callback"
self.response_callbacks[command] = callback
def pipeline(self, transaction=True, shard_hint=None):
"""
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are useful for reducing the back-and-forth overhead
between the client and server.
"""
return StrictPipeline(
self.connection_pool,
self.response_callbacks,
transaction,
shard_hint)
def transaction(self, func, *watches, **kwargs):
"""
Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single argument which is a Pipeline object.
"""
shard_hint = kwargs.pop('shard_hint', None)
value_from_callable = kwargs.pop('value_from_callable', False)
with self.pipeline(True, shard_hint) as pipe:
while 1:
try:
if watches:
pipe.watch(*watches)
func_value = func(pipe)
exec_value = pipe.execute()
return func_value if value_from_callable else exec_value
except WatchError:
continue
def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
lock_class=None, thread_local=True):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
``blocking_timeout`` indicates the maximum amount of time in seconds to
spend trying to acquire the lock. A value of ``None`` indicates
continue trying forever. ``blocking_timeout`` can be specified as a
float or integer, both representing the number of seconds to wait.
``lock_class`` forces the specified lock implementation.
``thread_local`` indicates whether the lock token is placed in
thread-local storage. By default, the token is placed in thread local
storage so that a thread only sees its token, not a token set by
another thread. Consider the following timeline:
time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
thread-1 sets the token to "abc"
time: 1, thread-2 blocks trying to acquire `my-lock` using the
Lock instance.
time: 5, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired `my-lock` now that it's available.
thread-2 sets the token to "xyz"
time: 6, thread-1 finishes its work and calls release(). if the
token is *not* stored in thread local storage, then
thread-1 would see the token value as "xyz" and would be
able to successfully release the thread-2's lock.
In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage. """
if lock_class is None:
if self._use_lua_lock is None:
# the first time .lock() is called, determine if we can use
# Lua by attempting to register the necessary scripts
try:
LuaLock.register_scripts(self)
self._use_lua_lock = True
except ResponseError:
self._use_lua_lock = False
lock_class = self._use_lua_lock and LuaLock or Lock
return lock_class(self, name, timeout=timeout, sleep=sleep,
blocking_timeout=blocking_timeout,
thread_local=thread_local)
def pubsub(self, **kwargs):
"""
Return a Publish/Subscribe object. With this object, you can
subscribe to channels and listen for messages that get published to
them.
"""
return PubSub(self.connection_pool, **kwargs)
# COMMAND EXECUTION AND PROTOCOL PARSING
def execute_command(self, *args, **options):
"Execute a command and return a parsed response"
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
finally:
pool.release(connection)
def parse_response(self, connection, command_name, **options):
"Parses a response from the Redis server"
response = connection.read_response()
if command_name in self.response_callbacks:
return self.response_callbacks[command_name](response, **options)
return response
# SERVER INFORMATION
def bgrewriteaof(self):
"Tell the Redis server to rewrite the AOF file from data in memory."
return self.execute_command('BGREWRITEAOF')
def bgsave(self):
"""
Tell the Redis server to save its data to disk. Unlike save(),
this method is asynchronous and returns immediately.
"""
return self.execute_command('BGSAVE')
def client_kill(self, address):
"Disconnects the client at ``address`` (ip:port)"
return self.execute_command('CLIENT KILL', address)
def client_list(self):
"Returns a list of currently connected clients"
return self.execute_command('CLIENT LIST')
def client_getname(self):
"Returns the current connection name"
return self.execute_command('CLIENT GETNAME')
def client_setname(self, name):
"Sets the current connection name"
return self.execute_command('CLIENT SETNAME', name)
def config_get(self, pattern="*"):
"Return a dictionary of configuration based on the ``pattern``"
return self.execute_command('CONFIG GET', pattern)
def config_set(self, name, value):
"Set config item ``name`` with ``value``"
return self.execute_command('CONFIG SET', name, value)
def config_resetstat(self):
"Reset runtime statistics"
return self.execute_command('CONFIG RESETSTAT')
def config_rewrite(self):
"Rewrite config file with the minimal change to reflect running config"
return self.execute_command('CONFIG REWRITE')
def dbsize(self):
"Returns the number of keys in the current database"
return self.execute_command('DBSIZE')
def debug_object(self, key):
"Returns version specific meta information about a given key"
return self.execute_command('DEBUG OBJECT', key)
def echo(self, value):
"Echo the string back from the server"
return self.execute_command('ECHO', value)
def flushall(self):
"Delete all keys in all databases on the current host"
return self.execute_command('FLUSHALL')
def flushdb(self):
"Delete all keys in the current database"
return self.execute_command('FLUSHDB')
def info(self, section=None):
"""
Returns a dictionary containing information about the Redis server
The ``section`` option can be used to select a specific section
of information
The section option is not supported by older versions of Redis Server,
and will generate ResponseError
"""
if section is None:
return self.execute_command('INFO')
else:
return self.execute_command('INFO', section)
def lastsave(self):
"""
Return a Python datetime object representing the last time the
Redis database was saved to disk
"""
return self.execute_command('LASTSAVE')
def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
return self.execute_command('OBJECT', infotype, key, infotype=infotype)
def ping(self):
"Ping the Redis server"
return self.execute_command('PING')
def save(self):
"""
Tell the Redis server to save its data to disk,
blocking until the save is complete
"""
return self.execute_command('SAVE')
def sentinel(self, *args):
"Redis Sentinel's SENTINEL command."
warnings.warn(
DeprecationWarning('Use the individual sentinel_* methods'))
def sentinel_get_master_addr_by_name(self, service_name):
"Returns a (host, port) pair for the given ``service_name``"
return self.execute_command('SENTINEL GET-MASTER-ADDR-BY-NAME',
service_name)
def sentinel_master(self, service_name):
"Returns a dictionary containing the specified masters state."
return self.execute_command('SENTINEL MASTER', service_name)
def sentinel_masters(self):
"Returns a list of dictionaries containing each master's state."
return self.execute_command('SENTINEL MASTERS')
def sentinel_monitor(self, name, ip, port, quorum):
"Add a new master to Sentinel to be monitored"
return self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
def sentinel_remove(self, name):
"Remove a master from Sentinel's monitoring"
return self.execute_command('SENTINEL REMOVE', name)
def sentinel_sentinels(self, service_name):
"Returns a list of sentinels for ``service_name``"
return self.execute_command('SENTINEL SENTINELS', service_name)
def sentinel_set(self, name, option, value):
"Set Sentinel monitoring parameters for a given master"
return self.execute_command('SENTINEL SET', name, option, value)
def sentinel_slaves(self, service_name):
"Returns a list of slaves for ``service_name``"
return self.execute_command('SENTINEL SLAVES', service_name)
def shutdown(self):
"Shutdown the server"
try:
self.execute_command('SHUTDOWN')
except ConnectionError:
# a ConnectionError here is expected
return
raise RedisError("SHUTDOWN seems to have failed.")
def slaveof(self, host=None, port=None):
"""
Set the server to be a replicated slave of the instance identified
by the ``host`` and ``port``. If called without arguments, the
instance is promoted to a master instead.
"""
if host is None and port is None:
return self.execute_command('SLAVEOF', Token('NO'), Token('ONE'))
return self.execute_command('SLAVEOF', host, port)
def slowlog_get(self, num=None):
"""
Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items.
"""
args = ['SLOWLOG GET']
if num is not None:
args.append(num)
return self.execute_command(*args)
def slowlog_len(self):
"Get the number of items in the slowlog"
return self.execute_command('SLOWLOG LEN')
def slowlog_reset(self):
"Remove all items in the slowlog"
return self.execute_command('SLOWLOG RESET')
def time(self):
"""
Returns the server time as a 2-item tuple of ints:
(seconds since epoch, microseconds into this second).
"""
return self.execute_command('TIME')
# BASIC KEY COMMANDS
def append(self, key, value):
"""
Appends the string ``value`` to the value at ``key``. If ``key``
doesn't already exist, create it with a value of ``value``.
Returns the new length of the value at ``key``.
"""
return self.execute_command('APPEND', key, value)
def bitcount(self, key, start=None, end=None):
"""
Returns the count of set bits in the value of ``key``. Optional
``start`` and ``end`` paramaters indicate which bytes to consider
"""
params = [key]
if start is not None and end is not None:
params.append(start)
params.append(end)
elif (start is not None and end is None) or \
(end is not None and start is None):
raise RedisError("Both start and end must be specified")
return self.execute_command('BITCOUNT', *params)
def bitop(self, operation, dest, *keys):
"""
Perform a bitwise operation using ``operation`` between ``keys`` and
store the result in ``dest``.
"""
return self.execute_command('BITOP', operation, dest, *keys)
def bitpos(self, key, bit, start=None, end=None):
"""
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` difines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to look at the first three bytes.
"""
if bit not in (0, 1):
raise RedisError('bit must be 0 or 1')
params = [key, bit]
start is not None and params.append(start)
if start is not None and end is not None:
params.append(end)
elif start is None and end is not None:
raise RedisError("start argument is not set, "
"when end is specified")
return self.execute_command('BITPOS', *params)
def decr(self, name, amount=1):
"""
Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount``
"""
return self.execute_command('DECRBY', name, amount)
def delete(self, *names):
"Delete one or more keys specified by ``names``"
return self.execute_command('DEL', *names)
def __delitem__(self, name):
self.delete(name)
def dump(self, name):
"""
Return a serialized version of the value stored at the specified key.
If key does not exist a nil bulk reply is returned.
"""
return self.execute_command('DUMP', name)
def exists(self, name):
"Returns a boolean indicating whether key ``name`` exists"
return self.execute_command('EXISTS', name)
__contains__ = exists
def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return self.execute_command('EXPIRE', name, time)
def expireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(mod_time.mktime(when.timetuple()))
return self.execute_command('EXPIREAT', name, when)
def get(self, name):
"""
Return the value at key ``name``, or None if the key doesn't exist
"""
return self.execute_command('GET', name)
def __getitem__(self, name):
"""
Return the value at key ``name``, raises a KeyError if the key
doesn't exist.
"""
value = self.get(name)
if value:
return value
raise KeyError(name)
def getbit(self, name, offset):
"Returns a boolean indicating the value of ``offset`` in ``name``"
return self.execute_command('GETBIT', name, offset)
def getrange(self, key, start, end):
"""
Returns the substring of the string value stored at ``key``,
determined by the offsets ``start`` and ``end`` (both are inclusive)
"""
return self.execute_command('GETRANGE', key, start, end)
def getset(self, name, value):
"""
Sets the value at key ``name`` to ``value``
and returns the old value at key ``name`` atomically.
"""
return self.execute_command('GETSET', name, value)
def incr(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
return self.execute_command('INCRBY', name, amount)
def incrby(self, name, amount=1):
"""
Increments the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as ``amount``
"""
# An alias for ``incr()``, because it is already implemented
# as INCRBY redis command.
return self.incr(name, amount)
def incrbyfloat(self, name, amount=1.0):
"""
Increments the value at key ``name`` by floating ``amount``.
If no key exists, the value will be initialized as ``amount``
"""
return self.execute_command('INCRBYFLOAT', name, amount)
def keys(self, pattern='*'):
"Returns a list of keys matching ``pattern``"
return self.execute_command('KEYS', pattern)
def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
args = list_or_args(keys, args)
return self.execute_command('MGET', *args)
def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
"""
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('MSET requires **kwargs or a single dict arg')
kwargs.update(args[0])
items = []
for pair in iteritems(kwargs):
items.extend(pair)
return self.execute_command('MSET', *items)
def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
"""
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('MSETNX requires **kwargs or a single '
'dict arg')
kwargs.update(args[0])
items = []
for pair in iteritems(kwargs):
items.extend(pair)
return self.execute_command('MSETNX', *items)
def move(self, name, db):
"Moves the key ``name`` to a different Redis database ``db``"
return self.execute_command('MOVE', name, db)
def persist(self, name):
"Removes an expiration on ``name``"
return self.execute_command('PERSIST', name)
def pexpire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` milliseconds.
``time`` can be represented by an integer or a Python timedelta
object.
"""
if isinstance(time, datetime.timedelta):
ms = int(time.microseconds / 1000)
time = (time.seconds + time.days * 24 * 3600) * 1000 + ms
return self.execute_command('PEXPIRE', name, time)
def pexpireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
ms = int(when.microsecond / 1000)
when = int(mod_time.mktime(when.timetuple())) * 1000 + ms
return self.execute_command('PEXPIREAT', name, when)
def psetex(self, name, time_ms, value):
"""
Set the value of key ``name`` to ``value`` that expires in ``time_ms``
milliseconds. ``time_ms`` can be represented by an integer or a Python
timedelta object
"""
if isinstance(time_ms, datetime.timedelta):
ms = int(time_ms.microseconds / 1000)
time_ms = (time_ms.seconds + time_ms.days * 24 * 3600) * 1000 + ms
return self.execute_command('PSETEX', name, time_ms, value)
def pttl(self, name):
"Returns the number of milliseconds until the key ``name`` will expire"
return self.execute_command('PTTL', name)
def randomkey(self):
"Returns the name of a random key"
return self.execute_command('RANDOMKEY')
def rename(self, src, dst):
"""
Rename key ``src`` to ``dst``
"""
return self.execute_command('RENAME', src, dst)
def renamenx(self, src, dst):
"Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
return self.execute_command('RENAMENX', src, dst)
def restore(self, name, ttl, value):
"""
Create a key using the provided serialized value, previously obtained
using DUMP.
"""
return self.execute_command('RESTORE', name, ttl, value)
def set(self, name, value, ex=None, px=None, nx=False, xx=False):
"""
Set the value at key ``name`` to ``value``
``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
``nx`` if set to True, set the value at key ``name`` to ``value`` if it
does not already exist.
``xx`` if set to True, set the value at key ``name`` to ``value`` if it
already exists.
"""
pieces = [name, value]
if ex:
pieces.append('EX')
if isinstance(ex, datetime.timedelta):
ex = ex.seconds + ex.days * 24 * 3600
pieces.append(ex)
if px:
pieces.append('PX')
if isinstance(px, datetime.timedelta):
ms = int(px.microseconds / 1000)
px = (px.seconds + px.days * 24 * 3600) * 1000 + ms
pieces.append(px)
if nx:
pieces.append('NX')
if xx:
pieces.append('XX')
return self.execute_command('SET', *pieces)
def __setitem__(self, name, value):
self.set(name, value)
def setbit(self, name, offset, value):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
"""
value = value and 1 or 0
return self.execute_command('SETBIT', name, offset, value)
def setex(self, name, time, value):
"""
Set the value of key ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return self.execute_command('SETEX', name, time, value)
def setnx(self, name, value):
"Set the value of key ``name`` to ``value`` if key doesn't exist"
return self.execute_command('SETNX', name, value)
def setrange(self, name, offset, value):
"""
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger than before.
If ``offset`` exceeds the length of the original value, null bytes
will be used to pad between the end of the previous value and the start
of what's being injected.
Returns the length of the new string.
"""
return self.execute_command('SETRANGE', name, offset, value)
def strlen(self, name):
"Return the number of bytes stored in the value of ``name``"
return self.execute_command('STRLEN', name)
def substr(self, name, start, end=-1):
"""
Return a substring of the string at key ``name``. ``start`` and ``end``
are 0-based integers specifying the portion of the string to return.
"""
return self.execute_command('SUBSTR', name, start, end)
def ttl(self, name):
"Returns the number of seconds until the key ``name`` will expire"
return self.execute_command('TTL', name)
def type(self, name):
"Returns the type of key ``name``"
return self.execute_command('TYPE', name)
def watch(self, *names):
"""
Watches the values at keys ``names``, or None if the key doesn't exist
"""
warnings.warn(DeprecationWarning('Call WATCH from a Pipeline object'))
def unwatch(self):
"""
Unwatches the value at key ``name``, or None of the key doesn't exist
"""
warnings.warn(
DeprecationWarning('Call UNWATCH from a Pipeline object'))
# LIST COMMANDS
def blpop(self, keys, timeout=0):
"""
LPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to LPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeout is 0, then block indefinitely.
"""
if timeout is None:
timeout = 0
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command('BLPOP', *keys)
def brpop(self, keys, timeout=0):
"""
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to LPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeout is 0, then block indefinitely.
"""
if timeout is None:
timeout = 0
if isinstance(keys, basestring):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command('BRPOP', *keys)
def brpoplpush(self, src, dst, timeout=0):
"""
Pop a value off the tail of ``src``, push it on the head of ``dst``
and then return it.
This command blocks until a value is in ``src`` or until ``timeout``
seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
forever.
"""
if timeout is None:
timeout = 0
return self.execute_command('BRPOPLPUSH', src, dst, timeout)
def lindex(self, name, index):
"""
Return the item from list ``name`` at position ``index``
Negative indexes are supported and will return an item at the
end of the list
"""
return self.execute_command('LINDEX', name, index)
def linsert(self, name, where, refvalue, value):
"""
Insert ``value`` in list ``name`` either immediately before or after
[``where``] ``refvalue``
Returns the new length of the list on success or -1 if ``refvalue``
is not in the list.
"""
return self.execute_command('LINSERT', name, where, refvalue, value)
def llen(self, name):
"Return the length of the list ``name``"
return self.execute_command('LLEN', name)
def lpop(self, name):
"Remove and return the first item of the list ``name``"
return self.execute_command('LPOP', name)
def lpush(self, name, *values):
"Push ``values`` onto the head of the list ``name``"
return self.execute_command('LPUSH', name, *values)
def lpushx(self, name, value):
"Push ``value`` onto the head of the list ``name`` if ``name`` exists"
return self.execute_command('LPUSHX', name, value)
def lrange(self, name, start, end):
"""
Return a slice of the list ``name`` between
position ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LRANGE', name, start, end)
def lrem(self, name, count, value):
"""
Remove the first ``count`` occurrences of elements equal to ``value``
from the list stored at ``name``.
The count argument influences the operation in the following ways:
count > 0: Remove elements equal to value moving from head to tail.
count < 0: Remove elements equal to value moving from tail to head.
count = 0: Remove all elements equal to value.
"""
return self.execute_command('LREM', name, count, value)
def lset(self, name, index, value):
"Set ``position`` of list ``name`` to ``value``"
return self.execute_command('LSET', name, index, value)
def ltrim(self, name, start, end):
"""
Trim the list ``name``, removing all values not within the slice
between ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LTRIM', name, start, end)
def rpop(self, name):
"Remove and return the last item of the list ``name``"
return self.execute_command('RPOP', name)
def rpoplpush(self, src, dst):
"""
RPOP a value off of the ``src`` list and atomically LPUSH it
on to the ``dst`` list. Returns the value.
"""
return self.execute_command('RPOPLPUSH', src, dst)
def rpush(self, name, *values):
"Push ``values`` onto the tail of the list ``name``"
return self.execute_command('RPUSH', name, *values)
def rpushx(self, name, value):
"Push ``value`` onto the tail of the list ``name`` if ``name`` exists"
return self.execute_command('RPUSHX', name, value)
def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = [name]
if by is not None:
pieces.append(Token('BY'))
pieces.append(by)
if start is not None and num is not None:
pieces.append(Token('LIMIT'))
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, basestring):
pieces.append(Token('GET'))
pieces.append(get)
else:
for g in get:
pieces.append(Token('GET'))
pieces.append(g)
if desc:
pieces.append(Token('DESC'))
if alpha:
pieces.append(Token('ALPHA'))
if store is not None:
pieces.append(Token('STORE'))
pieces.append(store)
if groups:
if not get or isinstance(get, basestring) or len(get) < 2:
raise DataError('when using "groups" the "get" argument '
'must be specified and contain at least '
'two keys')
options = {'groups': len(get) if groups else None}
return self.execute_command('SORT', *pieces, **options)
# SCAN COMMANDS
def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([Token('MATCH'), match])
if count is not None:
pieces.extend([Token('COUNT'), count])
return self.execute_command('SCAN', *pieces)
def scan_iter(self, match=None, count=None):
"""
Make an iterator using the SCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
cursor = '0'
while cursor != 0:
cursor, data = self.scan(cursor=cursor, match=match, count=count)
for item in data:
yield item
def sscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally return lists of elements in a set. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([Token('MATCH'), match])
if count is not None:
pieces.extend([Token('COUNT'), count])
return self.execute_command('SSCAN', *pieces)
def sscan_iter(self, name, match=None, count=None):
"""
Make an iterator using the SSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
cursor = '0'
while cursor != 0:
cursor, data = self.sscan(name, cursor=cursor,
match=match, count=count)
for item in data:
yield item
def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally return key/value slices in a hash. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([Token('MATCH'), match])
if count is not None:
pieces.extend([Token('COUNT'), count])
return self.execute_command('HSCAN', *pieces)
def hscan_iter(self, name, match=None, count=None):
"""
Make an iterator using the HSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
cursor = '0'
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor,
match=match, count=count)
for item in data.items():
yield item
def zscan(self, name, cursor=0, match=None, count=None,
score_cast_func=float):
"""
Incrementally return lists of elements in a sorted set. Also return a
cursor indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([Token('MATCH'), match])
if count is not None:
pieces.extend([Token('COUNT'), count])
options = {'score_cast_func': score_cast_func}
return self.execute_command('ZSCAN', *pieces, **options)
def zscan_iter(self, name, match=None, count=None,
score_cast_func=float):
"""
Make an iterator using the ZSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
cursor = '0'
while cursor != 0:
cursor, data = self.zscan(name, cursor=cursor, match=match,
count=count,
score_cast_func=score_cast_func)
for item in data:
yield item
# SET COMMANDS
def sadd(self, name, *values):
"Add ``value(s)`` to set ``name``"
return self.execute_command('SADD', name, *values)
def scard(self, name):
"Return the number of elements in set ``name``"
return self.execute_command('SCARD', name)
def sdiff(self, keys, *args):
"Return the difference of sets specified by ``keys``"
args = list_or_args(keys, args)
return self.execute_command('SDIFF', *args)
def sdiffstore(self, dest, keys, *args):
"""
Store the difference of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return self.execute_command('SDIFFSTORE', dest, *args)
def sinter(self, keys, *args):
"Return the intersection of sets specified by ``keys``"
args = list_or_args(keys, args)
return self.execute_command('SINTER', *args)
def sinterstore(self, dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return self.execute_command('SINTERSTORE', dest, *args)
def sismember(self, name, value):
"Return a boolean indicating if ``value`` is a member of set ``name``"
return self.execute_command('SISMEMBER', name, value)
def smembers(self, name):
"Return all members of the set ``name``"
return self.execute_command('SMEMBERS', name)
def smove(self, src, dst, value):
"Move ``value`` from set ``src`` to set ``dst`` atomically"
return self.execute_command('SMOVE', src, dst, value)
def spop(self, name):
"Remove and return a random member of set ``name``"
return self.execute_command('SPOP', name)
def srandmember(self, name, number=None):
"""
If ``number`` is None, returns a random member of set ``name``.
If ``number`` is supplied, returns a list of ``number`` random
memebers of set ``name``. Note this is only available when running
Redis 2.6+.
"""
args = number and [number] or []
return self.execute_command('SRANDMEMBER', name, *args)
def srem(self, name, *values):
"Remove ``values`` from set ``name``"
return self.execute_command('SREM', name, *values)
def sunion(self, keys, *args):
"Return the union of sets specified by ``keys``"
args = list_or_args(keys, args)
return self.execute_command('SUNION', *args)
def sunionstore(self, dest, keys, *args):
"""
Store the union of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return self.execute_command('SUNIONSTORE', dest, *args)
# SORTED SET COMMANDS
def zadd(self, name, *args, **kwargs):
"""
Set any number of score, element-name pairs to the key ``name``. Pairs
can be specified in two ways:
As *args, in the form of: score1, name1, score2, name2, ...
or as **kwargs, in the form of: name1=score1, name2=score2, ...
The following example would add four values to the 'my-key' key:
redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
"""
pieces = []
if args:
if len(args) % 2 != 0:
raise RedisError("ZADD requires an equal number of "
"values and scores")
pieces.extend(args)
for pair in iteritems(kwargs):
pieces.append(pair[1])
pieces.append(pair[0])
return self.execute_command('ZADD', name, *pieces)
def zcard(self, name):
"Return the number of elements in the sorted set ``name``"
return self.execute_command('ZCARD', name)
def zcount(self, name, min, max):
"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``min`` and ``max``.
"""
return self.execute_command('ZCOUNT', name, min, max)
def zincrby(self, name, value, amount=1):
"Increment the score of ``value`` in sorted set ``name`` by ``amount``"
return self.execute_command('ZINCRBY', name, amount, value)
def zinterstore(self, dest, keys, aggregate=None):
"""
Intersect multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)
def zlexcount(self, name, min, max):
"""
Return the number of items in the sorted set ``name`` between the
lexicographical range ``min`` and ``max``.
"""
return self.execute_command('ZLEXCOUNT', name, min, max)
def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of the range.
``desc`` a boolean indicating whether to sort the results descendingly
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
``score_cast_func`` a callable used to cast the score return value
"""
if desc:
return self.zrevrange(name, start, end, withscores,
score_cast_func)
pieces = ['ZRANGE', name, start, end]
if withscores:
pieces.append(Token('WITHSCORES'))
options = {
'withscores': withscores,
'score_cast_func': score_cast_func
}
return self.execute_command(*pieces, **options)
def zrangebylex(self, name, min, max, start=None, num=None):
"""
Return the lexicographical range of values from sorted set ``name``
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = ['ZRANGEBYLEX', name, min, max]
if start is not None and num is not None:
pieces.extend([Token('LIMIT'), start, num])
return self.execute_command(*pieces)
def zrangebyscore(self, name, min, max, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Return a range of values from the sorted set ``name`` with scores
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice
of the range.
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
`score_cast_func`` a callable used to cast the score return value
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = ['ZRANGEBYSCORE', name, min, max]
if start is not None and num is not None:
pieces.extend([Token('LIMIT'), start, num])
if withscores:
pieces.append(Token('WITHSCORES'))
options = {
'withscores': withscores,
'score_cast_func': score_cast_func
}
return self.execute_command(*pieces, **options)
def zrank(self, name, value):
"""
Returns a 0-based value indicating the rank of ``value`` in sorted set
``name``
"""
return self.execute_command('ZRANK', name, value)
def zrem(self, name, *values):
"Remove member ``values`` from sorted set ``name``"
return self.execute_command('ZREM', name, *values)
def zremrangebylex(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` between the
lexicographical range specified by ``min`` and ``max``.
Returns the number of elements removed.
"""
return self.execute_command('ZREMRANGEBYLEX', name, min, max)
def zremrangebyrank(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with ranks between
``min`` and ``max``. Values are 0-based, ordered from smallest score
to largest. Values can be negative indicating the highest scores.
Returns the number of elements removed
"""
return self.execute_command('ZREMRANGEBYRANK', name, min, max)
def zremrangebyscore(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with scores
between ``min`` and ``max``. Returns the number of elements removed.
"""
return self.execute_command('ZREMRANGEBYSCORE', name, min, max)
def zrevrange(self, name, start, end, withscores=False,
score_cast_func=float):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in descending order.
``start`` and ``end`` can be negative, indicating the end of the range.
``withscores`` indicates to return the scores along with the values
The return type is a list of (value, score) pairs
``score_cast_func`` a callable used to cast the score return value
"""
pieces = ['ZREVRANGE', name, start, end]
if withscores:
pieces.append(Token('WITHSCORES'))
options = {
'withscores': withscores,
'score_cast_func': score_cast_func
}
return self.execute_command(*pieces, **options)
def zrevrangebyscore(self, name, max, min, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Return a range of values from the sorted set ``name`` with scores
between ``min`` and ``max`` in descending order.
If ``start`` and ``num`` are specified, then return a slice
of the range.
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
``score_cast_func`` a callable used to cast the score return value
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = ['ZREVRANGEBYSCORE', name, max, min]
if start is not None and num is not None:
pieces.extend([Token('LIMIT'), start, num])
if withscores:
pieces.append(Token('WITHSCORES'))
options = {
'withscores': withscores,
'score_cast_func': score_cast_func
}
return self.execute_command(*pieces, **options)
def zrevrank(self, name, value):
"""
Returns a 0-based value indicating the descending rank of
``value`` in sorted set ``name``
"""
return self.execute_command('ZREVRANK', name, value)
def zscore(self, name, value):
"Return the score of element ``value`` in sorted set ``name``"
return self.execute_command('ZSCORE', name, value)
def zunionstore(self, dest, keys, aggregate=None):
"""
Union multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
def _zaggregate(self, command, dest, keys, aggregate=None):
pieces = [command, dest, len(keys)]
if isinstance(keys, dict):
keys, weights = iterkeys(keys), itervalues(keys)
else:
weights = None
pieces.extend(keys)
if weights:
pieces.append(Token('WEIGHTS'))
pieces.extend(weights)
if aggregate:
pieces.append(Token('AGGREGATE'))
pieces.append(aggregate)
return self.execute_command(*pieces)
# HYPERLOGLOG COMMANDS
def pfadd(self, name, *values):
"Adds the specified elements to the specified HyperLogLog."
return self.execute_command('PFADD', name, *values)
def pfcount(self, name):
"""
Return the approximated cardinality of
the set observed by the HyperLogLog at key.
"""
return self.execute_command('PFCOUNT', name)
def pfmerge(self, dest, *sources):
"Merge N different HyperLogLogs into a single one."
return self.execute_command('PFMERGE', dest, *sources)
# HASH COMMANDS
def hdel(self, name, *keys):
"Delete ``keys`` from hash ``name``"
return self.execute_command('HDEL', name, *keys)
def hexists(self, name, key):
"Returns a boolean indicating if ``key`` exists within hash ``name``"
return self.execute_command('HEXISTS', name, key)
def hget(self, name, key):
"Return the value of ``key`` within the hash ``name``"
return self.execute_command('HGET', name, key)
def hgetall(self, name):
"Return a Python dict of the hash's name/value pairs"
return self.execute_command('HGETALL', name)
def hincrby(self, name, key, amount=1):
"Increment the value of ``key`` in hash ``name`` by ``amount``"
return self.execute_command('HINCRBY', name, key, amount)
def hincrbyfloat(self, name, key, amount=1.0):
"""
Increment the value of ``key`` in hash ``name`` by floating ``amount``
"""
return self.execute_command('HINCRBYFLOAT', name, key, amount)
def hkeys(self, name):
"Return the list of keys within hash ``name``"
return self.execute_command('HKEYS', name)
def hlen(self, name):
"Return the number of elements in hash ``name``"
return self.execute_command('HLEN', name)
def hset(self, name, key, value):
"""
Set ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return self.execute_command('HSET', name, key, value)
def hsetnx(self, name, key, value):
"""
Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0.
"""
return self.execute_command('HSETNX', name, key, value)
def hmset(self, name, mapping):
"""
Set key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
for pair in iteritems(mapping):
items.extend(pair)
return self.execute_command('HMSET', name, *items)
def hmget(self, name, keys, *args):
"Returns a list of values ordered identically to ``keys``"
args = list_or_args(keys, args)
return self.execute_command('HMGET', name, *args)
def hvals(self, name):
"Return the list of values within hash ``name``"
return self.execute_command('HVALS', name)
def publish(self, channel, message):
"""
Publish ``message`` on ``channel``.
Returns the number of subscribers the message was delivered to.
"""
return self.execute_command('PUBLISH', channel, message)
def eval(self, script, numkeys, *keys_and_args):
"""
Execute the Lua ``script``, specifying the ``numkeys`` the script
will touch and the key names and argument values in ``keys_and_args``.
Returns the result of the script.
In practice, use the object returned by ``register_script``. This
function exists purely for Redis API completion.
"""
return self.execute_command('EVAL', script, numkeys, *keys_and_args)
def evalsha(self, sha, numkeys, *keys_and_args):
"""
Use the ``sha`` to execute a Lua script already registered via EVAL
or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
key names and argument values in ``keys_and_args``. Returns the result
of the script.
In practice, use the object returned by ``register_script``. This
function exists purely for Redis API completion.
"""
return self.execute_command('EVALSHA', sha, numkeys, *keys_and_args)
def script_exists(self, *args):
"""
Check if a script exists in the script cache by specifying the SHAs of
each script as ``args``. Returns a list of boolean values indicating if
if each already script exists in the cache.
"""
return self.execute_command('SCRIPT EXISTS', *args)
def script_flush(self):
"Flush all scripts from the script cache"
return self.execute_command('SCRIPT FLUSH')
def script_kill(self):
"Kill the currently executing Lua script"
return self.execute_command('SCRIPT KILL')
def script_load(self, script):
"Load a Lua ``script`` into the script cache. Returns the SHA."
return self.execute_command('SCRIPT LOAD', script)
def register_script(self, script):
"""
Register a Lua ``script`` specifying the ``keys`` it will touch.
Returns a Script object that is callable and hides the complexity of
deal with scripts, keys, and shas. This is the preferred way to work
with Lua scripts.
"""
return Script(self, script)
class Redis(StrictRedis):
"""
Provides backwards compatibility with older versions of redis-py that
changed arguments to some commands to be more Pythonic, sane, or by
accident.
"""
# Overridden callbacks
RESPONSE_CALLBACKS = dict_merge(
StrictRedis.RESPONSE_CALLBACKS,
{
'TTL': lambda r: r >= 0 and r or None,
'PTTL': lambda r: r >= 0 and r or None,
}
)
def pipeline(self, transaction=True, shard_hint=None):
"""
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are useful for reducing the back-and-forth overhead
between the client and server.
"""
return Pipeline(
self.connection_pool,
self.response_callbacks,
transaction,
shard_hint)
def setex(self, name, value, time):
"""
Set the value of key ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return self.execute_command('SETEX', name, time, value)
def lrem(self, name, value, num=0):
"""
Remove the first ``num`` occurrences of elements equal to ``value``
from the list stored at ``name``.
The ``num`` argument influences the operation in the following ways:
num > 0: Remove elements equal to value moving from head to tail.
num < 0: Remove elements equal to value moving from tail to head.
num = 0: Remove all elements equal to value.
"""
return self.execute_command('LREM', name, num, value)
def zadd(self, name, *args, **kwargs):
"""
NOTE: The order of arguments differs from that of the official ZADD
command. For backwards compatability, this method accepts arguments
in the form of name1, score1, name2, score2, while the official Redis
documents expects score1, name1, score2, name2.
If you're looking to use the standard syntax, consider using the
StrictRedis class. See the API Reference section of the docs for more
information.
Set any number of element-name, score pairs to the key ``name``. Pairs
can be specified in two ways:
As *args, in the form of: name1, score1, name2, score2, ...
or as **kwargs, in the form of: name1=score1, name2=score2, ...
The following example would add four values to the 'my-key' key:
redis.zadd('my-key', 'name1', 1.1, 'name2', 2.2, name3=3.3, name4=4.4)
"""
pieces = []
if args:
if len(args) % 2 != 0:
raise RedisError("ZADD requires an equal number of "
"values and scores")
pieces.extend(reversed(args))
for pair in iteritems(kwargs):
pieces.append(pair[1])
pieces.append(pair[0])
return self.execute_command('ZADD', name, *pieces)
class PubSub(object):
"""
PubSub provides publish, subscribe and listen support to Redis channels.
After subscribing to one or more channels, the listen() method will block
until a message arrives on one of the subscribed channels. That message
will be returned and it's safe to start listening again.
"""
PUBLISH_MESSAGE_TYPES = ('message', 'pmessage')
UNSUBSCRIBE_MESSAGE_TYPES = ('unsubscribe', 'punsubscribe')
def __init__(self, connection_pool, shard_hint=None,
ignore_subscribe_messages=False):
self.connection_pool = connection_pool
self.shard_hint = shard_hint
self.ignore_subscribe_messages = ignore_subscribe_messages
self.connection = None
# we need to know the encoding options for this connection in order
# to lookup channel and pattern names for callback handlers.
conn = connection_pool.get_connection('pubsub', shard_hint)
try:
self.encoding = conn.encoding
self.encoding_errors = conn.encoding_errors
self.decode_responses = conn.decode_responses
finally:
connection_pool.release(conn)
self.reset()
def __del__(self):
try:
# if this object went out of scope prior to shutting down
# subscriptions, close the connection manually before
# returning it to the connection pool
self.reset()
except Exception:
pass
def reset(self):
if self.connection:
self.connection.disconnect()
self.connection.clear_connect_callbacks()
self.connection_pool.release(self.connection)
self.connection = None
self.channels = {}
self.patterns = {}
def close(self):
self.reset()
def on_connect(self, connection):
"Re-subscribe to any channels and patterns previously subscribed to"
# NOTE: for python3, we can't pass bytestrings as keyword arguments
# so we need to decode channel/pattern names back to unicode strings
# before passing them to [p]subscribe.
if self.channels:
channels = {}
for k, v in iteritems(self.channels):
if not self.decode_responses:
k = k.decode(self.encoding, self.encoding_errors)
channels[k] = v
self.subscribe(**channels)
if self.patterns:
patterns = {}
for k, v in iteritems(self.patterns):
if not self.decode_responses:
k = k.decode(self.encoding, self.encoding_errors)
patterns[k] = v
self.psubscribe(**patterns)
def encode(self, value):
"""
Encode the value so that it's identical to what we'll
read off the connection
"""
if self.decode_responses and isinstance(value, bytes):
value = value.decode(self.encoding, self.encoding_errors)
elif not self.decode_responses and isinstance(value, unicode):
value = value.encode(self.encoding, self.encoding_errors)
return value
@property
def subscribed(self):
"Indicates if there are subscriptions to any channels or patterns"
return bool(self.channels or self.patterns)
def execute_command(self, *args, **kwargs):
"Execute a publish/subscribe command"
# NOTE: don't parse the response in this function. it could pull a
# legitmate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
self.connection = self.connection_pool.get_connection(
'pubsub',
self.shard_hint
)
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
connection = self.connection
self._execute(connection, connection.send_command, *args)
def _execute(self, connection, command, *args):
try:
return command(*args)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
# Connect manually here. If the Redis server is down, this will
# fail and raise a ConnectionError as desired.
connection.connect()
# the ``on_connect`` callback should haven been called by the
# connection to resubscribe us to any channels and patterns we were
# previously listening to
return command(*args)
def parse_response(self, block=True):
"Parse the response from a publish/subscribe command"
connection = self.connection
if not block and not connection.can_read():
return None
return self._execute(connection, connection.read_response)
def psubscribe(self, *args, **kwargs):
"""
Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_patterns = {}
new_patterns.update(dict.fromkeys(imap(self.encode, args)))
for pattern, handler in iteritems(kwargs):
new_patterns[self.encode(pattern)] = handler
ret_val = self.execute_command('PSUBSCRIBE', *iterkeys(new_patterns))
# update the patterns dict AFTER we send the command. we don't want to
# subscribe twice to these patterns, once for the command and again
# for the reconnection.
self.patterns.update(new_patterns)
return ret_val
def punsubscribe(self, *args):
"""
Unsubscribe from the supplied patterns. If empy, unsubscribe from
all patterns.
"""
if args:
args = list_or_args(args[0], args[1:])
return self.execute_command('PUNSUBSCRIBE', *args)
def subscribe(self, *args, **kwargs):
"""
Subscribe to channels. Channels supplied as keyword arguments expect
a channel name as the key and a callable as the value. A channel's
callable will be invoked automatically when a message is received on
that channel rather than producing a message via ``listen()`` or
``get_message()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_channels = {}
new_channels.update(dict.fromkeys(imap(self.encode, args)))
for channel, handler in iteritems(kwargs):
new_channels[self.encode(channel)] = handler
ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
# update the channels dict AFTER we send the command. we don't want to
# subscribe twice to these channels, once for the command and again
# for the reconnection.
self.channels.update(new_channels)
return ret_val
def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
"""
if args:
args = list_or_args(args[0], args[1:])
return self.execute_command('UNSUBSCRIBE', *args)
def listen(self):
"Listen for messages on channels this client has been subscribed to"
while self.subscribed:
response = self.handle_message(self.parse_response(block=True))
if response is not None:
yield response
def get_message(self, ignore_subscribe_messages=False):
"Get the next message if one is available, otherwise None"
response = self.parse_response(block=False)
if response:
return self.handle_message(response, ignore_subscribe_messages)
return None
def handle_message(self, response, ignore_subscribe_messages=False):
"""
Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned.
"""
message_type = nativestr(response[0])
if message_type == 'pmessage':
message = {
'type': message_type,
'pattern': response[1],
'channel': response[2],
'data': response[3]
}
else:
message = {
'type': message_type,
'pattern': None,
'channel': response[1],
'data': response[2]
}
# if this is an unsubscribe message, remove it from memory
if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
subscribed_dict = None
if message_type == 'punsubscribe':
subscribed_dict = self.patterns
else:
subscribed_dict = self.channels
try:
del subscribed_dict[message['channel']]
except KeyError:
pass
if message_type in self.PUBLISH_MESSAGE_TYPES:
# if there's a message handler, invoke it
handler = None
if message_type == 'pmessage':
handler = self.patterns.get(message['pattern'], None)
else:
handler = self.channels.get(message['channel'], None)
if handler:
handler(message)
return None
else:
# this is a subscribe/unsubscribe message. ignore if we don't
# want them
if ignore_subscribe_messages or self.ignore_subscribe_messages:
return None
return message
def run_in_thread(self, sleep_time=0):
for channel, handler in iteritems(self.channels):
if handler is None:
raise PubSubError("Channel: '%s' has no handler registered")
for pattern, handler in iteritems(self.patterns):
if handler is None:
raise PubSubError("Pattern: '%s' has no handler registered")
pubsub = self
class WorkerThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(WorkerThread, self).__init__(*args, **kwargs)
self._running = False
def run(self):
if self._running:
return
self._running = True
while self._running and pubsub.subscribed:
pubsub.get_message(ignore_subscribe_messages=True)
mod_time.sleep(sleep_time)
def stop(self):
self._running = False
self.join()
thread = WorkerThread()
thread.start()
return thread
class BasePipeline(object):
"""
Pipelines provide a way to transmit multiple commands to the Redis server
in one transmission. This is convenient for batch processing, such as
saving all the values in a list to Redis.
All commands executed within a pipeline are wrapped with MULTI and EXEC
calls. This guarantees all commands executed in the pipeline will be
executed atomically.
Any command raising an exception does *not* halt the execution of
subsequent commands in the pipeline. Instead, the exception is caught
and its instance is placed into the response list returned by execute().
Code iterating over the response list should be able to deal with an
instance of an exception as a potential value. In general, these will be
ResponseError exceptions, such as those raised when issuing a command
on a key of a different datatype.
"""
UNWATCH_COMMANDS = set(('DISCARD', 'EXEC', 'UNWATCH'))
def __init__(self, connection_pool, response_callbacks, transaction,
shard_hint):
self.connection_pool = connection_pool
self.connection = None
self.response_callbacks = response_callbacks
self.transaction = transaction
self.shard_hint = shard_hint
self.watching = False
self.reset()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.reset()
def __del__(self):
try:
self.reset()
except Exception:
pass
def __len__(self):
return len(self.command_stack)
def reset(self):
self.command_stack = []
self.scripts = set()
# make sure to reset the connection state in the event that we were
# watching something
if self.watching and self.connection:
try:
# call this manually since our unwatch or
# immediate_execute_command methods can call reset()
self.connection.send_command('UNWATCH')
self.connection.read_response()
except ConnectionError:
# disconnect will also remove any previous WATCHes
self.connection.disconnect()
# clean up the other instance attributes
self.watching = False
self.explicit_transaction = False
# we can safely return the connection to the pool here since we're
# sure we're no longer WATCHing anything
if self.connection:
self.connection_pool.release(self.connection)
self.connection = None
def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
if self.explicit_transaction:
raise RedisError('Cannot issue nested calls to MULTI')
if self.command_stack:
raise RedisError('Commands without an initial WATCH have already '
'been issued')
self.explicit_transaction = True
def execute_command(self, *args, **kwargs):
if (self.watching or args[0] == 'WATCH') and \
not self.explicit_transaction:
return self.immediate_execute_command(*args, **kwargs)
return self.pipeline_execute_command(*args, **kwargs)
def immediate_execute_command(self, *args, **options):
"""
Execute a command immediately, but don't auto-retry on a
ConnectionError if we're already WATCHing a variable. Used when
issuing WATCH or subsequent commands retrieving their values but before
MULTI is called.
"""
command_name = args[0]
conn = self.connection
# if this is the first call, we need a connection
if not conn:
conn = self.connection_pool.get_connection(command_name,
self.shard_hint)
self.connection = conn
try:
conn.send_command(*args)
return self.parse_response(conn, command_name, **options)
except (ConnectionError, TimeoutError) as e:
conn.disconnect()
if not conn.retry_on_timeout and isinstance(e, TimeoutError):
raise
# if we're not already watching, we can safely retry the command
try:
if not self.watching:
conn.send_command(*args)
return self.parse_response(conn, command_name, **options)
except ConnectionError:
# the retry failed so cleanup.
conn.disconnect()
self.reset()
raise
def pipeline_execute_command(self, *args, **options):
"""
Stage a command to be executed when execute() is next called
Returns the current Pipeline object back so commands can be
chained together, such as:
pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
At some other point, you can then run: pipe.execute(),
which will execute all commands queued in the pipe.
"""
self.command_stack.append((args, options))
return self
def _execute_transaction(self, connection, commands, raise_on_error):
cmds = chain([(('MULTI', ), {})], commands, [(('EXEC', ), {})])
all_cmds = connection.pack_commands([args for args, _ in cmds])
connection.send_packed_command(all_cmds)
errors = []
# parse off the response for MULTI
# NOTE: we need to handle ResponseErrors here and continue
# so that we read all the additional command messages from
# the socket
try:
self.parse_response(connection, '_')
except ResponseError:
errors.append((0, sys.exc_info()[1]))
# and all the other commands
for i, command in enumerate(commands):
try:
self.parse_response(connection, '_')
except ResponseError:
ex = sys.exc_info()[1]
self.annotate_exception(ex, i + 1, command[0])
errors.append((i, ex))
# parse the EXEC.
try:
response = self.parse_response(connection, '_')
except ExecAbortError:
if self.explicit_transaction:
self.immediate_execute_command('DISCARD')
if errors:
raise errors[0][1]
raise sys.exc_info()[1]
if response is None:
raise WatchError("Watched variable changed.")
# put any parse errors into the response
for i, e in errors:
response.insert(i, e)
if len(response) != len(commands):
self.connection.disconnect()
raise ResponseError("Wrong number of response items from "
"pipeline execution")
# find any errors in the response and raise if necessary
if raise_on_error:
self.raise_first_error(commands, response)
# We have to run response callbacks manually
data = []
for r, cmd in izip(response, commands):
if not isinstance(r, Exception):
args, options = cmd
command_name = args[0]
if command_name in self.response_callbacks:
r = self.response_callbacks[command_name](r, **options)
data.append(r)
return data
def _execute_pipeline(self, connection, commands, raise_on_error):
# build up all commands into a single request to increase network perf
all_cmds = connection.pack_commands([args for args, _ in commands])
connection.send_packed_command(all_cmds)
response = []
for args, options in commands:
try:
response.append(
self.parse_response(connection, args[0], **options))
except ResponseError:
response.append(sys.exc_info()[1])
if raise_on_error:
self.raise_first_error(commands, response)
return response
def raise_first_error(self, commands, response):
for i, r in enumerate(response):
if isinstance(r, ResponseError):
self.annotate_exception(r, i + 1, commands[i][0])
raise r
def annotate_exception(self, exception, number, command):
cmd = unicode(' ').join(imap(unicode, command))
msg = unicode('Command # %d (%s) of pipeline caused error: %s') % (
number, cmd, unicode(exception.args[0]))
exception.args = (msg,) + exception.args[1:]
def parse_response(self, connection, command_name, **options):
result = StrictRedis.parse_response(
self, connection, command_name, **options)
if command_name in self.UNWATCH_COMMANDS:
self.watching = False
elif command_name == 'WATCH':
self.watching = True
return result
def load_scripts(self):
# make sure all scripts that are about to be run on this pipeline exist
scripts = list(self.scripts)
immediate = self.immediate_execute_command
shas = [s.sha for s in scripts]
# we can't use the normal script_* methods because they would just
# get buffered in the pipeline.
exists = immediate('SCRIPT', 'EXISTS', *shas, **{'parse': 'EXISTS'})
if not all(exists):
for s, exist in izip(scripts, exists):
if not exist:
s.sha = immediate('SCRIPT', 'LOAD', s.script,
**{'parse': 'LOAD'})
def execute(self, raise_on_error=True):
"Execute all the commands in the current pipeline"
stack = self.command_stack
if not stack:
return []
if self.scripts:
self.load_scripts()
if self.transaction or self.explicit_transaction:
execute = self._execute_transaction
else:
execute = self._execute_pipeline
conn = self.connection
if not conn:
conn = self.connection_pool.get_connection('MULTI',
self.shard_hint)
# assign to self.connection so reset() releases the connection
# back to the pool after we're done
self.connection = conn
try:
return execute(conn, stack, raise_on_error)
except (ConnectionError, TimeoutError) as e:
conn.disconnect()
if not conn.retry_on_timeout and isinstance(e, TimeoutError):
raise
# if we were watching a variable, the watch is no longer valid
# since this connection has died. raise a WatchError, which
# indicates the user should retry his transaction. If this is more
# than a temporary failure, the WATCH that the user next issues
# will fail, propegating the real ConnectionError
if self.watching:
raise WatchError("A ConnectionError occured on while watching "
"one or more keys")
# otherwise, it's safe to retry since the transaction isn't
# predicated on any state
return execute(conn, stack, raise_on_error)
finally:
self.reset()
def watch(self, *names):
"Watches the values at keys ``names``"
if self.explicit_transaction:
raise RedisError('Cannot issue a WATCH after a MULTI')
return self.execute_command('WATCH', *names)
def unwatch(self):
"Unwatches all previously specified keys"
return self.watching and self.execute_command('UNWATCH') or True
def script_load_for_pipeline(self, script):
"Make sure scripts are loaded prior to pipeline execution"
# we need the sha now so that Script.__call__ can use it to run
# evalsha.
if not script.sha:
script.sha = self.immediate_execute_command('SCRIPT', 'LOAD',
script.script,
**{'parse': 'LOAD'})
self.scripts.add(script)
class StrictPipeline(BasePipeline, StrictRedis):
"Pipeline for the StrictRedis class"
pass
class Pipeline(BasePipeline, Redis):
"Pipeline for the Redis class"
pass
class Script(object):
"An executable Lua script object returned by ``register_script``"
def __init__(self, registered_client, script):
self.registered_client = registered_client
self.script = script
self.sha = ''
def __call__(self, keys=[], args=[], client=None):
"Execute the script, passing any required ``args``"
if client is None:
client = self.registered_client
args = tuple(keys) + tuple(args)
# make sure the Redis server knows about the script
if isinstance(client, BasePipeline):
# make sure this script is good to go on pipeline
client.script_load_for_pipeline(self)
try:
return client.evalsha(self.sha, len(keys), *args)
except NoScriptError:
# Maybe the client is pointed to a differnet server than the client
# that created this instance?
self.sha = client.script_load(self.script)
return client.evalsha(self.sha, len(keys), *args)
| gpl-2.0 |
kennethlove/django | django/middleware/common.py | 14 | 6780 | import hashlib
import re
from django.conf import settings
from django import http
from django.core.mail import mail_managers
from django.utils.http import urlquote
from django.core import urlresolvers
from django.utils.log import getLogger
logger = getLogger('django.request')
class CommonMiddleware(object):
"""
"Common" middleware for taking care of some basic operations:
- Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS
- URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
this middleware appends missing slashes and/or prepends missing
"www."s.
- If APPEND_SLASH is set and the initial URL doesn't end with a
slash, and it is not found in urlpatterns, a new URL is formed by
appending a slash at the end. If this new URL is found in
urlpatterns, then an HTTP-redirect is returned to this new URL;
otherwise the initial URL is processed as usual.
- ETags: If the USE_ETAGS setting is set, ETags will be calculated from
the entire page content and Not Modified responses will be returned
appropriately.
"""
def process_request(self, request):
"""
Check for denied User-Agents and rewrite the URL based on
settings.APPEND_SLASH and settings.PREPEND_WWW
"""
# Check for denied User-Agents
if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
logger.warning('Forbidden (User agent): %s', request.path,
extra={
'status_code': 403,
'request': request
}
)
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
# Check for a redirect based on settings.APPEND_SLASH
# and settings.PREPEND_WWW
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.PREPEND_WWW and old_url[0] and
not old_url[0].startswith('www.')):
new_url[0] = 'www.' + old_url[0]
# Append a slash if APPEND_SLASH is set and the URL doesn't have a
# trailing slash and there is no pattern for the current path
if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
urlconf = getattr(request, 'urlconf', None)
if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST':
raise RuntimeError((""
"You called this URL via POST, but the URL doesn't end "
"in a slash and you have APPEND_SLASH set. Django can't "
"redirect to the slash URL while maintaining POST data. "
"Change your form to point to %s%s (note the trailing "
"slash), or set APPEND_SLASH=False in your Django "
"settings.") % (new_url[0], new_url[1]))
if new_url == old_url:
# No redirects required.
return
if new_url[0]:
newurl = "%s://%s%s" % (
request.is_secure() and 'https' or 'http',
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.META.get('QUERY_STRING', ''):
newurl += '?' + request.META['QUERY_STRING']
return http.HttpResponsePermanentRedirect(newurl)
def process_response(self, request, response):
"Send broken link emails and calculate the Etag, if needed."
if response.status_code == 404:
if settings.SEND_BROKEN_LINK_EMAILS and not settings.DEBUG:
# If the referrer was from an internal link or a non-search-engine site,
# send a note to the managers.
domain = request.get_host()
referer = request.META.get('HTTP_REFERER', None)
is_internal = _is_internal_request(domain, referer)
path = request.get_full_path()
if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer):
ua = request.META.get('HTTP_USER_AGENT', '<none>')
ip = request.META.get('REMOTE_ADDR', '<none>')
mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain),
"Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \
% (referer, request.get_full_path(), ua, ip),
fail_silently=True)
return response
# Use ETags, if requested.
if settings.USE_ETAGS:
if response.has_header('ETag'):
etag = response['ETag']
else:
etag = '"%s"' % hashlib.md5(response.content).hexdigest()
if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag:
cookies = response.cookies
response = http.HttpResponseNotModified()
response.cookies = cookies
else:
response['ETag'] = etag
return response
def _is_ignorable_404(uri):
"""
Returns True if a 404 at the given URL *shouldn't* notify the site managers.
"""
if getattr(settings, 'IGNORABLE_404_STARTS', ()):
import warnings
warnings.warn('The IGNORABLE_404_STARTS setting has been deprecated '
'in favor of IGNORABLE_404_URLS.', DeprecationWarning)
for start in settings.IGNORABLE_404_STARTS:
if uri.startswith(start):
return True
if getattr(settings, 'IGNORABLE_404_ENDS', ()):
import warnings
warnings.warn('The IGNORABLE_404_ENDS setting has been deprecated '
'in favor of IGNORABLE_404_URLS.', DeprecationWarning)
for end in settings.IGNORABLE_404_ENDS:
if uri.endswith(end):
return True
return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS)
def _is_internal_request(domain, referer):
"""
Returns true if the referring URL is the same domain as the current request.
"""
# Different subdomains are treated as different domains.
return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer)
| bsd-3-clause |
scylladb/scylla-cluster-tests | sdcm/cluster_aws.py | 1 | 53645 | # 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 LICENSE for more details.
#
# Copyright (c) 2020 ScyllaDB
# pylint: disable=too-many-lines, too-many-public-methods
import os
import re
import json
import time
import uuid
import base64
import random
import logging
import tempfile
from math import floor
from typing import Dict, Optional
from datetime import datetime
from textwrap import dedent
from functools import cached_property
from contextlib import ExitStack
import yaml
import boto3
from mypy_boto3_ec2 import EC2Client
from pkg_resources import parse_version
from botocore.exceptions import WaiterError
from sdcm import ec2_client, cluster
from sdcm.remote import LocalCmdRunner, shell_script_cmd, NETWORK_EXCEPTIONS
from sdcm.ec2_client import CreateSpotInstancesError
from sdcm.utils.aws_utils import tags_as_ec2_tags, ec2_instance_wait_public_ip
from sdcm.utils.common import list_instances_aws, get_ami_tags, MAX_SPOT_DURATION_TIME
from sdcm.utils.decorators import retrying
from sdcm.sct_events.system import SpotTerminationEvent
from sdcm.sct_events.filters import DbEventsFilter
from sdcm.sct_events.database import DatabaseLogEvent
from sdcm.test_config import TestConfig
LOGGER = logging.getLogger(__name__)
INSTANCE_PROVISION_ON_DEMAND = 'on_demand'
INSTANCE_PROVISION_SPOT_FLEET = 'spot_fleet'
INSTANCE_PROVISION_SPOT_LOW_PRICE = 'spot_low_price'
INSTANCE_PROVISION_SPOT_DURATION = 'spot_duration'
SPOT_CNT_LIMIT = 20
SPOT_FLEET_LIMIT = 50
SPOT_TERMINATION_CHECK_OVERHEAD = 15
LOCAL_CMD_RUNNER = LocalCmdRunner()
# pylint: disable=too-many-lines
class AWSCluster(cluster.BaseCluster): # pylint: disable=too-many-instance-attributes,abstract-method,
"""
Cluster of Node objects, started on Amazon EC2.
"""
def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids, # pylint: disable=too-many-arguments
services, credentials, cluster_uuid=None,
ec2_instance_type='c5.xlarge', ec2_ami_username='root',
ec2_user_data='', ec2_block_device_mappings=None,
cluster_prefix='cluster',
node_prefix='node', n_nodes=10, params=None, node_type=None, extra_network_interface=False):
# pylint: disable=too-many-locals
region_names = params.region_names
if len(credentials) > 1 or len(region_names) > 1:
assert len(credentials) == len(region_names)
self._ec2_ami_id = ec2_ami_id
self._ec2_subnet_id = ec2_subnet_id
self._ec2_security_group_ids = ec2_security_group_ids
self._ec2_services = services
self._credentials = credentials
self._reuse_credentials = None
self._ec2_instance_type = ec2_instance_type
self._ec2_ami_username = ec2_ami_username
if ec2_block_device_mappings is None:
ec2_block_device_mappings = []
self._ec2_block_device_mappings = ec2_block_device_mappings
self._ec2_user_data = ec2_user_data
self.region_names = region_names
self.params = params
super(AWSCluster, self).__init__(cluster_uuid=cluster_uuid,
cluster_prefix=cluster_prefix,
node_prefix=node_prefix,
n_nodes=n_nodes,
params=params,
region_names=self.region_names,
node_type=node_type,
extra_network_interface=extra_network_interface
)
def __str__(self):
return 'Cluster %s (AMI: %s Type: %s)' % (self.name,
self._ec2_ami_id,
self._ec2_instance_type)
@staticmethod
def calculate_spot_duration_for_test():
return floor(TestConfig.TEST_DURATION / 60) * 60 + 60
def _create_on_demand_instances(self, count, interfaces, ec2_user_data, dc_idx=0): # pylint: disable=too-many-arguments
ami_id = self._ec2_ami_id[dc_idx]
self.log.debug(f"Creating {count} on-demand instances using AMI id '{ami_id}'... ")
params = dict(ImageId=ami_id,
UserData=ec2_user_data,
MinCount=count,
MaxCount=count,
KeyName=self._credentials[dc_idx].key_pair_name,
BlockDeviceMappings=self._ec2_block_device_mappings,
NetworkInterfaces=interfaces,
InstanceType=self._ec2_instance_type)
instance_profile = self.params.get('aws_instance_profile_name')
if instance_profile:
params['IamInstanceProfile'] = {'Name': instance_profile}
instances = self._ec2_services[dc_idx].create_instances(**params)
self.log.debug("Created instances: %s." % instances)
return instances
def _create_spot_instances(self, count, interfaces, ec2_user_data='', dc_idx=0): # pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
ec2 = ec2_client.EC2ClientWarpper(region_name=self.region_names[dc_idx],
spot_max_price_percentage=self.params.get('spot_max_price'))
subnet_info = ec2.get_subnet_info(self._ec2_subnet_id[dc_idx])
spot_params = dict(instance_type=self._ec2_instance_type,
image_id=self._ec2_ami_id[dc_idx],
region_name=subnet_info['AvailabilityZone'],
network_if=interfaces,
key_pair=self._credentials[dc_idx].key_pair_name,
user_data=ec2_user_data,
count=count,
block_device_mappings=self._ec2_block_device_mappings,
aws_instance_profile=self.params.get('aws_instance_profile_name'))
if self.instance_provision == INSTANCE_PROVISION_SPOT_DURATION:
# duration value must be a multiple of 60
spot_params.update({'duration': self.calculate_spot_duration_for_test()})
limit = SPOT_FLEET_LIMIT if self.instance_provision == INSTANCE_PROVISION_SPOT_FLEET else SPOT_CNT_LIMIT
request_cnt = 1
tail_cnt = 0
if count > limit:
request_cnt = count // limit
spot_params['count'] = limit
tail_cnt = count % limit
if tail_cnt:
request_cnt += 1
instances = []
for i in range(request_cnt):
if tail_cnt and i == request_cnt - 1:
spot_params['count'] = tail_cnt
if self.instance_provision == INSTANCE_PROVISION_SPOT_FLEET and count > 1:
instances_i = ec2.create_spot_fleet(**spot_params)
else:
instances_i = ec2.create_spot_instances(**spot_params)
instances.extend(instances_i)
return instances
def _create_instances(self, count, ec2_user_data='', dc_idx=0):
if not count: # EC2 API fails if we request zero instances.
return []
if not ec2_user_data:
ec2_user_data = self._ec2_user_data
self.log.debug("Passing user_data '%s' to create_instances", ec2_user_data)
interfaces = [{'DeviceIndex': 0,
'SubnetId': self._ec2_subnet_id[dc_idx],
'AssociatePublicIpAddress': True,
'Groups': self._ec2_security_group_ids[dc_idx]}]
if self.extra_network_interface:
interfaces = [{'DeviceIndex': 0,
'SubnetId': self._ec2_subnet_id[dc_idx],
'Groups': self._ec2_security_group_ids[dc_idx]},
{'DeviceIndex': 1,
'SubnetId': self._ec2_subnet_id[dc_idx],
'Groups': self._ec2_security_group_ids[dc_idx]}]
self.log.info(f"Create {self.instance_provision} instance(s)")
if self.instance_provision == 'mixed':
instances = self._create_mixed_instances(count, interfaces, ec2_user_data, dc_idx)
elif self.instance_provision == INSTANCE_PROVISION_ON_DEMAND:
instances = self._create_on_demand_instances(count, interfaces, ec2_user_data, dc_idx)
elif self.instance_provision == INSTANCE_PROVISION_SPOT_FLEET and count > 1:
instances = self._create_spot_instances(count, interfaces, ec2_user_data, dc_idx)
else:
instances = self.fallback_provision_type(count, interfaces, ec2_user_data, dc_idx)
return instances
def fallback_provision_type(self, count, interfaces, ec2_user_data, dc_idx):
# If user requested to use spot instances, first try to get spot_duration instances (according to test_duration)
# - if test_duration > 360 or spot_duration failed, try to get spot_low_price
# - if instance_provision_fallback_on_demand==true and previous attempts failed then create on_demand instance
# else fail the test
instances = None
if self.instance_provision.lower() == 'spot' or self.instance_provision == INSTANCE_PROVISION_SPOT_DURATION \
or (self.instance_provision == INSTANCE_PROVISION_SPOT_FLEET and count == 1):
instances_provision_fallbacks = [INSTANCE_PROVISION_SPOT_DURATION, INSTANCE_PROVISION_SPOT_LOW_PRICE]
else:
# If self.instance_provision == "spot_low_price"
instances_provision_fallbacks = [self.instance_provision]
if 'instance_provision_fallback_on_demand' in self.params \
and self.params['instance_provision_fallback_on_demand']:
instances_provision_fallbacks.append(INSTANCE_PROVISION_ON_DEMAND)
self.log.debug(f"Instances provision fallbacks : {instances_provision_fallbacks}")
for instances_provision_type in instances_provision_fallbacks:
# If original instance provision type was not spot_duration, we need to check that test duration
# not exceeds maximum allowed spot duration (360 min right for now). If it exceeds - it's impossible to
# request for spot duration provision type.
if instances_provision_type == INSTANCE_PROVISION_SPOT_DURATION and \
self.calculate_spot_duration_for_test() > MAX_SPOT_DURATION_TIME:
self.log.info(f"Create {instances_provision_type} instance(s) is not alowed: "
f"Test duration too long for spot_duration instance type. "
f"Max possible test duration time for this instance type is {MAX_SPOT_DURATION_TIME} "
f"minutes"
)
continue
try:
self.log.info(f"Create {instances_provision_type} instance(s)")
if instances_provision_type == INSTANCE_PROVISION_ON_DEMAND:
instances = self._create_on_demand_instances(count, interfaces, ec2_user_data, dc_idx)
else:
instances = self._create_spot_instances(count, interfaces, ec2_user_data, dc_idx)
break
except CreateSpotInstancesError as cl_ex:
if instances_provision_type == instances_provision_fallbacks[-1]:
raise
elif not self.check_spot_error(str(cl_ex), instances_provision_type):
raise
return instances
def check_spot_error(self, cl_ex, instance_provision):
if ec2_client.MAX_SPOT_EXCEEDED_ERROR in cl_ex or \
ec2_client.FLEET_LIMIT_EXCEEDED_ERROR in cl_ex or \
ec2_client.SPOT_CAPACITY_NOT_AVAILABLE_ERROR in cl_ex or \
ec2_client.SPOT_PRICE_TOO_LOW in cl_ex or \
ec2_client.SPOT_STATUS_UNEXPECTED_ERROR in cl_ex:
self.log.error(f"Cannot create {instance_provision} instance(s): {cl_ex}")
return True
return False
def _create_mixed_instances(self, count, interfaces, ec2_user_data, dc_idx): # pylint: disable=too-many-arguments
instances = []
max_num_on_demand = 2
if isinstance(self, (ScyllaAWSCluster, CassandraAWSCluster)):
if count > 2:
count_on_demand = max_num_on_demand
elif count == 2:
count_on_demand = 1
else:
count_on_demand = 0
if self.nodes:
num_of_on_demand = len([node for node in self.nodes if not node.is_spot])
if num_of_on_demand < max_num_on_demand:
count_on_demand = max_num_on_demand - num_of_on_demand
else:
count_on_demand = 0
count_spot = count - count_on_demand
if count_spot > 0:
self.instance_provision = INSTANCE_PROVISION_SPOT_LOW_PRICE
instances.extend(self._create_spot_instances(count_spot, interfaces, ec2_user_data, dc_idx))
if count_on_demand > 0:
self.instance_provision = INSTANCE_PROVISION_ON_DEMAND
instances.extend(self._create_on_demand_instances(count_on_demand, interfaces, ec2_user_data, dc_idx))
self.instance_provision = 'mixed'
elif isinstance(self, LoaderSetAWS):
self.instance_provision = INSTANCE_PROVISION_SPOT_LOW_PRICE
instances = self._create_spot_instances(count, interfaces, ec2_user_data, dc_idx)
elif isinstance(self, MonitorSetAWS):
self.instance_provision = INSTANCE_PROVISION_ON_DEMAND
instances.extend(self._create_on_demand_instances(count, interfaces, ec2_user_data, dc_idx))
else:
raise Exception('Unsuported type of cluster type %s' % self)
return instances
def _get_instances(self, dc_idx):
test_id = cluster.TestConfig.test_id()
if not test_id:
raise ValueError("test_id should be configured for using reuse_cluster")
ec2 = ec2_client.EC2ClientWarpper(region_name=self.region_names[dc_idx],
spot_max_price_percentage=self.params.get('spot_max_price'))
results = list_instances_aws(tags_dict={'TestId': test_id, 'NodeType': self.node_type},
region_name=self.region_names[dc_idx], group_as_region=True)
instances = results[self.region_names[dc_idx]]
def sort_by_index(item):
for tag in item['Tags']:
if tag['Key'] == 'NodeIndex':
return tag['Value']
return '0'
instances = sorted(instances, key=sort_by_index)
return [ec2.get_instance(instance['InstanceId']) for instance in instances]
@staticmethod
def update_bootstrap(ec2_user_data, enable_auto_bootstrap):
"""
Update --bootstrap argument inside ec2_user_data string.
"""
if isinstance(ec2_user_data, dict):
ec2_user_data['scylla_yaml']['auto_bootstrap'] = enable_auto_bootstrap
return ec2_user_data
if enable_auto_bootstrap:
if '--bootstrap ' in ec2_user_data:
ec2_user_data.replace('--bootstrap false', '--bootstrap true')
else:
ec2_user_data += ' --bootstrap true '
else:
if '--bootstrap ' in ec2_user_data:
ec2_user_data.replace('--bootstrap true', '--bootstrap false')
else:
ec2_user_data += ' --bootstrap false '
return ec2_user_data
# This is workaround for issue #5179: IPv6 - routing in scylla AMI isn't configured properly (when not Amazon Linux)
@staticmethod
def network_config_ipv6_workaround_script(): # pylint: disable=invalid-name
return dedent("""
if `grep -qi "ubuntu" /etc/os-release`; then
echo "On Ubuntu we don't need this workaround, so done"
else
BASE_EC2_NETWORK_URL=http://169.254.169.254/latest/meta-data/network/interfaces/macs/
MAC=`curl -s ${BASE_EC2_NETWORK_URL}`
IPv6_CIDR=`curl -s ${BASE_EC2_NETWORK_URL}${MAC}/subnet-ipv6-cidr-blocks`
grep -qi "amazon linux" /etc/os-release || sudo ip route add $IPv6_CIDR dev eth0
grep -q IPV6_AUTOCONF /etc/sysconfig/network-scripts/ifcfg-eth0
if [[ $? -eq 0 ]]; then
sudo sed -i 's/^IPV6_AUTOCONF=[^ ]*/IPV6_AUTOCONF=yes/' /etc/sysconfig/network-scripts/ifcfg-eth0
else
sudo echo "IPV6_AUTOCONF=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
fi
grep -q IPV6_DEFROUTE /etc/sysconfig/network-scripts/ifcfg-eth0
if [[ $? -eq 0 ]]; then
sudo sed -i 's/^IPV6_DEFROUTE=[^ ]*/IPV6_DEFROUTE=yes/' /etc/sysconfig/network-scripts/ifcfg-eth0
else
sudo echo "IPV6_DEFROUTE=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth0
fi
sudo systemctl restart network
fi
""")
@staticmethod
def configure_eth1_script():
return dedent("""
BASE_EC2_NETWORK_URL=http://169.254.169.254/latest/meta-data/network/interfaces/macs/
NUMBER_OF_ENI=`curl -s ${BASE_EC2_NETWORK_URL} | wc -w`
for mac in `curl -s ${BASE_EC2_NETWORK_URL}`
do
DEVICE_NUMBER=`curl -s ${BASE_EC2_NETWORK_URL}${mac}/device-number`
if [[ "$DEVICE_NUMBER" == "1" ]]; then
ETH1_MAC=${mac}
fi
done
if [[ ! "${DEVICE_NUMBER}x" == "x" ]]; then
ETH1_IP_ADDRESS=`curl -s ${BASE_EC2_NETWORK_URL}${ETH1_MAC}/local-ipv4s`
ETH1_CIDR_BLOCK=`curl -s ${BASE_EC2_NETWORK_URL}${ETH1_MAC}/subnet-ipv4-cidr-block`
fi
sudo bash -c "echo 'GATEWAYDEV=eth0' >> /etc/sysconfig/network"
echo "
DEVICE="eth1"
BOOTPROTO="dhcp"
ONBOOT="yes"
TYPE="Ethernet"
USERCTL="yes"
PEERDNS="yes"
IPV6INIT="no"
PERSISTENT_DHCLIENT="1"
" > /etc/sysconfig/network-scripts/ifcfg-eth1
echo "
default via 10.0.0.1 dev eth1 table 2
${ETH1_CIDR_BLOCK} dev eth1 src ${ETH1_IP_ADDRESS} table 2
" > /etc/sysconfig/network-scripts/route-eth1
echo "
from ${ETH1_IP_ADDRESS}/32 table 2
" > /etc/sysconfig/network-scripts/rule-eth1
sudo systemctl restart network
""")
def add_nodes(self, count, ec2_user_data='', dc_idx=0, rack=0, enable_auto_bootstrap=False):
post_boot_script = cluster.TestConfig.get_startup_script()
if self.extra_network_interface:
post_boot_script += self.configure_eth1_script()
if self.params.get('ip_ssh_connections') == 'ipv6':
post_boot_script += self.network_config_ipv6_workaround_script()
if isinstance(ec2_user_data, dict):
ec2_user_data['post_configuration_script'] = base64.b64encode(
post_boot_script.encode('utf-8')).decode('ascii')
ec2_user_data = json.dumps(ec2_user_data)
else:
if 'clustername' in ec2_user_data:
ec2_user_data += " --base64postscript={0}".format(
base64.b64encode(post_boot_script.encode('utf-8')).decode('ascii'))
else:
ec2_user_data = post_boot_script
if cluster.TestConfig.REUSE_CLUSTER:
instances = self._get_instances(dc_idx)
else:
instances = self._create_instances(count, ec2_user_data, dc_idx)
added_nodes = [self._create_node(instance, self._ec2_ami_username,
self.node_prefix, node_index,
self.logdir, dc_idx=dc_idx)
for node_index, instance in
enumerate(instances, start=self._node_index + 1)]
for node in added_nodes:
node.enable_auto_bootstrap = enable_auto_bootstrap
if self.params.get('ip_ssh_connections') == 'ipv6' and not node.distro.is_amazon2 and \
not node.distro.is_ubuntu:
node.config_ipv6_as_persistent()
self._node_index += len(added_nodes)
self.nodes += added_nodes
self.write_node_public_ip_file()
self.write_node_private_ip_file()
return added_nodes
def _create_node(self, instance, ami_username, node_prefix, node_index, # pylint: disable=too-many-arguments
base_logdir, dc_idx):
node = AWSNode(ec2_instance=instance, ec2_service=self._ec2_services[dc_idx],
credentials=self._credentials[dc_idx], parent_cluster=self, ami_username=ami_username,
node_prefix=node_prefix, node_index=node_index,
base_logdir=base_logdir, dc_idx=dc_idx)
node.init()
return node
class AWSNode(cluster.BaseNode):
"""
Wraps EC2.Instance, so that we can also control the instance through SSH.
"""
log = LOGGER
def __init__(self, ec2_instance, ec2_service, credentials, parent_cluster, # pylint: disable=too-many-arguments
node_prefix='node', node_index=1, ami_username='root',
base_logdir=None, dc_idx=0):
self.node_index = node_index
self._instance = ec2_instance
self._ec2_service = ec2_service
self._eth1_private_ip_address = None
self.eip_allocation_id = None
ssh_login_info = {'hostname': None,
'user': ami_username,
'key_file': credentials.key_file}
super(AWSNode, self).__init__(name=f"{node_prefix}-{self.node_index}",
parent_cluster=parent_cluster,
ssh_login_info=ssh_login_info,
base_logdir=base_logdir,
node_prefix=node_prefix,
dc_idx=dc_idx)
def init(self):
LOGGER.debug("Waiting until instance {0._instance} starts running...".format(self))
self._instance_wait_safe(self._instance.wait_until_running)
if not cluster.TestConfig.REUSE_CLUSTER:
resources_to_tag = [self._instance.id, ]
if len(self._instance.network_interfaces) == 2:
# first we need to configure the both networks so we'll have public ip
self.allocate_and_attach_elastic_ip(self.parent_cluster, self.dc_idx)
resources_to_tag.append(self.eip_allocation_id)
self._ec2_service.create_tags(Resources=resources_to_tag, Tags=tags_as_ec2_tags(self.tags))
self._wait_public_ip()
super().init()
@cached_property
def tags(self) -> Dict[str, str]:
return {**super().tags,
"NodeIndex": str(self.node_index), }
def _set_keep_alive(self):
self._ec2_service.create_tags(Resources=[self._instance.id], Tags=[{"Key": "keep", "Value": "alive"}])
return super()._set_keep_alive()
@property
def region(self):
return self._ec2_service.meta.client.meta.region_name
@retrying(n=10, sleep_time=5, allowed_exceptions=NETWORK_EXCEPTIONS, message="Retrying set_hostname")
def set_hostname(self):
self.log.info('Changing hostname to %s', self.name)
# Using https://aws.amazon.com/premiumsupport/knowledge-center/linux-static-hostname-rhel7-centos7/
# FIXME: workaround to avoid host rename generating errors on other commands
if self.is_debian():
return
result = self.remoter.run(f"sudo hostnamectl set-hostname --static {self.name}", ignore_status=True)
if result.ok:
self.log.debug('Hostname has been changed succesfully. Apply')
apply_hostname_change_script = dedent(f"""
if ! grep "\\$LocalHostname {self.name}" /etc/rsyslog.conf; then
echo "" >> /etc/rsyslog.conf
echo "\\$LocalHostname {self.name}" >> /etc/rsyslog.conf
fi
grep -P "127.0.0.1[^\\\\n]+{self.name}" /etc/hosts || sed -ri "s/(127.0.0.1[ \\t]+localhost[^\\n]*)$/\\1\\t{self.name}/" /etc/hosts
grep "preserve_hostname: true" /etc/cloud/cloud.cfg 1>/dev/null 2>&1 || echo "preserve_hostname: true" >> /etc/cloud/cloud.cfg
systemctl restart rsyslog
""")
self.remoter.run(f"sudo bash -cxe '{apply_hostname_change_script}'")
self.log.debug('Continue node %s set up', self.name)
else:
self.log.warning('Hostname has not been changed. Error: %s.\n Continue with old name', result.stderr)
@property
def is_spot(self):
return bool(self._instance.instance_lifecycle and 'spot' in self._instance.instance_lifecycle.lower())
def check_spot_termination(self):
try:
result = self.remoter.run(
'curl http://169.254.169.254/latest/meta-data/spot/instance-action', verbose=False)
status = result.stdout.strip()
except Exception as details: # pylint: disable=broad-except
self.log.warning('Error during getting spot termination notification %s', details)
return 0
if '404 - Not Found' in status:
return 0
self.log.warning('Got spot termination notification from AWS %s', status)
terminate_action = json.loads(status)
terminate_action_timestamp = time.mktime(datetime.strptime(
terminate_action['time'], "%Y-%m-%dT%H:%M:%SZ").timetuple())
next_check_delay = terminate_action['time-left'] = terminate_action_timestamp - time.time()
SpotTerminationEvent(node=self, message=terminate_action).publish()
return max(next_check_delay - SPOT_TERMINATION_CHECK_OVERHEAD, 0)
@property
def external_address(self):
"""
the communication address for usage between the test and the nodes
:return:
"""
if self.parent_cluster.params.get("ip_ssh_connections") == "ipv6":
return self.ipv6_ip_address
elif TestConfig.IP_SSH_CONNECTIONS == 'public' or cluster.TestConfig.INTRA_NODE_COMM_PUBLIC:
return self.public_ip_address
else:
return self._instance.private_ip_address
def _get_public_ip_address(self) -> Optional[str]:
return self._instance.public_ip_address
def _get_private_ip_address(self) -> Optional[str]:
if self._eth1_private_ip_address:
return self._eth1_private_ip_address
return self._instance.private_ip_address
def _get_ipv6_ip_address(self) -> Optional[str]:
return self._instance.network_interfaces[0].ipv6_addresses[0]["Ipv6Address"]
def _refresh_instance_state(self):
raise NotImplementedError()
def allocate_and_attach_elastic_ip(self, parent_cluster, dc_idx):
primary_interface = [
interface for interface in self._instance.network_interfaces if interface.attachment['DeviceIndex'] == 0][0]
if primary_interface.association_attribute is None:
# create and attach EIP
client: EC2Client = boto3.client('ec2', region_name=parent_cluster.region_names[dc_idx])
response = client.allocate_address(Domain='vpc')
self.eip_allocation_id = response['AllocationId']
client.associate_address(
AllocationId=self.eip_allocation_id,
NetworkInterfaceId=primary_interface.id,
)
self._eth1_private_ip_address = [interface for interface in self._instance.network_interfaces if
interface.attachment['DeviceIndex'] == 1][0].private_ip_address
def _instance_wait_safe(self, instance_method, *args, **kwargs):
"""
Wrapper around AWS instance waiters that is safer to use.
Since AWS adopts an eventual consistency model, sometimes the method
wait_until_running will raise a botocore.exceptions.WaiterError saying
the instance does not exist. AWS API guide [1] recommends that the
procedure is retried using an exponencial backoff algorithm [2].
:see: [1] http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#eventual-consistency
:see: [2] http://docs.aws.amazon.com/general/latest/gr/api-retries.html
"""
threshold = 300
ok = False
retries = 0
max_retries = 9
while not ok and retries <= max_retries:
try:
instance_method(*args, **kwargs)
ok = True
except WaiterError:
time.sleep(min((2 ** retries) * 2, threshold))
retries += 1
if not ok:
try:
self._instance.reload()
except Exception as ex: # pylint: disable=broad-except
LOGGER.exception("Error while reloading instance metadata: %s", ex)
finally:
method_name = instance_method.__name__
instance_id = self._instance.id
LOGGER.debug(self._instance.meta.data)
msg = "Timeout while running '{method_name}' method on AWS instance '{instance_id}'".format(
method_name=method_name, instance_id=instance_id)
raise cluster.NodeError(msg)
def _wait_public_ip(self):
ec2_instance_wait_public_ip(self._instance)
def config_ipv6_as_persistent(self):
if self.distro.is_ubuntu:
self.remoter.sudo("sh -c \"echo 'iface eth0 inet6 auto' >> /etc/network/interfaces\"")
LOGGER.debug('adding ipv6 autogenerated config to /etc/network/interfaces')
else:
cidr = dedent("""
BASE_EC2_NETWORK_URL=http://169.254.169.254/latest/meta-data/network/interfaces/macs/
MAC=`curl -s ${BASE_EC2_NETWORK_URL}`
curl -s ${BASE_EC2_NETWORK_URL}${MAC}/subnet-ipv6-cidr-blocks
""")
output = self.remoter.run(f"sudo bash -cxe '{cidr}'")
ipv6_cidr = output.stdout.strip()
self.remoter.run(
f"sudo sh -c \"echo 'sudo ip route add {ipv6_cidr} dev eth0' >> /etc/sysconfig/network-scripts/init.ipv6-global\"")
res = self.remoter.run(f"grep '{ipv6_cidr}' /etc/sysconfig/network-scripts/init.ipv6-global")
LOGGER.debug('init.ipv6-global was {}updated'.format('' if res.stdout.strip else 'NOT '))
def restart(self):
# We differentiate between "Restart" and "Reboot".
# Restart in AWS will be a Stop and Start of an instance.
# When using storage optimized instances like i2 or i3, the data on disk is deleted upon STOP. Therefore, we
# need to setup the instance and treat it as a new instance.
if self._instance.spot_instance_request_id:
LOGGER.debug("target node is spot instance, impossible to stop this instance, skipping the restart")
return
if self.is_seed:
# Due to https://github.com/scylladb/scylla/issues/7588, when we restart a node that is defined as "seed",
# we must state a different, living node as the seed provider in the scylla yaml of the restarted node
other_nodes = list(set(self.parent_cluster.nodes) - {self})
free_nodes = [node for node in other_nodes if not node.running_nemesis]
random_node = random.choice(free_nodes)
seed_provider = [{
"class_name": "org.apache.cassandra.locator.SimpleSeedProvider",
"parameters": [{
"seeds": f"{random_node.ip_address}"
}, ],
}, ]
with self.remote_scylla_yaml() as scylla_yml:
scylla_yml["seed_provider"] = seed_provider
need_to_setup = any(ss in self._instance.instance_type for ss in ("i2", "i3", ))
with ExitStack() as stack:
if need_to_setup:
# There is no disk yet, lots of the errors here are acceptable, and we'll ignore them.
for db_filter in (DbEventsFilter(db_event=DatabaseLogEvent.DATABASE_ERROR, node=self),
DbEventsFilter(db_event=DatabaseLogEvent.SCHEMA_FAILURE, node=self),
DbEventsFilter(db_event=DatabaseLogEvent.NO_SPACE_ERROR, node=self),
DbEventsFilter(db_event=DatabaseLogEvent.FILESYSTEM_ERROR, node=self),
DbEventsFilter(db_event=DatabaseLogEvent.POWER_OFF, node=self),
DbEventsFilter(db_event=DatabaseLogEvent.RUNTIME_ERROR, node=self), ):
stack.enter_context(db_filter)
self.remoter.sudo(shell_script_cmd(f"""\
sed -e '/.*scylla/s/^/#/g' -i /etc/fstab
sed -e '/auto_bootstrap:.*/s/false/true/g' -i /etc/scylla/scylla.yaml
if ! grep ^replace_address_first_boot: /etc/scylla/scylla.yaml; then
echo 'replace_address_first_boot: {self.ip_address}' | tee --append /etc/scylla/scylla.yaml
fi
"""))
self._instance.stop()
self._instance_wait_safe(self._instance.wait_until_stopped)
self._instance.start()
self._instance_wait_safe(self._instance.wait_until_running)
self._wait_public_ip()
self.log.debug("Got a new public IP: %s", self._instance.public_ip_address)
self.refresh_ip_address()
self.wait_ssh_up()
if need_to_setup:
self.stop_scylla_server(verify_down=False)
# Moving var-lib-scylla.mount away, since scylla_create_devices fails if it already exists
mount_path = "/etc/systemd/system/var-lib-scylla.mount"
if self.remoter.sudo(f"test -e {mount_path}", ignore_status=True).ok:
self.remoter.sudo(f"mv {mount_path} /tmp/")
# The scylla_create_devices has been moved to the '/opt/scylladb' folder in the master branch.
for create_devices_file in ("/usr/lib/scylla/scylla-ami/scylla_create_devices",
"/opt/scylladb/scylla-ami/scylla_create_devices",
"/opt/scylladb/scylla-machine-image/scylla_create_devices", ):
if self.remoter.sudo(f"test -x {create_devices_file}", ignore_status=True).ok:
self.remoter.sudo(create_devices_file)
break
else:
raise IOError("scylla_create_devices file isn't found")
self.start_scylla_server(verify_up=False)
self.remoter.sudo(shell_script_cmd("""\
sed -e '/auto_bootstrap:.*/s/true/false/g' -i /etc/scylla/scylla.yaml
sed -e 's/^replace_address_first_boot:/# replace_address_first_boot:/g' -i /etc/scylla/scylla.yaml
"""))
def hard_reboot(self):
self._instance_wait_safe(self._instance.reboot)
def release_address(self):
self._instance.wait_until_terminated()
client: EC2Client = boto3.client('ec2', region_name=self.parent_cluster.region_names[self.dc_idx])
client.release_address(AllocationId=self.eip_allocation_id)
def destroy(self):
self.stop_task_threads()
self.wait_till_tasks_threads_are_stopped()
self._instance.terminate()
if self.eip_allocation_id:
self.release_address()
super().destroy()
def get_console_output(self):
"""Get instance console Output
Get console output of instance which is printed during initiating and loading
Get only last 64KB of output data.
"""
result = self._ec2_service.meta.client.get_console_output(
InstanceId=self._instance.id,
)
console_output = result.get('Output', '')
if not console_output:
self.log.warning('Some error during getting console output')
return console_output
def get_console_screenshot(self):
result = self._ec2_service.meta.client.get_console_screenshot(
InstanceId=self._instance.id
)
imagedata = result.get('ImageData', '')
if not imagedata:
self.log.warning('Some error during getting console screenshot')
return imagedata.encode('ascii')
def traffic_control(self, tcconfig_params=None):
"""
run tcconfig locally to create tc commands, and run them on the node
:param tcconfig_params: commandline arguments for tcset, if None will call tcdel
:return: None
"""
self.remoter.run("sudo modprobe sch_netem")
if tcconfig_params is None:
tc_command = LOCAL_CMD_RUNNER.run("tcdel eth1 --tc-command", ignore_status=True).stdout
self.remoter.run('sudo bash -cxe "%s"' % tc_command, ignore_status=True)
else:
tc_command = LOCAL_CMD_RUNNER.run("tcset eth1 {} --tc-command".format(tcconfig_params)).stdout
self.remoter.run('sudo bash -cxe "%s"' % tc_command)
def install_traffic_control(self):
if self.distro.is_amazon2:
self.log.debug("Installing iproute-tc package for AMAZON2")
self.remoter.run("sudo yum install -y iproute-tc", ignore_status=True)
return self.remoter.run("/sbin/tc -h", ignore_status=True).ok
@property
def image(self):
return self._instance.image_id
@property
def ena_support(self) -> bool:
return self._instance.ena_support
class ScyllaAWSCluster(cluster.BaseScyllaCluster, AWSCluster):
def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids, # pylint: disable=too-many-arguments
services, credentials, ec2_instance_type='c5.xlarge',
ec2_ami_username='centos',
ec2_block_device_mappings=None,
user_prefix=None,
n_nodes=3,
params=None):
# pylint: disable=too-many-locals
# We have to pass the cluster name in advance in user_data
cluster_uuid = cluster.TestConfig.test_id()
cluster_prefix = cluster.prepend_user_prefix(user_prefix, 'db-cluster')
node_prefix = cluster.prepend_user_prefix(user_prefix, 'db-node')
node_type = 'scylla-db'
shortid = str(cluster_uuid)[:8]
name = '%s-%s' % (cluster_prefix, shortid)
ami_tags = get_ami_tags(ec2_ami_id[0], region_name=params.get('region_name').split()[0])
# TODO: remove once all other related code is merged in scylla-pkg and scylla-machine-image
user_data_format_version = ami_tags.get('sci_version', '2')
user_data_format_version = ami_tags.get('user_data_format_version', user_data_format_version)
if parse_version(user_data_format_version) >= parse_version('2'):
user_data = dict(scylla_yaml=dict(cluster_name=name), start_scylla_on_first_boot=False)
else:
user_data = ('--clustername %s '
'--totalnodes %s' % (name, sum(n_nodes)))
user_data += ' --stop-services'
super(ScyllaAWSCluster, self).__init__(ec2_ami_id=ec2_ami_id,
ec2_subnet_id=ec2_subnet_id,
ec2_security_group_ids=ec2_security_group_ids,
ec2_instance_type=ec2_instance_type,
ec2_ami_username=ec2_ami_username,
ec2_user_data=user_data,
ec2_block_device_mappings=ec2_block_device_mappings,
cluster_uuid=cluster_uuid,
services=services,
credentials=credentials,
cluster_prefix=cluster_prefix,
node_prefix=node_prefix,
n_nodes=n_nodes,
params=params,
node_type=node_type,
extra_network_interface=params.get('extra_network_interface'))
self.version = '2.1'
def add_nodes(self, count, ec2_user_data='', dc_idx=0, rack=0, enable_auto_bootstrap=False):
if not ec2_user_data:
if self._ec2_user_data and isinstance(self._ec2_user_data, str):
ec2_user_data = re.sub(r'(--totalnodes\s)(\d*)(\s)',
r'\g<1>{}\g<3>'.format(len(self.nodes) + count), self._ec2_user_data)
elif self._ec2_user_data and isinstance(self._ec2_user_data, dict):
ec2_user_data = self._ec2_user_data
else:
ec2_user_data = ('--clustername %s --totalnodes %s ' % (self.name, count))
if self.nodes and isinstance(ec2_user_data, str):
node_ips = [node.ip_address for node in self.nodes if node.is_seed]
seeds = ",".join(node_ips)
if not seeds:
seeds = self.nodes[0].ip_address
ec2_user_data += ' --seeds %s ' % seeds
ec2_user_data = self.update_bootstrap(ec2_user_data, enable_auto_bootstrap)
added_nodes = super(ScyllaAWSCluster, self).add_nodes(count=count,
ec2_user_data=ec2_user_data,
dc_idx=dc_idx,
rack=rack,
enable_auto_bootstrap=enable_auto_bootstrap)
return added_nodes
def node_config_setup(self, node, seed_address=None, endpoint_snitch=None, murmur3_partitioner_ignore_msb_bits=None, client_encrypt=None): # pylint: disable=too-many-arguments
setup_params = dict(
enable_exp=self.params.get('experimental'),
endpoint_snitch=endpoint_snitch,
authenticator=self.params.get('authenticator'),
server_encrypt=self.params.get('server_encrypt'),
client_encrypt=client_encrypt if client_encrypt is not None else self.params.get('client_encrypt'),
append_scylla_args=self.get_scylla_args(),
authorizer=self.params.get('authorizer'),
hinted_handoff=self.params.get('hinted_handoff'),
alternator_port=self.params.get('alternator_port'),
seed_address=seed_address,
append_scylla_yaml=self.params.get('append_scylla_yaml'),
murmur3_partitioner_ignore_msb_bits=murmur3_partitioner_ignore_msb_bits,
ip_ssh_connections=self.params.get('ip_ssh_connections'),
alternator_enforce_authorization=self.params.get('alternator_enforce_authorization'),
internode_compression=self.params.get('internode_compression'),
internode_encryption=self.params.get('internode_encryption'),
ldap=self.params.get('use_ldap_authorization'),
ms_ad_ldap=self.params.get('use_ms_ad_ldap'),
)
if cluster.TestConfig.INTRA_NODE_COMM_PUBLIC:
setup_params.update(dict(
broadcast=node.public_ip_address,
))
if self.extra_network_interface:
setup_params.update(dict(
seed_address=seed_address,
broadcast=node.private_ip_address,
listen_on_all_interfaces=True,
))
node.config_setup(**setup_params)
@staticmethod
def _wait_for_preinstalled_scylla(node):
node.wait_for_machine_image_configured()
def _scylla_post_install(self, node: AWSNode, new_scylla_installed: bool, devname: str) -> None:
super()._scylla_post_install(node, new_scylla_installed, devname)
if self.params.get('ip_ssh_connections') == 'ipv6':
node.set_web_listen_address()
def _reuse_cluster_setup(self, node):
node.run_startup_script() # Reconfigure rsyslog.
def get_endpoint_snitch(self, default_multi_region="Ec2MultiRegionSnitch"):
return super().get_endpoint_snitch(default_multi_region,)
def destroy(self):
self.stop_nemesis()
super(ScyllaAWSCluster, self).destroy()
class CassandraAWSCluster(ScyllaAWSCluster):
def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids, # pylint: disable=too-many-arguments
services, credentials, ec2_instance_type='c5.xlarge',
ec2_ami_username='ubuntu',
ec2_block_device_mappings=None,
user_prefix=None,
n_nodes=3,
params=None):
# pylint: disable=too-many-locals
if ec2_block_device_mappings is None:
ec2_block_device_mappings = []
# We have to pass the cluster name in advance in user_data
cluster_uuid = uuid.uuid4()
cluster_prefix = cluster.prepend_user_prefix(user_prefix,
'cs-db-cluster')
node_prefix = cluster.prepend_user_prefix(user_prefix, 'cs-db-node')
node_type = 'cs-db'
shortid = str(cluster_uuid)[:8]
name = '%s-%s' % (cluster_prefix, shortid)
user_data = ('--clustername %s '
'--totalnodes %s --version community '
'--release 2.1.15' % (name, sum(n_nodes)))
super(CassandraAWSCluster, self).__init__(ec2_ami_id=ec2_ami_id, # pylint: disable=unexpected-keyword-arg
ec2_subnet_id=ec2_subnet_id,
ec2_security_group_ids=ec2_security_group_ids,
ec2_instance_type=ec2_instance_type,
ec2_ami_username=ec2_ami_username,
ec2_user_data=user_data,
ec2_block_device_mappings=ec2_block_device_mappings,
cluster_uuid=cluster_uuid,
services=services,
credentials=credentials,
cluster_prefix=cluster_prefix,
node_prefix=node_prefix,
n_nodes=n_nodes,
params=params,
node_type=node_type)
def get_seed_nodes(self):
node = self.nodes[0]
yaml_dst_path = os.path.join(tempfile.mkdtemp(prefix='sct-cassandra'), 'cassandra.yaml')
node.remoter.receive_files(src='/etc/cassandra/cassandra.yaml',
dst=yaml_dst_path)
with open(yaml_dst_path, 'r') as yaml_stream:
conf_dict = yaml.safe_load(yaml_stream)
try:
return conf_dict['seed_provider'][0]['parameters'][0]['seeds'].split(',')
except:
raise ValueError('Unexpected cassandra.yaml '
'contents:\n%s' % yaml_stream.read())
def add_nodes(self, count, ec2_user_data='', dc_idx=0, rack=0, enable_auto_bootstrap=False):
if not ec2_user_data:
if self.nodes:
seeds = ",".join(self.get_seed_nodes())
ec2_user_data = ('--clustername %s '
'--totalnodes %s --seeds %s '
'--version community '
'--release 2.1.15' % (self.name,
count,
seeds))
ec2_user_data = self.update_bootstrap(ec2_user_data, enable_auto_bootstrap)
added_nodes = super(CassandraAWSCluster, self).add_nodes(count=count,
ec2_user_data=ec2_user_data,
dc_idx=dc_idx,
rack=0)
return added_nodes
def node_setup(self, node, verbose=False, timeout=3600):
node.wait_ssh_up(verbose=verbose)
node.wait_db_up(verbose=verbose)
if cluster.TestConfig.REUSE_CLUSTER:
# for reconfigure rsyslog
node.run_startup_script()
return
node.wait_apt_not_running()
node.remoter.run('sudo apt-get update')
node.remoter.run('sudo apt-get install -y collectd collectd-utils')
node.remoter.run('sudo apt-get install -y openjdk-6-jdk')
@cluster.wait_for_init_wrap
def wait_for_init(self, node_list=None, verbose=False, timeout=None, check_node_health=True): # pylint: disable=too-many-arguments
self.get_seed_nodes()
class LoaderSetAWS(cluster.BaseLoaderSet, AWSCluster):
def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids, # pylint: disable=too-many-arguments
services, credentials, ec2_instance_type='c5.xlarge',
ec2_block_device_mappings=None,
ec2_ami_username='centos',
user_prefix=None, n_nodes=10, params=None):
# pylint: disable=too-many-locals
node_prefix = cluster.prepend_user_prefix(user_prefix, 'loader-node')
node_type = 'loader'
cluster_prefix = cluster.prepend_user_prefix(user_prefix, 'loader-set')
user_data = ('--clustername %s --totalnodes %s --bootstrap false --stop-services' %
(cluster_prefix, n_nodes))
cluster.BaseLoaderSet.__init__(self,
params=params)
AWSCluster.__init__(self,
ec2_ami_id=ec2_ami_id,
ec2_subnet_id=ec2_subnet_id,
ec2_security_group_ids=ec2_security_group_ids,
ec2_instance_type=ec2_instance_type,
ec2_ami_username=ec2_ami_username,
ec2_user_data=user_data,
services=services,
ec2_block_device_mappings=ec2_block_device_mappings,
credentials=credentials,
cluster_prefix=cluster_prefix,
node_prefix=node_prefix,
n_nodes=n_nodes,
params=params,
node_type=node_type)
class MonitorSetAWS(cluster.BaseMonitorSet, AWSCluster):
def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids, # pylint: disable=too-many-arguments
services, credentials, ec2_instance_type='c5.xlarge',
ec2_block_device_mappings=None,
ec2_ami_username='centos',
user_prefix=None, n_nodes=10, targets=None, params=None):
# pylint: disable=too-many-locals
node_prefix = cluster.prepend_user_prefix(user_prefix, 'monitor-node')
node_type = 'monitor'
cluster_prefix = cluster.prepend_user_prefix(user_prefix, 'monitor-set')
cluster.BaseMonitorSet.__init__(self,
targets=targets,
params=params)
AWSCluster.__init__(self,
ec2_ami_id=ec2_ami_id,
ec2_subnet_id=ec2_subnet_id,
ec2_security_group_ids=ec2_security_group_ids,
ec2_instance_type=ec2_instance_type,
ec2_ami_username=ec2_ami_username,
services=services,
ec2_block_device_mappings=ec2_block_device_mappings,
credentials=credentials,
cluster_prefix=cluster_prefix,
node_prefix=node_prefix,
n_nodes=n_nodes,
params=params,
node_type=node_type)
| agpl-3.0 |
s3nk4s/flaskTutorials | FlaskApp/FlaskApp/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py | 2375 | 11628 | """Utilities for writing code that runs on Python 2 and 3"""
#Copyright (c) 2010-2011 Benjamin Peterson
#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.
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.2.0" # Revision 41c74fef2ded
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result)
# This is a bit ugly, but it avoids running this again.
delattr(tp, self.name)
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _MovedItems(types.ModuleType):
"""Lazy loading of moved objects"""
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
del attr
moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_iterkeys = "keys"
_itervalues = "values"
_iteritems = "items"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_code = "func_code"
_func_defaults = "func_defaults"
_iterkeys = "iterkeys"
_itervalues = "itervalues"
_iteritems = "iteritems"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
if PY3:
def get_unbound_function(unbound):
return unbound
Iterator = object
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
else:
def get_unbound_function(unbound):
return unbound.im_func
class Iterator(object):
def next(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
def iterkeys(d):
"""Return an iterator over the keys of a dictionary."""
return iter(getattr(d, _iterkeys)())
def itervalues(d):
"""Return an iterator over the values of a dictionary."""
return iter(getattr(d, _itervalues)())
def iteritems(d):
"""Return an iterator over the (key, value) pairs of a dictionary."""
return iter(getattr(d, _iteritems)())
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
int2byte = chr
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if PY3:
import builtins
exec_ = getattr(builtins, "exec")
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
print_ = getattr(builtins, "print")
del builtins
else:
def exec_(code, globs=None, locs=None):
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
def print_(*args, **kwargs):
"""The new-style print function."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
_add_doc(reraise, """Reraise an exception.""")
def with_metaclass(meta, base=object):
"""Create a base class with a metaclass."""
return meta("NewBase", (base,), {})
| mit |
muntasirsyed/intellij-community | python/lib/Lib/site-packages/django/conf/locale/ka/formats.py | 329 | 1888 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'l, j F, Y'
TIME_FORMAT = 'h:i:s a'
DATETIME_FORMAT = 'j F, Y h:i:s a'
YEAR_MONTH_FORMAT = 'F, Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j.M.Y'
SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s'
FIRST_DAY_OF_WEEK = 1 # (Monday)
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
# '%d %b %Y', '%d %b, %Y', '%d %b. %Y', # '25 Oct 2006', '25 Oct, 2006', '25 Oct. 2006'
# '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
# '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06'
)
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59'
'%d.%m.%Y %H:%M', # '25.10.2006 14:30'
'%d.%m.%Y', # '25.10.2006'
'%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59'
'%d.%m.%y %H:%M', # '25.10.06 14:30'
'%d.%m.%y', # '25.10.06'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
)
DECIMAL_SEPARATOR = '.'
THOUSAND_SEPARATOR = " "
NUMBER_GROUPING = 3
| apache-2.0 |
hiuwo/acq4 | acq4/analysis/modules/MapImager/MapConvolverTemplate.py | 4 | 3208 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './acq4/analysis/modules/MapImager/MapConvolverTemplate.ui'
#
# Created: Tue Dec 24 01:49:13 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(504, 237)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setMargin(3)
self.gridLayout.setSpacing(3)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setSpacing(1)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(Form)
self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.spacingSpin = SpinBox(Form)
self.spacingSpin.setObjectName(_fromUtf8("spacingSpin"))
self.horizontalLayout.addWidget(self.spacingSpin)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.processBtn = QtGui.QPushButton(Form)
self.processBtn.setObjectName(_fromUtf8("processBtn"))
self.gridLayout.addWidget(self.processBtn, 3, 0, 1, 1)
self.tree = TreeWidget(Form)
self.tree.setObjectName(_fromUtf8("tree"))
self.tree.header().setDefaultSectionSize(120)
self.tree.header().setStretchLastSection(True)
self.gridLayout.addWidget(self.tree, 2, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form", "Spacing:", None))
self.spacingSpin.setToolTip(_translate("Form", "Spacing of the grid that the map will be projected onto.", None))
self.processBtn.setText(_translate("Form", "Process", None))
self.tree.headerItem().setText(0, _translate("Form", "Parameter", None))
self.tree.headerItem().setText(1, _translate("Form", "Method", None))
self.tree.headerItem().setText(2, _translate("Form", "Sigma", None))
self.tree.headerItem().setText(3, _translate("Form", "Interpolation type", None))
self.tree.headerItem().setText(4, _translate("Form", "Remove", None))
from acq4.pyqtgraph.widgets.SpinBox import SpinBox
from pyqtgraph import TreeWidget
| mit |
icoxfog417/WatsonDisasterApp | run.py | 1 | 1421 | import argparse
from app.environment import Environment
import app.apis.twitter as twitter
import app.apis.file_api as file_api
import app.apis.kintone as kintone
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Data Extractor for Watson Disaster App")
keyword, locations = Environment.get_runtime_parameters()
parser.add_argument("-kw", type=str, help="keyword to search the tweets")
parser.add_argument("-loc", type=str, help="locations to search the tweets")
parser.add_argument("-path", type=str, help="file path to read")
parser.add_argument("-delimiter", type=str, default=",", help="file delimiter")
parser.add_argument("--header", action="store_true", help="use header as column definition")
parser.add_argument("--save", action="store_true", help="don't post to the kintone")
args = parser.parse_args()
keyword = args.kw if args.kw else keyword
locations = args.loc if args.loc else locations
generator = None
if args.path:
print("Read content from {0}".format(args.path))
generator = file_api.read(args.path, delimiter=args.delimiter, use_header=args.header)
else:
print("Search tweets by {0} @ {1}".format(keyword, locations))
generator = twitter.get_tweets(keyword, locations)
for n in generator:
if n.evaluate() and args.save:
kintone.post(n)
print(str(n))
| mit |
jhawkesworth/ansible | lib/ansible/modules/cloud/packet/packet_device.py | 31 | 21395 | #!/usr/bin/python
# (c) 2016, Tomas Karasek <tom.to.the.k@gmail.com>
# (c) 2016, Matt Baldwin <baldwin@stackpointcloud.com>
# (c) 2016, Thibaud Morel l'Horset <teebes@gmail.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: packet_device
short_description: Manage a bare metal server in the Packet Host.
description:
- Manage a bare metal server in the Packet Host (a "device" in the API terms).
- When the machine is created it can optionally wait for public IP address, or for active state.
- This module has a dependency on packet >= 1.0.
- API is documented at U(https://www.packet.net/developers/api/devices).
version_added: "2.3"
author:
- Tomas Karasek (@t0mk) <tom.to.the.k@gmail.com>
- Matt Baldwin (@baldwinSPC) <baldwin@stackpointcloud.com>
- Thibaud Morel l'Horset (@teebes) <teebes@gmail.com>
options:
auth_token:
description:
- Packet api token. You can also supply it in env var C(PACKET_API_TOKEN).
count:
description:
- The number of devices to create. Count number can be included in hostname via the %d string formatter.
default: 1
count_offset:
description:
- From which number to start the count.
default: 1
device_ids:
description:
- List of device IDs on which to operate.
facility:
description:
- Facility slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/facilities/).
features:
description:
- Dict with "features" for device creation. See Packet API docs for details.
hostnames:
description:
- A hostname of a device, or a list of hostnames.
- If given string or one-item list, you can use the C("%d") Python string format to expand numbers from I(count).
- If only one hostname, it might be expanded to list if I(count)>1.
aliases: [name]
locked:
description:
- Whether to lock a created device.
default: false
version_added: "2.4"
aliases: [lock]
type: bool
operating_system:
description:
- OS slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/operatingsystems/).
plan:
description:
- Plan slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/plans/).
project_id:
description:
- ID of project of the device.
required: true
state:
description:
- Desired state of the device.
- If set to C(present) (the default), the module call will return immediately after the device-creating HTTP request successfully returns.
- If set to C(active), the module call will block until all the specified devices are in state active due to the Packet API, or until I(wait_timeout).
choices: [present, absent, active, inactive, rebooted]
default: present
user_data:
description:
- Userdata blob made available to the machine
wait_for_public_IPv:
description:
- Whether to wait for the instance to be assigned a public IPv4/IPv6 address.
- If set to 4, it will wait until IPv4 is assigned to the instance.
- If set to 6, wait until public IPv6 is assigned to the instance.
choices: [4,6]
version_added: "2.4"
wait_timeout:
description:
- How long (seconds) to wait either for automatic IP address assignment, or for the device to reach the C(active) I(state).
- If I(wait_for_public_IPv) is set and I(state) is C(active), the module will wait for both events consequently, applying the timeout twice.
default: 900
ipxe_script_url:
description:
- URL of custom iPXE script for provisioning.
- More about custom iPXE for Packet devices at U(https://help.packet.net/technical/infrastructure/custom-ipxe).
version_added: "2.4"
always_pxe:
description:
- Persist PXE as the first boot option.
- Normally, the PXE process happens only on the first boot. Set this arg to have your device continuously boot to iPXE.
default: false
version_added: "2.4"
type: bool
requirements:
- "packet-python >= 1.35"
notes:
- Doesn't support check mode.
'''
EXAMPLES = '''
# All the examples assume that you have your Packet api token in env var PACKET_API_TOKEN.
# You can also pass it to the auth_token parameter of the module instead.
# Creating devices
- name: create 1 device
hosts: localhost
tasks:
- packet_device:
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
hostnames: myserver
operating_system: ubuntu_16_04
plan: baremetal_0
facility: sjc1
# Create the same device and wait until it is in state "active", (when it's
# ready for other API operations). Fail if the devices in not "active" in
# 10 minutes.
- name: create device and wait up to 10 minutes for active state
hosts: localhost
tasks:
- packet_device:
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
hostnames: myserver
operating_system: ubuntu_16_04
plan: baremetal_0
facility: sjc1
state: active
wait_timeout: 600
- name: create 3 ubuntu devices called server-01, server-02 and server-03
hosts: localhost
tasks:
- packet_device:
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
hostnames: server-%02d
count: 3
operating_system: ubuntu_16_04
plan: baremetal_0
facility: sjc1
- name: Create 3 coreos devices with userdata, wait until they get IPs and then wait for SSH
hosts: localhost
tasks:
- name: create 3 devices and register their facts
packet_device:
hostnames: [coreos-one, coreos-two, coreos-three]
operating_system: coreos_stable
plan: baremetal_0
facility: ewr1
locked: true
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
wait_for_public_IPv: 4
user_data: |
#cloud-config
ssh_authorized_keys:
- {{ lookup('file', 'my_packet_sshkey') }}
coreos:
etcd:
discovery: https://discovery.etcd.io/6a28e078895c5ec737174db2419bb2f3
addr: $private_ipv4:4001
peer-addr: $private_ipv4:7001
fleet:
public-ip: $private_ipv4
units:
- name: etcd.service
command: start
- name: fleet.service
command: start
register: newhosts
- name: wait for ssh
wait_for:
delay: 1
host: "{{ item.public_ipv4 }}"
port: 22
state: started
timeout: 500
with_items: "{{ newhosts.devices }}"
# Other states of devices
- name: remove 3 devices by uuid
hosts: localhost
tasks:
- packet_device:
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
state: absent
device_ids:
- 1fb4faf8-a638-4ac7-8f47-86fe514c30d8
- 2eb4faf8-a638-4ac7-8f47-86fe514c3043
- 6bb4faf8-a638-4ac7-8f47-86fe514c301f
'''
RETURN = '''
changed:
description: True if a device was altered in any way (created, modified or removed)
type: bool
sample: True
returned: success
devices:
description: Information about each device that was processed
type: list
sample: '[{"hostname": "my-server.com", "id": "2a5122b9-c323-4d5c-b53c-9ad3f54273e7",
"public_ipv4": "147.229.15.12", "private-ipv4": "10.0.15.12",
"tags": [], "locked": false, "state": "provisioning",
"public_ipv6": ""2604:1380:2:5200::3"}]'
returned: success
''' # NOQA
import os
import re
import time
import uuid
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
HAS_PACKET_SDK = True
try:
import packet
except ImportError:
HAS_PACKET_SDK = False
from ansible.module_utils.basic import AnsibleModule
NAME_RE = r'({0}|{0}{1}*{0})'.format(r'[a-zA-Z0-9]', r'[a-zA-Z0-9\-]')
HOSTNAME_RE = r'({0}\.)*{0}$'.format(NAME_RE)
MAX_DEVICES = 100
PACKET_DEVICE_STATES = (
'queued',
'provisioning',
'failed',
'powering_on',
'active',
'powering_off',
'inactive',
'rebooting',
)
PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN"
ALLOWED_STATES = ['absent', 'active', 'inactive', 'rebooted', 'present']
def serialize_device(device):
"""
Standard represenation for a device as returned by various tasks::
{
'id': 'device_id'
'hostname': 'device_hostname',
'tags': [],
'locked': false,
'state': 'provisioning',
'ip_addresses': [
{
"address": "147.75.194.227",
"address_family": 4,
"public": true
},
{
"address": "2604:1380:2:5200::3",
"address_family": 6,
"public": true
},
{
"address": "10.100.11.129",
"address_family": 4,
"public": false
}
],
"private_ipv4": "10.100.11.129",
"public_ipv4": "147.75.194.227",
"public_ipv6": "2604:1380:2:5200::3",
}
"""
device_data = {}
device_data['id'] = device.id
device_data['hostname'] = device.hostname
device_data['tags'] = device.tags
device_data['locked'] = device.locked
device_data['state'] = device.state
device_data['ip_addresses'] = [
{
'address': addr_data['address'],
'address_family': addr_data['address_family'],
'public': addr_data['public'],
}
for addr_data in device.ip_addresses
]
# Also include each IPs as a key for easier lookup in roles.
# Key names:
# - public_ipv4
# - public_ipv6
# - private_ipv4
# - private_ipv6 (if there is one)
for ipdata in device_data['ip_addresses']:
if ipdata['public']:
if ipdata['address_family'] == 6:
device_data['public_ipv6'] = ipdata['address']
elif ipdata['address_family'] == 4:
device_data['public_ipv4'] = ipdata['address']
elif not ipdata['public']:
if ipdata['address_family'] == 6:
# Packet doesn't give public ipv6 yet, but maybe one
# day they will
device_data['private_ipv6'] = ipdata['address']
elif ipdata['address_family'] == 4:
device_data['private_ipv4'] = ipdata['address']
return device_data
def is_valid_hostname(hostname):
return re.match(HOSTNAME_RE, hostname) is not None
def is_valid_uuid(myuuid):
try:
val = uuid.UUID(myuuid, version=4)
except ValueError:
return False
return str(val) == myuuid
def listify_string_name_or_id(s):
if ',' in s:
return s.split(',')
else:
return [s]
def get_hostname_list(module):
# hostname is a list-typed param, so I guess it should return list
# (and it does, in Ansible 2.2.1) but in order to be defensive,
# I keep here the code to convert an eventual string to list
hostnames = module.params.get('hostnames')
count = module.params.get('count')
count_offset = module.params.get('count_offset')
if isinstance(hostnames, str):
hostnames = listify_string_name_or_id(hostnames)
if not isinstance(hostnames, list):
raise Exception("name %s is not convertible to list" % hostnames)
# at this point, hostnames is a list
hostnames = [h.strip() for h in hostnames]
if (len(hostnames) > 1) and (count > 1):
_msg = ("If you set count>1, you should only specify one hostname "
"with the %d formatter, not a list of hostnames.")
raise Exception(_msg)
if (len(hostnames) == 1) and (count > 0):
hostname_spec = hostnames[0]
count_range = range(count_offset, count_offset + count)
if re.search(r"%\d{0,2}d", hostname_spec):
hostnames = [hostname_spec % i for i in count_range]
elif count > 1:
hostname_spec = '%s%%02d' % hostname_spec
hostnames = [hostname_spec % i for i in count_range]
for hn in hostnames:
if not is_valid_hostname(hn):
raise Exception("Hostname '%s' does not seem to be valid" % hn)
if len(hostnames) > MAX_DEVICES:
raise Exception("You specified too many hostnames, max is %d" %
MAX_DEVICES)
return hostnames
def get_device_id_list(module):
device_ids = module.params.get('device_ids')
if isinstance(device_ids, str):
device_ids = listify_string_name_or_id(device_ids)
device_ids = [di.strip() for di in device_ids]
for di in device_ids:
if not is_valid_uuid(di):
raise Exception("Device ID '%s' does not seem to be valid" % di)
if len(device_ids) > MAX_DEVICES:
raise Exception("You specified too many devices, max is %d" %
MAX_DEVICES)
return device_ids
def create_single_device(module, packet_conn, hostname):
for param in ('hostnames', 'operating_system', 'plan'):
if not module.params.get(param):
raise Exception("%s parameter is required for new device."
% param)
project_id = module.params.get('project_id')
plan = module.params.get('plan')
user_data = module.params.get('user_data')
facility = module.params.get('facility')
operating_system = module.params.get('operating_system')
locked = module.params.get('locked')
ipxe_script_url = module.params.get('ipxe_script_url')
always_pxe = module.params.get('always_pxe')
device = packet_conn.create_device(
project_id=project_id,
hostname=hostname,
plan=plan,
facility=facility,
operating_system=operating_system,
userdata=user_data,
locked=locked)
return device
def refresh_device_list(module, packet_conn, devices):
device_ids = [d.id for d in devices]
new_device_list = get_existing_devices(module, packet_conn)
return [d for d in new_device_list if d.id in device_ids]
def wait_for_devices_active(module, packet_conn, watched_devices):
wait_timeout = module.params.get('wait_timeout')
wait_timeout = time.time() + wait_timeout
refreshed = watched_devices
while wait_timeout > time.time():
refreshed = refresh_device_list(module, packet_conn, watched_devices)
if all(d.state == 'active' for d in refreshed):
return refreshed
time.sleep(5)
raise Exception("Waiting for state \"active\" timed out for devices: %s"
% [d.hostname for d in refreshed if d.state != "active"])
def wait_for_public_IPv(module, packet_conn, created_devices):
def has_public_ip(addr_list, ip_v):
return any([a['public'] and a['address_family'] == ip_v and
a['address'] for a in addr_list])
def all_have_public_ip(ds, ip_v):
return all([has_public_ip(d.ip_addresses, ip_v) for d in ds])
address_family = module.params.get('wait_for_public_IPv')
wait_timeout = module.params.get('wait_timeout')
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
refreshed = refresh_device_list(module, packet_conn, created_devices)
if all_have_public_ip(refreshed, address_family):
return refreshed
time.sleep(5)
raise Exception("Waiting for IPv%d address timed out. Hostnames: %s"
% (address_family, [d.hostname for d in created_devices]))
def get_existing_devices(module, packet_conn):
project_id = module.params.get('project_id')
return packet_conn.list_devices(
project_id, params={
'per_page': MAX_DEVICES})
def get_specified_device_identifiers(module):
if module.params.get('device_ids'):
device_id_list = get_device_id_list(module)
return {'ids': device_id_list, 'hostnames': []}
elif module.params.get('hostnames'):
hostname_list = get_hostname_list(module)
return {'hostnames': hostname_list, 'ids': []}
def act_on_devices(module, packet_conn, target_state):
specified_identifiers = get_specified_device_identifiers(module)
existing_devices = get_existing_devices(module, packet_conn)
changed = False
create_hostnames = []
if target_state in ['present', 'active', 'rebooted']:
# states where we might create non-existing specified devices
existing_devices_names = [ed.hostname for ed in existing_devices]
create_hostnames = [hn for hn in specified_identifiers['hostnames']
if hn not in existing_devices_names]
process_devices = [d for d in existing_devices
if (d.id in specified_identifiers['ids']) or
(d.hostname in specified_identifiers['hostnames'])]
if target_state != 'present':
_absent_state_map = {}
for s in PACKET_DEVICE_STATES:
_absent_state_map[s] = packet.Device.delete
state_map = {
'absent': _absent_state_map,
'active': {'inactive': packet.Device.power_on,
'provisioning': None, 'rebooting': None
},
'inactive': {'active': packet.Device.power_off},
'rebooted': {'active': packet.Device.reboot,
'inactive': packet.Device.power_on,
'provisioning': None, 'rebooting': None
},
}
# First do non-creation actions, it might be faster
for d in process_devices:
if d.state == target_state:
continue
if d.state in state_map[target_state]:
api_operation = state_map[target_state].get(d.state)
if api_operation is not None:
api_operation(d)
changed = True
else:
_msg = (
"I don't know how to process existing device %s from state %s "
"to state %s" %
(d.hostname, d.state, target_state))
raise Exception(_msg)
# At last create missing devices
created_devices = []
if create_hostnames:
created_devices = [create_single_device(module, packet_conn, n)
for n in create_hostnames]
if module.params.get('wait_for_public_IPv'):
created_devices = wait_for_public_IPv(
module, packet_conn, created_devices)
changed = True
processed_devices = created_devices + process_devices
if target_state == 'active':
processed_devices = wait_for_devices_active(
module, packet_conn, processed_devices)
return {
'changed': changed,
'devices': [serialize_device(d) for d in processed_devices]
}
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR),
no_log=True),
count=dict(type='int', default=1),
count_offset=dict(type='int', default=1),
device_ids=dict(type='list'),
facility=dict(),
features=dict(type='dict'),
hostnames=dict(type='list', aliases=['name']),
locked=dict(type='bool', default=False, aliases=['lock']),
operating_system=dict(),
plan=dict(),
project_id=dict(required=True),
state=dict(choices=ALLOWED_STATES, default='present'),
user_data=dict(default=None),
wait_for_public_IPv=dict(type='int', choices=[4, 6]),
wait_timeout=dict(type='int', default=900),
ipxe_script_url=dict(default=''),
always_pxe=dict(type='bool', default=False),
),
required_one_of=[('device_ids', 'hostnames',)],
mutually_exclusive=[
('always_pxe', 'operating_system'),
('ipxe_script_url', 'operating_system'),
('hostnames', 'device_ids'),
('count', 'device_ids'),
('count_offset', 'device_ids'),
]
)
if not HAS_PACKET_SDK:
module.fail_json(msg='packet required for this module')
if not module.params.get('auth_token'):
_fail_msg = ("if Packet API token is not in environment variable %s, "
"the auth_token parameter is required" %
PACKET_API_TOKEN_ENV_VAR)
module.fail_json(msg=_fail_msg)
auth_token = module.params.get('auth_token')
packet_conn = packet.Manager(auth_token=auth_token)
state = module.params.get('state')
try:
module.exit_json(**act_on_devices(module, packet_conn, state))
except Exception as e:
module.fail_json(msg='failed to set device state %s, error: %s' %
(state, to_native(e)), exception=traceback.format_exc())
if __name__ == '__main__':
main()
| gpl-3.0 |
cneill/barbican | functionaltests/api/v1/behaviors/container_behaviors.py | 2 | 5289 | """
Copyright 2014-2015 Rackspace
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.
"""
from functionaltests.api.v1.behaviors import base_behaviors
from functionaltests.api.v1.models import container_models
class ContainerBehaviors(base_behaviors.BaseBehaviors):
def create_container(self, model, extra_headers=None,
user_name=None, admin=None):
"""Create a container from the data in the model.
:param model: The metadata used to create the container
:param extra_headers: Headers used to create the container
:param user_name: The user name used to create the container
:param admin: The user with permissions to delete the container
:return: A tuple containing the response from the create
and the href to the newly created container
"""
resp = self.client.post('containers', request_model=model,
extra_headers=extra_headers,
user_name=user_name)
returned_data = self.get_json(resp)
container_ref = returned_data.get('container_ref')
if container_ref:
if admin is None:
admin = user_name
self.created_entities.append((container_ref, admin))
return resp, container_ref
def get_container(self, container_ref, extra_headers=None, user_name=None):
"""Handles getting a single container
:param container_ref: Reference to the container to be retrieved
:param extra_headers: Headers used to get the container
:param user_name: The user name used to get the container
:return: The response of the GET.
"""
resp = self.client.get(
container_ref, response_model_type=container_models.ContainerModel,
user_name=user_name)
return resp
def get_containers(self, limit=10, offset=0, filter=None,
extra_headers=None, user_name=None):
"""Handles getting a list of containers.
:param limit: limits number of returned containers
:param offset: represents how many records to skip before retrieving
the list
:param name_filter: allows you to filter results based on name
:param extra_headers: Extra headers used to retrieve a list of
containers
:param user_name: The user name used to get the list
:return: Returns the response, a list of container models, and
references to the next and previous list of containers.
"""
params = {'limit': limit, 'offset': offset}
if filter:
params['name'] = filter
resp = self.client.get('containers', params=params,
extra_headers=extra_headers,
user_name=user_name)
container_list = self.get_json(resp)
containers, next_ref, prev_ref = self.client.get_list_of_models(
container_list, container_models.ContainerModel)
return resp, containers, next_ref, prev_ref
def delete_container(self, container_ref, extra_headers=None,
expected_fail=False, user_name=None):
"""Handles deleting a containers.
:param container_ref: Reference of the container to be deleted
:param extra_headers: Any additional headers needed.
:param expected_fail: If there is a negative test, this should be
marked true if you are trying to delete a container that does
not exist.
:param user_name: The user name used to delete the container
:return: Response of the delete.
"""
resp = self.client.delete(container_ref, extra_headers,
user_name=user_name)
if not expected_fail:
for item in self.created_entities:
if item[0] == container_ref:
self.created_entities.remove(item)
return resp
def delete_all_created_containers(self):
"""Delete all of the containers that we have created."""
entities = list(self.created_entities)
for (container_ref, admin) in entities:
self.delete_container(container_ref, user_name=admin)
def update_container(self, container_ref, user_name=None):
"""Attempt to update a container (which is an invalid operation)
Update (HTTP PUT) is not supported against a container resource, so
issuing this call should fail.
:param container_ref: Reference of the container to be updated
:param user_name: The user name used to update the container
:return: Response of the update.
"""
resp = self.client.put(container_ref, user_name=user_name)
return resp
| apache-2.0 |
Pretio/boto | boto/cloudsearch/__init__.py | 145 | 1731 | # Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
#
from boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the Amazon CloudSearch service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
import boto.cloudsearch.layer1
return get_regions(
'cloudsearch',
connection_cls=boto.cloudsearch.layer1.Layer1
)
def connect_to_region(region_name, **kw_params):
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None
| mit |
google/mysql-protobuf | protobuf/gtest/test/gtest_catch_exceptions_test.py | 2139 | 9901 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of Google Inc. 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.
"""Tests Google Test's exception catching behavior.
This script invokes gtest_catch_exceptions_test_ and
gtest_catch_exceptions_ex_test_ (programs written with
Google Test) and verifies their output.
"""
__author__ = 'vladl@google.com (Vlad Losev)'
import os
import gtest_test_utils
# Constants.
FLAG_PREFIX = '--gtest_'
LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0'
FILTER_FLAG = FLAG_PREFIX + 'filter'
# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with
# exceptions enabled.
EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_catch_exceptions_ex_test_')
# Path to the gtest_catch_exceptions_test_ binary, compiled with
# exceptions disabled.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_catch_exceptions_no_ex_test_')
environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
# Tests in this file run a Google-Test-based test program and expect it
# to terminate prematurely. Therefore they are incompatible with
# the premature-exit-file protocol by design. Unset the
# premature-exit filepath to prevent Google Test from creating
# the file.
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
TEST_LIST = gtest_test_utils.Subprocess(
[EXE_PATH, LIST_TESTS_FLAG], env=environ).output
SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
if SUPPORTS_SEH_EXCEPTIONS:
BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output
EX_BINARY_OUTPUT = gtest_test_utils.Subprocess(
[EX_EXE_PATH], env=environ).output
# The tests.
if SUPPORTS_SEH_EXCEPTIONS:
# pylint:disable-msg=C6302
class CatchSehExceptionsTest(gtest_test_utils.TestCase):
"""Tests exception-catching behavior."""
def TestSehExceptions(self, test_output):
self.assert_('SEH exception with code 0x2a thrown '
'in the test fixture\'s constructor'
in test_output)
self.assert_('SEH exception with code 0x2a thrown '
'in the test fixture\'s destructor'
in test_output)
self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()'
in test_output)
self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()'
in test_output)
self.assert_('SEH exception with code 0x2a thrown in SetUp()'
in test_output)
self.assert_('SEH exception with code 0x2a thrown in TearDown()'
in test_output)
self.assert_('SEH exception with code 0x2a thrown in the test body'
in test_output)
def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
self.TestSehExceptions(EX_BINARY_OUTPUT)
def testCatchesSehExceptionsWithCxxExceptionsDisabled(self):
self.TestSehExceptions(BINARY_OUTPUT)
class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
"""Tests C++ exception-catching behavior.
Tests in this test case verify that:
* C++ exceptions are caught and logged as C++ (not SEH) exceptions
* Exception thrown affect the remainder of the test work flow in the
expected manner.
"""
def testCatchesCxxExceptionsInFixtureConstructor(self):
self.assert_('C++ exception with description '
'"Standard C++ exception" thrown '
'in the test fixture\'s constructor'
in EX_BINARY_OUTPUT)
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
'This failure belongs in this test only if '
'"CxxExceptionInConstructorTest" (no quotes) '
'appears on the same line as words "called unexpectedly"')
if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in
EX_BINARY_OUTPUT):
def testCatchesCxxExceptionsInFixtureDestructor(self):
self.assert_('C++ exception with description '
'"Standard C++ exception" thrown '
'in the test fixture\'s destructor'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() '
'called as expected.'
in EX_BINARY_OUTPUT)
def testCatchesCxxExceptionsInSetUpTestCase(self):
self.assert_('C++ exception with description "Standard C++ exception"'
' thrown in SetUpTestCase()'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTestCaseTest constructor '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTestCaseTest destructor '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTestCaseTest test body '
'called as expected.'
in EX_BINARY_OUTPUT)
def testCatchesCxxExceptionsInTearDownTestCase(self):
self.assert_('C++ exception with description "Standard C++ exception"'
' thrown in TearDownTestCase()'
in EX_BINARY_OUTPUT)
def testCatchesCxxExceptionsInSetUp(self):
self.assert_('C++ exception with description "Standard C++ exception"'
' thrown in SetUp()'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTest destructor '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInSetUpTest::TearDown() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
'This failure belongs in this test only if '
'"CxxExceptionInSetUpTest" (no quotes) '
'appears on the same line as words "called unexpectedly"')
def testCatchesCxxExceptionsInTearDown(self):
self.assert_('C++ exception with description "Standard C++ exception"'
' thrown in TearDown()'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInTearDownTest destructor '
'called as expected.'
in EX_BINARY_OUTPUT)
def testCatchesCxxExceptionsInTestBody(self):
self.assert_('C++ exception with description "Standard C++ exception"'
' thrown in the test body'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInTestBodyTest destructor '
'called as expected.'
in EX_BINARY_OUTPUT)
self.assert_('CxxExceptionInTestBodyTest::TearDown() '
'called as expected.'
in EX_BINARY_OUTPUT)
def testCatchesNonStdCxxExceptions(self):
self.assert_('Unknown C++ exception thrown in the test body'
in EX_BINARY_OUTPUT)
def testUnhandledCxxExceptionsAbortTheProgram(self):
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions
# cause tests to show pop-up windows there.
FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'
# By default, Google Test doesn't catch the exceptions.
uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
[EX_EXE_PATH,
NO_CATCH_EXCEPTIONS_FLAG,
FITLER_OUT_SEH_TESTS_FLAG],
env=environ).output
self.assert_('Unhandled C++ exception terminating the program'
in uncaught_exceptions_ex_binary_output)
self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)
if __name__ == '__main__':
gtest_test_utils.Main()
| gpl-2.0 |
alhashash/odoomrp-wip | mrp_production_project_estimated_cost/models/account_analytic_line.py | 17 | 1322 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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
import openerp.addons.decimal_precision as dp
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
estim_std_cost = fields.Float(string='Estimated Standard Cost',
digits=dp.get_precision('Product Price'))
estim_avg_cost = fields.Float(string='Estimated Average Cost',
digits=dp.get_precision('Product Price'))
| agpl-3.0 |
hisaharu/ryu | ryu/tests/unit/lib/test_ofp_pktinfilter.py | 27 | 3064 | # Copyright (C) 2013 Stratosphere Inc.
#
# 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.
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import unittest
import logging
import six
from nose.tools import *
from ryu.controller import ofp_event
from ryu.controller.handler import (
set_ev_cls,
MAIN_DISPATCHER,
)
from ryu.lib.packet import vlan, ethernet, ipv4
from ryu.lib.ofp_pktinfilter import packet_in_filter, RequiredTypeFilter
from ryu.lib import mac
from ryu.ofproto import ether, ofproto_v1_3, ofproto_v1_3_parser
from ryu.ofproto.ofproto_protocol import ProtocolDesc
LOG = logging.getLogger('test_pktinfilter')
class _PacketInFilterApp(object):
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
@packet_in_filter(RequiredTypeFilter, {'types': [
vlan.vlan,
]})
def packet_in_handler(self, ev):
return True
class Test_packet_in_filter(unittest.TestCase):
""" Test case for pktinfilter
"""
def setUp(self):
self.app = _PacketInFilterApp()
def tearDown(self):
pass
def test_pkt_in_filter_pass(self):
datapath = ProtocolDesc(version=ofproto_v1_3.OFP_VERSION)
e = ethernet.ethernet(mac.BROADCAST_STR,
mac.BROADCAST_STR,
ether.ETH_TYPE_8021Q)
v = vlan.vlan()
i = ipv4.ipv4()
pkt = (e / v / i)
pkt.serialize()
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=six.binary_type(pkt.data))
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(self.app.packet_in_handler(ev))
def test_pkt_in_filter_discard(self):
datapath = ProtocolDesc(version=ofproto_v1_3.OFP_VERSION)
e = ethernet.ethernet(mac.BROADCAST_STR,
mac.BROADCAST_STR,
ether.ETH_TYPE_IP)
i = ipv4.ipv4()
pkt = (e / i)
pkt.serialize()
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=six.binary_type(pkt.data))
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(not self.app.packet_in_handler(ev))
def test_pkt_in_filter_truncated(self):
datapath = ProtocolDesc(version=ofproto_v1_3.OFP_VERSION)
truncated_data = ''
pkt_in = ofproto_v1_3_parser.OFPPacketIn(datapath,
data=truncated_data)
ev = ofp_event.EventOFPPacketIn(pkt_in)
ok_(not self.app.packet_in_handler(ev))
| apache-2.0 |
sertac/django | django/contrib/gis/gdal/driver.py | 526 | 3260 | from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
from django.utils import six
from django.utils.encoding import force_bytes, force_text
class Driver(GDALBase):
"""
Wraps a GDAL/OGR Data Source Driver.
For more information, see the C API source code:
http://www.gdal.org/gdal_8h.html - http://www.gdal.org/ogr__api_8h.html
"""
# Case-insensitive aliases for some GDAL/OGR Drivers.
# For a complete list of original driver names see
# http://www.gdal.org/ogr_formats.html (vector)
# http://www.gdal.org/formats_list.html (raster)
_alias = {
# vector
'esri': 'ESRI Shapefile',
'shp': 'ESRI Shapefile',
'shape': 'ESRI Shapefile',
'tiger': 'TIGER',
'tiger/line': 'TIGER',
# raster
'tiff': 'GTiff',
'tif': 'GTiff',
'jpeg': 'JPEG',
'jpg': 'JPEG',
}
def __init__(self, dr_input):
"""
Initializes an GDAL/OGR driver on either a string or integer input.
"""
if isinstance(dr_input, six.string_types):
# If a string name of the driver was passed in
self.ensure_registered()
# Checking the alias dictionary (case-insensitive) to see if an
# alias exists for the given driver.
if dr_input.lower() in self._alias:
name = self._alias[dr_input.lower()]
else:
name = dr_input
# Attempting to get the GDAL/OGR driver by the string name.
for iface in (vcapi, rcapi):
driver = iface.get_driver_by_name(force_bytes(name))
if driver:
break
elif isinstance(dr_input, int):
self.ensure_registered()
for iface in (vcapi, rcapi):
driver = iface.get_driver(dr_input)
if driver:
break
elif isinstance(dr_input, c_void_p):
driver = dr_input
else:
raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input)))
# Making sure we get a valid pointer to the OGR Driver
if not driver:
raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input))
self.ptr = driver
def __str__(self):
return self.name
@classmethod
def ensure_registered(cls):
"""
Attempts to register all the data source drivers.
"""
# Only register all if the driver count is 0 (or else all drivers
# will be registered over and over again)
if not cls.driver_count():
vcapi.register_all()
rcapi.register_all()
@classmethod
def driver_count(cls):
"""
Returns the number of GDAL/OGR data source drivers registered.
"""
return vcapi.get_driver_count() + rcapi.get_driver_count()
@property
def name(self):
"""
Returns description/name string for this driver.
"""
return force_text(rcapi.get_driver_description(self.ptr))
| bsd-3-clause |
silly-wacky-3-town-toon/SOURCE-COD | Panda3D-1.10.0/python/Lib/platform.py | 43 | 53212 | #!/usr/bin/env python
""" This module tries to retrieve as much platform-identifying data as
possible. It makes this information available via function APIs.
If called from the command line, it prints the platform
information concatenated as single string to stdout. The output
format is useable as part of a filename.
"""
# This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
# If you find problems, please submit bug reports/patches via the
# Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
#
# Note: Please keep this module compatible to Python 1.5.2.
#
# Still needed:
# * more support for WinCE
# * support for MS-DOS (PythonDX ?)
# * support for Amiga and other still unsupported platforms running Python
# * support for additional Linux distributions
#
# Many thanks to all those who helped adding platform-specific
# checks (in no particular order):
#
# Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
# Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
#
# History:
#
# <see CVS and SVN checkin messages for history>
#
# 1.0.7 - added DEV_NULL
# 1.0.6 - added linux_distribution()
# 1.0.5 - fixed Java support to allow running the module on Jython
# 1.0.4 - added IronPython support
# 1.0.3 - added normalization of Windows system name
# 1.0.2 - added more Windows support
# 1.0.1 - reformatted to make doc.py happy
# 1.0.0 - reformatted a bit and checked into Python CVS
# 0.8.0 - added sys.version parser and various new access
# APIs (python_version(), python_compiler(), etc.)
# 0.7.2 - fixed architecture() to use sizeof(pointer) where available
# 0.7.1 - added support for Caldera OpenLinux
# 0.7.0 - some fixes for WinCE; untabified the source file
# 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
# vms_lib.getsyi() configured
# 0.6.1 - added code to prevent 'uname -p' on platforms which are
# known not to support it
# 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
# did some cleanup of the interfaces - some APIs have changed
# 0.5.5 - fixed another type in the MacOS code... should have
# used more coffee today ;-)
# 0.5.4 - fixed a few typos in the MacOS code
# 0.5.3 - added experimental MacOS support; added better popen()
# workarounds in _syscmd_ver() -- still not 100% elegant
# though
# 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
# return values (the system uname command tends to return
# 'unknown' instead of just leaving the field emtpy)
# 0.5.1 - included code for slackware dist; added exception handlers
# to cover up situations where platforms don't have os.popen
# (e.g. Mac) or fail on socket.gethostname(); fixed libc
# detection RE
# 0.5.0 - changed the API names referring to system commands to *syscmd*;
# added java_ver(); made syscmd_ver() a private
# API (was system_ver() in previous versions) -- use uname()
# instead; extended the win32_ver() to also return processor
# type information
# 0.4.0 - added win32_ver() and modified the platform() output for WinXX
# 0.3.4 - fixed a bug in _follow_symlinks()
# 0.3.3 - fixed popen() and "file" command invokation bugs
# 0.3.2 - added architecture() API and support for it in platform()
# 0.3.1 - fixed syscmd_ver() RE to support Windows NT
# 0.3.0 - added system alias support
# 0.2.3 - removed 'wince' again... oh well.
# 0.2.2 - added 'wince' to syscmd_ver() supported platforms
# 0.2.1 - added cache logic and changed the platform string format
# 0.2.0 - changed the API to use functions instead of module globals
# since some action take too long to be run on module import
# 0.1.0 - first release
#
# You can always get the latest version of this module at:
#
# http://www.egenix.com/files/python/platform.py
#
# If that URL should fail, try contacting the author.
__copyright__ = """
Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee or royalty is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation or portions thereof, including modifications,
that you make.
EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
"""
__version__ = '1.0.7'
import sys,string,os,re
### Globals & Constants
# Determine the platform's /dev/null device
try:
DEV_NULL = os.devnull
except AttributeError:
# os.devnull was added in Python 2.4, so emulate it for earlier
# Python versions
if sys.platform in ('dos','win32','win16','os2'):
# Use the old CP/M NUL as device name
DEV_NULL = 'NUL'
else:
# Standard Unix uses /dev/null
DEV_NULL = '/dev/null'
### Platform specific APIs
_libc_search = re.compile(r'(__libc_init)'
'|'
'(GLIBC_([0-9.]+))'
'|'
'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
def libc_ver(executable=sys.executable,lib='',version='',
chunksize=2048):
""" Tries to determine the libc version that the file executable
(which defaults to the Python interpreter) is linked against.
Returns a tuple of strings (lib,version) which default to the
given parameters in case the lookup fails.
Note that the function has intimate knowledge of how different
libc versions add symbols to the executable and thus is probably
only useable for executables compiled using gcc.
The file is read and scanned in chunks of chunksize bytes.
"""
if hasattr(os.path, 'realpath'):
# Python 2.2 introduced os.path.realpath(); it is used
# here to work around problems with Cygwin not being
# able to open symlinks for reading
executable = os.path.realpath(executable)
f = open(executable,'rb')
binary = f.read(chunksize)
pos = 0
while 1:
m = _libc_search.search(binary,pos)
if not m:
binary = f.read(chunksize)
if not binary:
break
pos = 0
continue
libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
if libcinit and not lib:
lib = 'libc'
elif glibc:
if lib != 'glibc':
lib = 'glibc'
version = glibcversion
elif glibcversion > version:
version = glibcversion
elif so:
if lib != 'glibc':
lib = 'libc'
if soversion and soversion > version:
version = soversion
if threads and version[-len(threads):] != threads:
version = version + threads
pos = m.end()
f.close()
return lib,version
def _dist_try_harder(distname,version,id):
""" Tries some special tricks to get the distribution
information in case the default method fails.
Currently supports older SuSE Linux, Caldera OpenLinux and
Slackware Linux distributions.
"""
if os.path.exists('/var/adm/inst-log/info'):
# SuSE Linux stores distribution information in that file
info = open('/var/adm/inst-log/info').readlines()
distname = 'SuSE'
for line in info:
tv = string.split(line)
if len(tv) == 2:
tag,value = tv
else:
continue
if tag == 'MIN_DIST_VERSION':
version = string.strip(value)
elif tag == 'DIST_IDENT':
values = string.split(value,'-')
id = values[2]
return distname,version,id
if os.path.exists('/etc/.installed'):
# Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
info = open('/etc/.installed').readlines()
for line in info:
pkg = string.split(line,'-')
if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
# XXX does Caldera support non Intel platforms ? If yes,
# where can we find the needed id ?
return 'OpenLinux',pkg[1],id
if os.path.isdir('/usr/lib/setup'):
# Check for slackware verson tag file (thanks to Greg Andruk)
verfiles = os.listdir('/usr/lib/setup')
for n in range(len(verfiles)-1, -1, -1):
if verfiles[n][:14] != 'slack-version-':
del verfiles[n]
if verfiles:
verfiles.sort()
distname = 'slackware'
version = verfiles[-1][14:]
return distname,version,id
return distname,version,id
_release_filename = re.compile(r'(\w+)[-_](release|version)')
_lsb_release_version = re.compile(r'(.+)'
' release '
'([\d.]+)'
'[^(]*(?:\((.+)\))?')
_release_version = re.compile(r'([^0-9]+)'
'(?: release )?'
'([\d.]+)'
'[^(]*(?:\((.+)\))?')
# See also http://www.novell.com/coolsolutions/feature/11251.html
# and http://linuxmafia.com/faq/Admin/release-files.html
# and http://data.linux-ntfs.org/rpm/whichrpm
# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
_supported_dists = (
'SuSE', 'debian', 'fedora', 'redhat', 'centos',
'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
'UnitedLinux', 'turbolinux')
def _parse_release_file(firstline):
# Default to empty 'version' and 'id' strings. Both defaults are used
# when 'firstline' is empty. 'id' defaults to empty when an id can not
# be deduced.
version = ''
id = ''
# Parse the first line
m = _lsb_release_version.match(firstline)
if m is not None:
# LSB format: "distro release x.x (codename)"
return tuple(m.groups())
# Pre-LSB format: "distro x.x (codename)"
m = _release_version.match(firstline)
if m is not None:
return tuple(m.groups())
# Unkown format... take the first two words
l = string.split(string.strip(firstline))
if l:
version = l[0]
if len(l) > 1:
id = l[1]
return '', version, id
def linux_distribution(distname='', version='', id='',
supported_dists=_supported_dists,
full_distribution_name=1):
""" Tries to determine the name of the Linux OS distribution name.
The function first looks for a distribution release file in
/etc and then reverts to _dist_try_harder() in case no
suitable files are found.
supported_dists may be given to define the set of Linux
distributions to look for. It defaults to a list of currently
supported Linux distributions identified by their release file
name.
If full_distribution_name is true (default), the full
distribution read from the OS is returned. Otherwise the short
name taken from supported_dists is used.
Returns a tuple (distname,version,id) which default to the
args given as parameters.
"""
try:
etc = os.listdir('/etc')
except os.error:
# Probably not a Unix system
return distname,version,id
etc.sort()
for file in etc:
m = _release_filename.match(file)
if m is not None:
_distname,dummy = m.groups()
if _distname in supported_dists:
distname = _distname
break
else:
return _dist_try_harder(distname,version,id)
# Read the first line
f = open('/etc/'+file, 'r')
firstline = f.readline()
f.close()
_distname, _version, _id = _parse_release_file(firstline)
if _distname and full_distribution_name:
distname = _distname
if _version:
version = _version
if _id:
id = _id
return distname, version, id
# To maintain backwards compatibility:
def dist(distname='',version='',id='',
supported_dists=_supported_dists):
""" Tries to determine the name of the Linux OS distribution name.
The function first looks for a distribution release file in
/etc and then reverts to _dist_try_harder() in case no
suitable files are found.
Returns a tuple (distname,version,id) which default to the
args given as parameters.
"""
return linux_distribution(distname, version, id,
supported_dists=supported_dists,
full_distribution_name=0)
class _popen:
""" Fairly portable (alternative) popen implementation.
This is mostly needed in case os.popen() is not available, or
doesn't work as advertised, e.g. in Win9X GUI programs like
PythonWin or IDLE.
Writing to the pipe is currently not supported.
"""
tmpfile = ''
pipe = None
bufsize = None
mode = 'r'
def __init__(self,cmd,mode='r',bufsize=None):
if mode != 'r':
raise ValueError,'popen()-emulation only supports read mode'
import tempfile
self.tmpfile = tmpfile = tempfile.mktemp()
os.system(cmd + ' > %s' % tmpfile)
self.pipe = open(tmpfile,'rb')
self.bufsize = bufsize
self.mode = mode
def read(self):
return self.pipe.read()
def readlines(self):
if self.bufsize is not None:
return self.pipe.readlines()
def close(self,
remove=os.unlink,error=os.error):
if self.pipe:
rc = self.pipe.close()
else:
rc = 255
if self.tmpfile:
try:
remove(self.tmpfile)
except error:
pass
return rc
# Alias
__del__ = close
def popen(cmd, mode='r', bufsize=None):
""" Portable popen() interface.
"""
# Find a working popen implementation preferring win32pipe.popen
# over os.popen over _popen
popen = None
if os.environ.get('OS','') == 'Windows_NT':
# On NT win32pipe should work; on Win9x it hangs due to bugs
# in the MS C lib (see MS KnowledgeBase article Q150956)
try:
import win32pipe
except ImportError:
pass
else:
popen = win32pipe.popen
if popen is None:
if hasattr(os,'popen'):
popen = os.popen
# Check whether it works... it doesn't in GUI programs
# on Windows platforms
if sys.platform == 'win32': # XXX Others too ?
try:
popen('')
except os.error:
popen = _popen
else:
popen = _popen
if bufsize is None:
return popen(cmd,mode)
else:
return popen(cmd,mode,bufsize)
def _norm_version(version, build=''):
""" Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel).
"""
l = string.split(version,'.')
if build:
l.append(build)
try:
ints = map(int,l)
except ValueError:
strings = l
else:
strings = map(str,ints)
version = string.join(strings[:3],'.')
return version
_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
'.*'
'\[.* ([\d.]+)\])')
# Examples of VER command output:
#
# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
# Windows XP: Microsoft Windows XP [Version 5.1.2600]
# Windows Vista: Microsoft Windows [Version 6.0.6002]
#
# Note that the "Version" string gets localized on different
# Windows versions.
def _syscmd_ver(system='', release='', version='',
supported_platforms=('win32','win16','dos','os2')):
""" Tries to figure out the OS version used and returns
a tuple (system,release,version).
It uses the "ver" shell command for this which is known
to exists on Windows, DOS and OS/2. XXX Others too ?
In case this fails, the given parameters are used as
defaults.
"""
if sys.platform not in supported_platforms:
return system,release,version
# Try some common cmd strings
for cmd in ('ver','command /c ver','cmd /c ver'):
try:
pipe = popen(cmd)
info = pipe.read()
if pipe.close():
raise os.error,'command failed'
# XXX How can I suppress shell errors from being written
# to stderr ?
except os.error,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
except IOError,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
else:
break
else:
return system,release,version
# Parse the output
info = string.strip(info)
m = _ver_output.match(info)
if m is not None:
system,release,version = m.groups()
# Strip trailing dots from version and release
if release[-1] == '.':
release = release[:-1]
if version[-1] == '.':
version = version[:-1]
# Normalize the version and build strings (eliminating additional
# zeros)
version = _norm_version(version)
return system,release,version
def _win32_getvalue(key,name,default=''):
""" Read a value for name from the registry key.
In case this fails, default is returned.
"""
try:
# Use win32api if available
from win32api import RegQueryValueEx
except ImportError:
# On Python 2.0 and later, emulate using _winreg
import _winreg
RegQueryValueEx = _winreg.QueryValueEx
try:
return RegQueryValueEx(key,name)
except:
return default
def win32_ver(release='',version='',csd='',ptype=''):
""" Get additional version information from the Windows Registry
and return a tuple (version,csd,ptype) referring to version
number, CSD level (service pack), and OS type (multi/single
processor).
As a hint: ptype returns 'Uniprocessor Free' on single
processor NT machines and 'Multiprocessor Free' on multi
processor machines. The 'Free' refers to the OS version being
free of debugging code. It could also state 'Checked' which
means the OS version uses debugging code, i.e. code that
checks arguments, ranges, etc. (Thomas Heller).
Note: this function works best with Mark Hammond's win32
package installed, but also on Python 2.3 and later. It
obviously only runs on Win32 compatible platforms.
"""
# XXX Is there any way to find out the processor type on WinXX ?
# XXX Is win32 available on Windows CE ?
#
# Adapted from code posted by Karl Putland to comp.lang.python.
#
# The mappings between reg. values and release names can be found
# here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
# Import the needed APIs
try:
import win32api
from win32api import RegQueryValueEx, RegOpenKeyEx, \
RegCloseKey, GetVersionEx
from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
except ImportError:
# Emulate the win32api module using Python APIs
try:
sys.getwindowsversion
except AttributeError:
# No emulation possible, so return the defaults...
return release,version,csd,ptype
else:
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
RegQueryValueEx = _winreg.QueryValueEx
RegOpenKeyEx = _winreg.OpenKeyEx
RegCloseKey = _winreg.CloseKey
HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
VER_PLATFORM_WIN32_WINDOWS = 1
VER_PLATFORM_WIN32_NT = 2
VER_NT_WORKSTATION = 1
VER_NT_SERVER = 3
REG_SZ = 1
# Find out the registry key and some general version infos
winver = GetVersionEx()
maj,min,buildno,plat,csd = winver
version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
if hasattr(winver, "service_pack"):
if winver.service_pack != "":
csd = 'SP%s' % winver.service_pack_major
else:
if csd[:13] == 'Service Pack ':
csd = 'SP' + csd[13:]
if plat == VER_PLATFORM_WIN32_WINDOWS:
regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
# Try to guess the release name
if maj == 4:
if min == 0:
release = '95'
elif min == 10:
release = '98'
elif min == 90:
release = 'Me'
else:
release = 'postMe'
elif maj == 5:
release = '2000'
elif plat == VER_PLATFORM_WIN32_NT:
regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
if maj <= 4:
release = 'NT'
elif maj == 5:
if min == 0:
release = '2000'
elif min == 1:
release = 'XP'
elif min == 2:
release = '2003Server'
else:
release = 'post2003'
elif maj == 6:
if hasattr(winver, "product_type"):
product_type = winver.product_type
else:
product_type = VER_NT_WORKSTATION
# Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
# or help from the registry, we cannot properly identify
# non-workstation versions.
try:
key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
name, type = RegQueryValueEx(key, "ProductName")
# Discard any type that isn't REG_SZ
if type == REG_SZ and name.find("Server") != -1:
product_type = VER_NT_SERVER
except WindowsError:
# Use default of VER_NT_WORKSTATION
pass
if min == 0:
if product_type == VER_NT_WORKSTATION:
release = 'Vista'
else:
release = '2008Server'
elif min == 1:
if product_type == VER_NT_WORKSTATION:
release = '7'
else:
release = '2008ServerR2'
elif min == 2:
if product_type == VER_NT_WORKSTATION:
release = '8'
else:
release = '2012Server'
else:
release = 'post2012Server'
else:
if not release:
# E.g. Win3.1 with win32s
release = '%i.%i' % (maj,min)
return release,version,csd,ptype
# Open the registry key
try:
keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
# Get a value to make sure the key exists...
RegQueryValueEx(keyCurVer, 'SystemRoot')
except:
return release,version,csd,ptype
# Parse values
#subversion = _win32_getvalue(keyCurVer,
# 'SubVersionNumber',
# ('',1))[0]
#if subversion:
# release = release + subversion # 95a, 95b, etc.
build = _win32_getvalue(keyCurVer,
'CurrentBuildNumber',
('',1))[0]
ptype = _win32_getvalue(keyCurVer,
'CurrentType',
(ptype,1))[0]
# Normalize version
version = _norm_version(version,build)
# Close key
RegCloseKey(keyCurVer)
return release,version,csd,ptype
def _mac_ver_lookup(selectors,default=None):
from gestalt import gestalt
import MacOS
l = []
append = l.append
for selector in selectors:
try:
append(gestalt(selector))
except (RuntimeError, MacOS.Error):
append(default)
return l
def _bcd2str(bcd):
return hex(bcd)[2:]
def _mac_ver_gestalt():
"""
Thanks to Mark R. Levinson for mailing documentation links and
code examples for this function. Documentation for the
gestalt() API is available online at:
http://www.rgaros.nl/gestalt/
"""
# Check whether the version info module is available
try:
import gestalt
import MacOS
except ImportError:
return None
# Get the infos
sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
# Decode the infos
if sysv:
major = (sysv & 0xFF00) >> 8
minor = (sysv & 0x00F0) >> 4
patch = (sysv & 0x000F)
if (major, minor) >= (10, 4):
# the 'sysv' gestald cannot return patchlevels
# higher than 9. Apple introduced 3 new
# gestalt codes in 10.4 to deal with this
# issue (needed because patch levels can
# run higher than 9, such as 10.4.11)
major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
release = '%i.%i.%i' %(major, minor, patch)
else:
release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
if sysa:
machine = {0x1: '68k',
0x2: 'PowerPC',
0xa: 'i386'}.get(sysa,'')
versioninfo=('', '', '')
return release,versioninfo,machine
def _mac_ver_xml():
fn = '/System/Library/CoreServices/SystemVersion.plist'
if not os.path.exists(fn):
return None
try:
import plistlib
except ImportError:
return None
pl = plistlib.readPlist(fn)
release = pl['ProductVersion']
versioninfo=('', '', '')
machine = os.uname()[4]
if machine in ('ppc', 'Power Macintosh'):
# for compatibility with the gestalt based code
machine = 'PowerPC'
return release,versioninfo,machine
def mac_ver(release='',versioninfo=('','',''),machine=''):
""" Get MacOS version information and return it as tuple (release,
versioninfo, machine) with versioninfo being a tuple (version,
dev_stage, non_release_version).
Entries which cannot be determined are set to the paramter values
which default to ''. All tuple entries are strings.
"""
# First try reading the information from an XML file which should
# always be present
info = _mac_ver_xml()
if info is not None:
return info
# If that doesn't work for some reason fall back to reading the
# information using gestalt calls.
info = _mac_ver_gestalt()
if info is not None:
return info
# If that also doesn't work return the default values
return release,versioninfo,machine
def _java_getprop(name,default):
from java.lang import System
try:
value = System.getProperty(name)
if value is None:
return default
return value
except AttributeError:
return default
def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
""" Version interface for Jython.
Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
tuple (os_name,os_version,os_arch).
Values which cannot be determined are set to the defaults
given as parameters (which all default to '').
"""
# Import the needed APIs
try:
import java.lang
except ImportError:
return release,vendor,vminfo,osinfo
vendor = _java_getprop('java.vendor', vendor)
release = _java_getprop('java.version', release)
vm_name, vm_release, vm_vendor = vminfo
vm_name = _java_getprop('java.vm.name', vm_name)
vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
vm_release = _java_getprop('java.vm.version', vm_release)
vminfo = vm_name, vm_release, vm_vendor
os_name, os_version, os_arch = osinfo
os_arch = _java_getprop('java.os.arch', os_arch)
os_name = _java_getprop('java.os.name', os_name)
os_version = _java_getprop('java.os.version', os_version)
osinfo = os_name, os_version, os_arch
return release, vendor, vminfo, osinfo
### System name aliasing
def system_alias(system,release,version):
""" Returns (system,release,version) aliased to common
marketing names used for some systems.
It also does some reordering of the information in some cases
where it would otherwise cause confusion.
"""
if system == 'Rhapsody':
# Apple's BSD derivative
# XXX How can we determine the marketing release number ?
return 'MacOS X Server',system+release,version
elif system == 'SunOS':
# Sun's OS
if release < '5':
# These releases use the old name SunOS
return system,release,version
# Modify release (marketing release = SunOS release - 3)
l = string.split(release,'.')
if l:
try:
major = int(l[0])
except ValueError:
pass
else:
major = major - 3
l[0] = str(major)
release = string.join(l,'.')
if release < '6':
system = 'Solaris'
else:
# XXX Whatever the new SunOS marketing name is...
system = 'Solaris'
elif system == 'IRIX64':
# IRIX reports IRIX64 on platforms with 64-bit support; yet it
# is really a version and not a different platform, since 32-bit
# apps are also supported..
system = 'IRIX'
if version:
version = version + ' (64bit)'
else:
version = '64bit'
elif system in ('win32','win16'):
# In case one of the other tricks
system = 'Windows'
return system,release,version
### Various internal helpers
def _platform(*args):
""" Helper to format the platform string in a filename
compatible format e.g. "system-version-machine".
"""
# Format the platform string
platform = string.join(
map(string.strip,
filter(len, args)),
'-')
# Cleanup some possible filename obstacles...
replace = string.replace
platform = replace(platform,' ','_')
platform = replace(platform,'/','-')
platform = replace(platform,'\\','-')
platform = replace(platform,':','-')
platform = replace(platform,';','-')
platform = replace(platform,'"','-')
platform = replace(platform,'(','-')
platform = replace(platform,')','-')
# No need to report 'unknown' information...
platform = replace(platform,'unknown','')
# Fold '--'s and remove trailing '-'
while 1:
cleaned = replace(platform,'--','-')
if cleaned == platform:
break
platform = cleaned
while platform[-1] == '-':
platform = platform[:-1]
return platform
def _node(default=''):
""" Helper to determine the node name of this machine.
"""
try:
import socket
except ImportError:
# No sockets...
return default
try:
return socket.gethostname()
except socket.error:
# Still not working...
return default
# os.path.abspath is new in Python 1.5.2:
if not hasattr(os.path,'abspath'):
def _abspath(path,
isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
normpath=os.path.normpath):
if not isabs(path):
path = join(getcwd(), path)
return normpath(path)
else:
_abspath = os.path.abspath
def _follow_symlinks(filepath):
""" In case filepath is a symlink, follow it until a
real file is reached.
"""
filepath = _abspath(filepath)
while os.path.islink(filepath):
filepath = os.path.normpath(
os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
return filepath
def _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = string.strip(f.read())
rc = f.close()
if not output or rc:
return default
else:
return output
def _syscmd_file(target,default=''):
""" Interface to the system's file command.
The function uses the -b option of the file command to have it
ommit the filename in its output and if possible the -L option
to have the command follow symlinks. It returns default in
case the command should fail.
"""
# We do the import here to avoid a bootstrap issue.
# See c73b90b6dadd changeset.
#
# [..]
# ranlib libpython2.7.a
# gcc -o python \
# Modules/python.o \
# libpython2.7.a -lsocket -lnsl -ldl -lm
# Traceback (most recent call last):
# File "./setup.py", line 8, in <module>
# from platform import machine as platform_machine
# File "[..]/build/Lib/platform.py", line 116, in <module>
# import sys,string,os,re,subprocess
# File "[..]/build/Lib/subprocess.py", line 429, in <module>
# import select
# ImportError: No module named select
import subprocess
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
target = _follow_symlinks(target)
try:
proc = subprocess.Popen(['file', target],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except (AttributeError,os.error):
return default
output = proc.communicate()[0]
rc = proc.wait()
if not output or rc:
return default
else:
return output
### Information about the used architecture
# Default values for architecture; non-empty strings override the
# defaults given as parameters
_default_architecture = {
'win32': ('','WindowsPE'),
'win16': ('','Windows'),
'dos': ('','MSDOS'),
}
_architecture_split = re.compile(r'[\s,]').split
def architecture(executable=sys.executable,bits='',linkage=''):
""" Queries the given executable (defaults to the Python interpreter
binary) for various architecture information.
Returns a tuple (bits,linkage) which contains information about
the bit architecture and the linkage format used for the
executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the
parameter presets. If bits is given as '', the sizeof(pointer)
(or sizeof(long) on Python version < 1.5.2) is used as
indicator for the supported pointer size.
The function relies on the system's "file" command to do the
actual work. This is available on most if not all Unix
platforms. On some non-Unix platforms where the "file" command
does not exist and the executable is set to the Python interpreter
binary defaults from _default_architecture are used.
"""
# Use the sizeof(pointer) as default number of bits if nothing
# else is given as default.
if not bits:
import struct
try:
size = struct.calcsize('P')
except struct.error:
# Older installations can only query longs
size = struct.calcsize('l')
bits = str(size*8) + 'bit'
# Get data from the 'file' system command
if executable:
output = _syscmd_file(executable, '')
else:
output = ''
if not output and \
executable == sys.executable:
# "file" command did not return anything; we'll try to provide
# some sensible defaults then...
if sys.platform in _default_architecture:
b, l = _default_architecture[sys.platform]
if b:
bits = b
if l:
linkage = l
return bits, linkage
# Split the output into a list of strings omitting the filename
fileout = _architecture_split(output)[1:]
if 'executable' not in fileout:
# Format not supported
return bits,linkage
# Bits
if '32-bit' in fileout:
bits = '32bit'
elif 'N32' in fileout:
# On Irix only
bits = 'n32bit'
elif '64-bit' in fileout:
bits = '64bit'
# Linkage
if 'ELF' in fileout:
linkage = 'ELF'
elif 'PE' in fileout:
# E.g. Windows uses this format
if 'Windows' in fileout:
linkage = 'WindowsPE'
else:
linkage = 'PE'
elif 'COFF' in fileout:
linkage = 'COFF'
elif 'MS-DOS' in fileout:
linkage = 'MSDOS'
else:
# XXX the A.OUT format also falls under this class...
pass
return bits,linkage
### Portable uname() interface
_uname_cache = None
def uname():
""" Fairly portable uname interface. Returns a tuple
of strings (system,node,release,version,machine,processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
"""
global _uname_cache
no_os_uname = 0
if _uname_cache is not None:
return _uname_cache
processor = ''
# Get some infos from the builtin os.uname API...
try:
system,node,release,version,machine = os.uname()
except AttributeError:
no_os_uname = 1
if no_os_uname or not filter(None, (system, node, release, version, machine)):
# Hmm, no there is either no uname or uname has returned
#'unknowns'... we'll have to poke around the system then.
if no_os_uname:
system = sys.platform
release = ''
version = ''
node = _node()
machine = ''
use_syscmd_ver = 1
# Try win32_ver() on win32 platforms
if system == 'win32':
release,version,csd,ptype = win32_ver()
if release and version:
use_syscmd_ver = 0
# Try to use the PROCESSOR_* environment variables
# available on Win XP and later; see
# http://support.microsoft.com/kb/888731 and
# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
if not machine:
# WOW64 processes mask the native architecture
if "PROCESSOR_ARCHITEW6432" in os.environ:
machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
else:
machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
if not processor:
processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
# Try the 'ver' system command available on some
# platforms
if use_syscmd_ver:
system,release,version = _syscmd_ver(system)
# Normalize system to what win32_ver() normally returns
# (_syscmd_ver() tends to return the vendor name as well)
if system == 'Microsoft Windows':
system = 'Windows'
elif system == 'Microsoft' and release == 'Windows':
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system = 'Windows'
if '6.0' == version[:3]:
release = 'Vista'
else:
release = ''
# In case we still don't know anything useful, we'll try to
# help ourselves
if system in ('win32','win16'):
if not version:
if system == 'win32':
version = '32bit'
else:
version = '16bit'
system = 'Windows'
elif system[:4] == 'java':
release,vendor,vminfo,osinfo = java_ver()
system = 'Java'
version = string.join(vminfo,', ')
if not version:
version = vendor
# System specific extensions
if system == 'OpenVMS':
# OpenVMS seems to have release and version mixed up
if not release or release == '0':
release = version
version = ''
# Get processor information
try:
import vms_lib
except ImportError:
pass
else:
csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
if (cpu_number >= 128):
processor = 'Alpha'
else:
processor = 'VAX'
if not processor:
# Get processor information from the uname system command
processor = _syscmd_uname('-p','')
#If any unknowns still exist, replace them with ''s, which are more portable
if system == 'unknown':
system = ''
if node == 'unknown':
node = ''
if release == 'unknown':
release = ''
if version == 'unknown':
version = ''
if machine == 'unknown':
machine = ''
if processor == 'unknown':
processor = ''
# normalize name
if system == 'Microsoft' and release == 'Windows':
system = 'Windows'
release = 'Vista'
_uname_cache = system,node,release,version,machine,processor
return _uname_cache
### Direct interfaces to some of the uname() return values
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0]
def node():
""" Returns the computer's network name (which may not be fully
qualified)
An empty string is returned if the value cannot be determined.
"""
return uname()[1]
def release():
""" Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined.
"""
return uname()[2]
def version():
""" Returns the system's release version, e.g. '#3 on degas'
An empty string is returned if the value cannot be determined.
"""
return uname()[3]
def machine():
""" Returns the machine type, e.g. 'i386'
An empty string is returned if the value cannot be determined.
"""
return uname()[4]
def processor():
""" Returns the (true) processor name, e.g. 'amdk6'
An empty string is returned if the value cannot be
determined. Note that many platforms do not provide this
information or simply return the same value as for machine(),
e.g. NetBSD does this.
"""
return uname()[5]
### Various APIs for extracting information from sys.version
_sys_version_parser = re.compile(
r'([\w.+]+)\s*'
'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
'\[([^\]]+)\]?')
_ironpython_sys_version_parser = re.compile(
r'IronPython\s*'
'([\d\.]+)'
'(?: \(([\d\.]+)\))?'
' on (.NET [\d\.]+)')
_pypy_sys_version_parser = re.compile(
r'([\w.+]+)\s*'
'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
'\[PyPy [^\]]+\]?')
_sys_version_cache = {}
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementation name, version, branch,
revision, build number, build date/time as string and the compiler
identification string.
Note that unlike the Python sys.version, the returned value
for the Python version will always include the patchlevel (it
defaults to '.0').
The function returns empty strings for tuple entries that
cannot be determined.
sys_version may be given to parse an alternative version
string, e.g. if the version was read from a different Python
interpreter.
"""
# Get the Python version
if sys_version is None:
sys_version = sys.version
# Try the cache first
result = _sys_version_cache.get(sys_version, None)
if result is not None:
return result
# Parse it
if sys_version[:10] == 'IronPython':
# IronPython
name = 'IronPython'
match = _ironpython_sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse IronPython sys.version: %s' %
repr(sys_version))
version, alt_version, compiler = match.groups()
buildno = ''
builddate = ''
elif sys.platform[:4] == 'java':
# Jython
name = 'Jython'
match = _sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse Jython sys.version: %s' %
repr(sys_version))
version, buildno, builddate, buildtime, _ = match.groups()
compiler = sys.platform
elif "PyPy" in sys_version:
# PyPy
name = "PyPy"
match = _pypy_sys_version_parser.match(sys_version)
if match is None:
raise ValueError("failed to parse PyPy sys.version: %s" %
repr(sys_version))
version, buildno, builddate, buildtime = match.groups()
compiler = ""
else:
# CPython
match = _sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse CPython sys.version: %s' %
repr(sys_version))
version, buildno, builddate, buildtime, compiler = \
match.groups()
name = 'CPython'
builddate = builddate + ' ' + buildtime
if hasattr(sys, 'subversion'):
# sys.subversion was added in Python 2.5
_, branch, revision = sys.subversion
else:
branch = ''
revision = ''
# Add the patchlevel version if missing
l = string.split(version, '.')
if len(l) == 2:
l.append('0')
version = string.join(l, '.')
# Build and cache the result
result = (name, version, branch, revision, buildno, builddate, compiler)
_sys_version_cache[sys_version] = result
return result
def python_implementation():
""" Returns a string identifying the Python implementation.
Currently, the following implementations are identified:
'CPython' (C implementation of Python),
'IronPython' (.NET implementation of Python),
'Jython' (Java implementation of Python),
'PyPy' (Python implementation of Python).
"""
return _sys_version()[0]
def python_version():
""" Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return _sys_version()[1]
def python_version_tuple():
""" Returns the Python version as tuple (major, minor, patchlevel)
of strings.
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return tuple(string.split(_sys_version()[1], '.'))
def python_branch():
""" Returns a string identifying the Python implementation
branch.
For CPython this is the Subversion branch from which the
Python binary was built.
If not available, an empty string is returned.
"""
return _sys_version()[2]
def python_revision():
""" Returns a string identifying the Python implementation
revision.
For CPython this is the Subversion revision from which the
Python binary was built.
If not available, an empty string is returned.
"""
return _sys_version()[3]
def python_build():
""" Returns a tuple (buildno, builddate) stating the Python
build number and date as strings.
"""
return _sys_version()[4:6]
def python_compiler():
""" Returns a string identifying the compiler used for compiling
Python.
"""
return _sys_version()[6]
### The Opus Magnum of platform strings :-)
_platform_cache = {}
def platform(aliased=0, terse=0):
""" Returns a single string identifying the underlying platform
with as much useful information as possible (but no more :).
The output is intended to be human readable rather than
machine parseable. It may look different on different
platforms and this is intended.
If "aliased" is true, the function will use aliases for
various platforms that report system names which differ from
their common names, e.g. SunOS will be reported as
Solaris. The system_alias() function is used to implement
this.
Setting terse to true causes the function to return only the
absolute minimum information needed to identify the platform.
"""
result = _platform_cache.get((aliased, terse), None)
if result is not None:
return result
# Get uname information and then apply platform specific cosmetics
# to it...
system,node,release,version,machine,processor = uname()
if machine == processor:
processor = ''
if aliased:
system,release,version = system_alias(system,release,version)
if system == 'Windows':
# MS platforms
rel,vers,csd,ptype = win32_ver(version)
if terse:
platform = _platform(system,release)
else:
platform = _platform(system,release,version,csd)
elif system in ('Linux',):
# Linux based systems
distname,distversion,distid = dist('')
if distname and not terse:
platform = _platform(system,release,machine,processor,
'with',
distname,distversion,distid)
else:
# If the distribution name is unknown check for libc vs. glibc
libcname,libcversion = libc_ver(sys.executable)
platform = _platform(system,release,machine,processor,
'with',
libcname+libcversion)
elif system == 'Java':
# Java platforms
r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
if terse or not os_name:
platform = _platform(system,release,version)
else:
platform = _platform(system,release,version,
'on',
os_name,os_version,os_arch)
elif system == 'MacOS':
# MacOS platforms
if terse:
platform = _platform(system,release)
else:
platform = _platform(system,release,machine)
else:
# Generic handler
if terse:
platform = _platform(system,release)
else:
bits,linkage = architecture(sys.executable)
platform = _platform(system,release,machine,processor,bits,linkage)
_platform_cache[(aliased, terse)] = platform
return platform
### Command line interface
if __name__ == '__main__':
# Default is to print the aliased verbose platform string
terse = ('terse' in sys.argv or '--terse' in sys.argv)
aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
print platform(aliased,terse)
sys.exit(0)
| apache-2.0 |
brchiu/tensorflow | tensorflow/compiler/tests/bucketize_op_test.py | 22 | 3002 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for bucketize_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.compiler.tests import xla_test
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class BucketizationOpTest(xla_test.XLATestCase):
def testInt(self):
with self.cached_session() as sess:
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
op = math_ops._bucketize(p, boundaries=[0, 3, 8, 11])
expected_out = [0, 1, 1, 2, 2, 3, 3, 4, 4]
self.assertAllEqual(expected_out,
sess.run(op, {p: [-5, 0, 2, 3, 5, 8, 10, 11, 12]}))
def testFloat(self):
with self.cached_session() as sess:
p = array_ops.placeholder(dtypes.float32)
with self.test_scope():
op = math_ops._bucketize(p, boundaries=[0., 3., 8., 11.])
expected_out = [0, 1, 1, 2, 2, 3, 3, 4, 4]
self.assertAllEqual(
expected_out,
sess.run(op, {p: [-5., 0., 2., 3., 5., 8., 10., 11., 12.]}))
def test2DInput(self):
with self.cached_session() as sess:
p = array_ops.placeholder(dtypes.float32)
with self.test_scope():
op = math_ops._bucketize(p, boundaries=[0, 3, 8, 11])
expected_out = [[0, 1, 1, 2, 2], [3, 3, 4, 4, 1]]
self.assertAllEqual(
expected_out, sess.run(op,
{p: [[-5, 0, 2, 3, 5], [8, 10, 11, 12, 0]]}))
def testInvalidBoundariesOrder(self):
with self.cached_session() as sess:
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
op = math_ops._bucketize(p, boundaries=[0, 8, 3, 11])
with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,
"Expected sorted boundaries"):
sess.run(op, {p: [-5, 0]})
def testBoundariesNotList(self):
with self.cached_session():
with self.assertRaisesRegexp(TypeError, "Expected list.*"):
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
math_ops._bucketize(p, boundaries=0)
if __name__ == "__main__":
test.main()
| apache-2.0 |
LePastis/pyload | module/plugins/accounts/QuickshareCz.py | 6 | 1304 | # -*- coding: utf-8 -*-
import re
from module.plugins.internal.Account import Account
class QuickshareCz(Account):
__name__ = "QuickshareCz"
__type__ = "account"
__version__ = "0.05"
__status__ = "testing"
__description__ = """Quickshare.cz account plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
TRAFFIC_LEFT_PATTERN = r'Stav kreditu: <strong>(.+?)</strong>'
def parse_info(self, user, password, data, req):
html = self.load("http://www.quickshare.cz/premium")
m = re.search(self.TRAFFIC_LEFT_PATTERN, html)
if m:
trafficleft = self.parse_traffic(m.group(1))
premium = True if trafficleft else False
else:
trafficleft = None
premium = False
return {'validuntil': -1, 'trafficleft': trafficleft, 'premium': premium}
def login(self, user, password, data, req):
html = self.load('http://www.quickshare.cz/html/prihlaseni_process.php',
post={'akce' : u'Přihlásit',
'heslo': password,
'jmeno': user})
if u'>Takový uživatel neexistuje.<' in html or u'>Špatné heslo.<' in html:
self.login_fail()
| gpl-3.0 |
chaffra/sympy | sympy/assumptions/tests/test_context.py | 126 | 1153 | from sympy.assumptions import ask, Q
from sympy.assumptions.assume import assuming, global_assumptions
from sympy.abc import x, y
def test_assuming():
with assuming(Q.integer(x)):
assert ask(Q.integer(x))
assert not ask(Q.integer(x))
def test_assuming_nested():
assert not ask(Q.integer(x))
assert not ask(Q.integer(y))
with assuming(Q.integer(x)):
assert ask(Q.integer(x))
assert not ask(Q.integer(y))
with assuming(Q.integer(y)):
assert ask(Q.integer(x))
assert ask(Q.integer(y))
assert ask(Q.integer(x))
assert not ask(Q.integer(y))
assert not ask(Q.integer(x))
assert not ask(Q.integer(y))
def test_finally():
try:
with assuming(Q.integer(x)):
1/0
except ZeroDivisionError:
pass
assert not ask(Q.integer(x))
def test_remove_safe():
global_assumptions.add(Q.integer(x))
with assuming():
assert ask(Q.integer(x))
global_assumptions.remove(Q.integer(x))
assert not ask(Q.integer(x))
assert ask(Q.integer(x))
global_assumptions.clear() # for the benefit of other tests
| bsd-3-clause |
kawasaki2013/python-for-android-x86 | python3-alpha/python3-src/Lib/test/buffer_tests.py | 59 | 10581 | # Tests that work for both bytes and buffer objects.
# See PEP 3137.
import struct
import sys
class MixinBytesBufferCommonTests(object):
"""Tests that work for both bytes and buffer objects.
See PEP 3137.
"""
def marshal(self, x):
"""Convert x into the appropriate type for these tests."""
raise RuntimeError('test class must provide a marshal method')
def test_islower(self):
self.assertFalse(self.marshal(b'').islower())
self.assertTrue(self.marshal(b'a').islower())
self.assertFalse(self.marshal(b'A').islower())
self.assertFalse(self.marshal(b'\n').islower())
self.assertTrue(self.marshal(b'abc').islower())
self.assertFalse(self.marshal(b'aBc').islower())
self.assertTrue(self.marshal(b'abc\n').islower())
self.assertRaises(TypeError, self.marshal(b'abc').islower, 42)
def test_isupper(self):
self.assertFalse(self.marshal(b'').isupper())
self.assertFalse(self.marshal(b'a').isupper())
self.assertTrue(self.marshal(b'A').isupper())
self.assertFalse(self.marshal(b'\n').isupper())
self.assertTrue(self.marshal(b'ABC').isupper())
self.assertFalse(self.marshal(b'AbC').isupper())
self.assertTrue(self.marshal(b'ABC\n').isupper())
self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42)
def test_istitle(self):
self.assertFalse(self.marshal(b'').istitle())
self.assertFalse(self.marshal(b'a').istitle())
self.assertTrue(self.marshal(b'A').istitle())
self.assertFalse(self.marshal(b'\n').istitle())
self.assertTrue(self.marshal(b'A Titlecased Line').istitle())
self.assertTrue(self.marshal(b'A\nTitlecased Line').istitle())
self.assertTrue(self.marshal(b'A Titlecased, Line').istitle())
self.assertFalse(self.marshal(b'Not a capitalized String').istitle())
self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle())
self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle())
self.assertFalse(self.marshal(b'NOT').istitle())
self.assertRaises(TypeError, self.marshal(b'abc').istitle, 42)
def test_isspace(self):
self.assertFalse(self.marshal(b'').isspace())
self.assertFalse(self.marshal(b'a').isspace())
self.assertTrue(self.marshal(b' ').isspace())
self.assertTrue(self.marshal(b'\t').isspace())
self.assertTrue(self.marshal(b'\r').isspace())
self.assertTrue(self.marshal(b'\n').isspace())
self.assertTrue(self.marshal(b' \t\r\n').isspace())
self.assertFalse(self.marshal(b' \t\r\na').isspace())
self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42)
def test_isalpha(self):
self.assertFalse(self.marshal(b'').isalpha())
self.assertTrue(self.marshal(b'a').isalpha())
self.assertTrue(self.marshal(b'A').isalpha())
self.assertFalse(self.marshal(b'\n').isalpha())
self.assertTrue(self.marshal(b'abc').isalpha())
self.assertFalse(self.marshal(b'aBc123').isalpha())
self.assertFalse(self.marshal(b'abc\n').isalpha())
self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42)
def test_isalnum(self):
self.assertFalse(self.marshal(b'').isalnum())
self.assertTrue(self.marshal(b'a').isalnum())
self.assertTrue(self.marshal(b'A').isalnum())
self.assertFalse(self.marshal(b'\n').isalnum())
self.assertTrue(self.marshal(b'123abc456').isalnum())
self.assertTrue(self.marshal(b'a1b3c').isalnum())
self.assertFalse(self.marshal(b'aBc000 ').isalnum())
self.assertFalse(self.marshal(b'abc\n').isalnum())
self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42)
def test_isdigit(self):
self.assertFalse(self.marshal(b'').isdigit())
self.assertFalse(self.marshal(b'a').isdigit())
self.assertTrue(self.marshal(b'0').isdigit())
self.assertTrue(self.marshal(b'0123456789').isdigit())
self.assertFalse(self.marshal(b'0123456789a').isdigit())
self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42)
def test_lower(self):
self.assertEqual(b'hello', self.marshal(b'HeLLo').lower())
self.assertEqual(b'hello', self.marshal(b'hello').lower())
self.assertRaises(TypeError, self.marshal(b'hello').lower, 42)
def test_upper(self):
self.assertEqual(b'HELLO', self.marshal(b'HeLLo').upper())
self.assertEqual(b'HELLO', self.marshal(b'HELLO').upper())
self.assertRaises(TypeError, self.marshal(b'hello').upper, 42)
def test_capitalize(self):
self.assertEqual(b' hello ', self.marshal(b' hello ').capitalize())
self.assertEqual(b'Hello ', self.marshal(b'Hello ').capitalize())
self.assertEqual(b'Hello ', self.marshal(b'hello ').capitalize())
self.assertEqual(b'Aaaa', self.marshal(b'aaaa').capitalize())
self.assertEqual(b'Aaaa', self.marshal(b'AaAa').capitalize())
self.assertRaises(TypeError, self.marshal(b'hello').capitalize, 42)
def test_ljust(self):
self.assertEqual(b'abc ', self.marshal(b'abc').ljust(10))
self.assertEqual(b'abc ', self.marshal(b'abc').ljust(6))
self.assertEqual(b'abc', self.marshal(b'abc').ljust(3))
self.assertEqual(b'abc', self.marshal(b'abc').ljust(2))
self.assertEqual(b'abc*******', self.marshal(b'abc').ljust(10, b'*'))
self.assertRaises(TypeError, self.marshal(b'abc').ljust)
def test_rjust(self):
self.assertEqual(b' abc', self.marshal(b'abc').rjust(10))
self.assertEqual(b' abc', self.marshal(b'abc').rjust(6))
self.assertEqual(b'abc', self.marshal(b'abc').rjust(3))
self.assertEqual(b'abc', self.marshal(b'abc').rjust(2))
self.assertEqual(b'*******abc', self.marshal(b'abc').rjust(10, b'*'))
self.assertRaises(TypeError, self.marshal(b'abc').rjust)
def test_center(self):
self.assertEqual(b' abc ', self.marshal(b'abc').center(10))
self.assertEqual(b' abc ', self.marshal(b'abc').center(6))
self.assertEqual(b'abc', self.marshal(b'abc').center(3))
self.assertEqual(b'abc', self.marshal(b'abc').center(2))
self.assertEqual(b'***abc****', self.marshal(b'abc').center(10, b'*'))
self.assertRaises(TypeError, self.marshal(b'abc').center)
def test_swapcase(self):
self.assertEqual(b'hEllO CoMPuTErS',
self.marshal(b'HeLLo cOmpUteRs').swapcase())
self.assertRaises(TypeError, self.marshal(b'hello').swapcase, 42)
def test_zfill(self):
self.assertEqual(b'123', self.marshal(b'123').zfill(2))
self.assertEqual(b'123', self.marshal(b'123').zfill(3))
self.assertEqual(b'0123', self.marshal(b'123').zfill(4))
self.assertEqual(b'+123', self.marshal(b'+123').zfill(3))
self.assertEqual(b'+123', self.marshal(b'+123').zfill(4))
self.assertEqual(b'+0123', self.marshal(b'+123').zfill(5))
self.assertEqual(b'-123', self.marshal(b'-123').zfill(3))
self.assertEqual(b'-123', self.marshal(b'-123').zfill(4))
self.assertEqual(b'-0123', self.marshal(b'-123').zfill(5))
self.assertEqual(b'000', self.marshal(b'').zfill(3))
self.assertEqual(b'34', self.marshal(b'34').zfill(1))
self.assertEqual(b'0034', self.marshal(b'34').zfill(4))
self.assertRaises(TypeError, self.marshal(b'123').zfill)
def test_expandtabs(self):
self.assertEqual(b'abc\rab def\ng hi',
self.marshal(b'abc\rab\tdef\ng\thi').expandtabs())
self.assertEqual(b'abc\rab def\ng hi',
self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8))
self.assertEqual(b'abc\rab def\ng hi',
self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(4))
self.assertEqual(b'abc\r\nab def\ng hi',
self.marshal(b'abc\r\nab\tdef\ng\thi').expandtabs(4))
self.assertEqual(b'abc\rab def\ng hi',
self.marshal(b'abc\rab\tdef\ng\thi').expandtabs())
self.assertEqual(b'abc\rab def\ng hi',
self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8))
self.assertEqual(b'abc\r\nab\r\ndef\ng\r\nhi',
self.marshal(b'abc\r\nab\r\ndef\ng\r\nhi').expandtabs(4))
self.assertEqual(b' a\n b', self.marshal(b' \ta\n\tb').expandtabs(1))
self.assertRaises(TypeError, self.marshal(b'hello').expandtabs, 42, 42)
# This test is only valid when sizeof(int) == sizeof(void*) == 4.
if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
self.assertRaises(OverflowError,
self.marshal(b'\ta\n\tb').expandtabs, sys.maxsize)
def test_title(self):
self.assertEqual(b' Hello ', self.marshal(b' hello ').title())
self.assertEqual(b'Hello ', self.marshal(b'hello ').title())
self.assertEqual(b'Hello ', self.marshal(b'Hello ').title())
self.assertEqual(b'Format This As Title String',
self.marshal(b'fOrMaT thIs aS titLe String').title())
self.assertEqual(b'Format,This-As*Title;String',
self.marshal(b'fOrMaT,thIs-aS*titLe;String').title())
self.assertEqual(b'Getint', self.marshal(b'getInt').title())
self.assertRaises(TypeError, self.marshal(b'hello').title, 42)
def test_splitlines(self):
self.assertEqual([b'abc', b'def', b'', b'ghi'],
self.marshal(b'abc\ndef\n\rghi').splitlines())
self.assertEqual([b'abc', b'def', b'', b'ghi'],
self.marshal(b'abc\ndef\n\r\nghi').splitlines())
self.assertEqual([b'abc', b'def', b'ghi'],
self.marshal(b'abc\ndef\r\nghi').splitlines())
self.assertEqual([b'abc', b'def', b'ghi'],
self.marshal(b'abc\ndef\r\nghi\n').splitlines())
self.assertEqual([b'abc', b'def', b'ghi', b''],
self.marshal(b'abc\ndef\r\nghi\n\r').splitlines())
self.assertEqual([b'', b'abc', b'def', b'ghi', b''],
self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines())
self.assertEqual([b'\n', b'abc\n', b'def\r\n', b'ghi\n', b'\r'],
self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(1))
self.assertRaises(TypeError, self.marshal(b'abc').splitlines, 42, 42)
| apache-2.0 |
asnir/airflow | tests/dags/test_issue_1225.py | 42 | 4542 | # -*- coding: utf-8 -*-
#
# 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.
"""
DAG designed to test what happens when a DAG with pooled tasks is run
by a BackfillJob.
Addresses issue #1225.
"""
from datetime import datetime
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.subdag_operator import SubDagOperator
from airflow.utils.trigger_rule import TriggerRule
import time
DEFAULT_DATE = datetime(2016, 1, 1)
default_args = dict(
start_date=DEFAULT_DATE,
owner='airflow')
def fail():
raise ValueError('Expected failure.')
def delayed_fail():
"""
Delayed failure to make sure that processes are running before the error
is raised.
TODO handle more directly (without sleeping)
"""
time.sleep(5)
raise ValueError('Expected failure.')
# DAG tests backfill with pooled tasks
# Previously backfill would queue the task but never run it
dag1 = DAG(dag_id='test_backfill_pooled_task_dag', default_args=default_args)
dag1_task1 = DummyOperator(
task_id='test_backfill_pooled_task',
dag=dag1,
pool='test_backfill_pooled_task_pool',)
# DAG tests depends_on_past dependencies
dag2 = DAG(dag_id='test_depends_on_past', default_args=default_args)
dag2_task1 = DummyOperator(
task_id='test_dop_task',
dag=dag2,
depends_on_past=True,)
# DAG tests that a Dag run that doesn't complete is marked failed
dag3 = DAG(dag_id='test_dagrun_states_fail', default_args=default_args)
dag3_task1 = PythonOperator(
task_id='test_dagrun_fail',
dag=dag3,
python_callable=fail)
dag3_task2 = DummyOperator(
task_id='test_dagrun_succeed',
dag=dag3,)
dag3_task2.set_upstream(dag3_task1)
# DAG tests that a Dag run that completes but has a failure is marked success
dag4 = DAG(dag_id='test_dagrun_states_success', default_args=default_args)
dag4_task1 = PythonOperator(
task_id='test_dagrun_fail',
dag=dag4,
python_callable=fail,
)
dag4_task2 = DummyOperator(
task_id='test_dagrun_succeed',
dag=dag4,
trigger_rule=TriggerRule.ALL_FAILED
)
dag4_task2.set_upstream(dag4_task1)
# DAG tests that a Dag run that completes but has a root failure is marked fail
dag5 = DAG(dag_id='test_dagrun_states_root_fail', default_args=default_args)
dag5_task1 = DummyOperator(
task_id='test_dagrun_succeed',
dag=dag5,
)
dag5_task2 = PythonOperator(
task_id='test_dagrun_fail',
dag=dag5,
python_callable=fail,
)
# DAG tests that a Dag run that is deadlocked with no states is failed
dag6 = DAG(dag_id='test_dagrun_states_deadlock', default_args=default_args)
dag6_task1 = DummyOperator(
task_id='test_depends_on_past',
depends_on_past=True,
dag=dag6,)
dag6_task2 = DummyOperator(
task_id='test_depends_on_past_2',
depends_on_past=True,
dag=dag6,)
dag6_task2.set_upstream(dag6_task1)
# DAG tests that a deadlocked subdag is properly caught
dag7 = DAG(dag_id='test_subdag_deadlock', default_args=default_args)
subdag7 = DAG(dag_id='test_subdag_deadlock.subdag', default_args=default_args)
subdag7_task1 = PythonOperator(
task_id='test_subdag_fail',
dag=subdag7,
python_callable=fail)
subdag7_task2 = DummyOperator(
task_id='test_subdag_dummy_1',
dag=subdag7,)
subdag7_task3 = DummyOperator(
task_id='test_subdag_dummy_2',
dag=subdag7)
dag7_subdag1 = SubDagOperator(
task_id='subdag',
dag=dag7,
subdag=subdag7)
subdag7_task1.set_downstream(subdag7_task2)
subdag7_task2.set_downstream(subdag7_task3)
# DAG tests that a Dag run that doesn't complete but has a root failure is marked running
dag8 = DAG(dag_id='test_dagrun_states_root_fail_unfinished', default_args=default_args)
dag8_task1 = DummyOperator(
task_id='test_dagrun_unfinished', # The test will unset the task instance state after
# running this test
dag=dag8,
)
dag8_task2 = PythonOperator(
task_id='test_dagrun_fail',
dag=dag8,
python_callable=fail,
)
| apache-2.0 |
showgood/YCM_windows | python/ycm/server/tests/test_utils.py | 4 | 2170 | #!/usr/bin/env python
#
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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.
#
# YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
import os
from .. import handlers
from ycm import user_options_store
def BuildRequest( **kwargs ):
filepath = kwargs[ 'filepath' ] if 'filepath' in kwargs else '/foo'
contents = kwargs[ 'contents' ] if 'contents' in kwargs else ''
filetype = kwargs[ 'filetype' ] if 'filetype' in kwargs else 'foo'
request = {
'query': '',
'line_num': 0,
'column_num': 0,
'start_column': 0,
'filetypes': [ filetype ],
'filepath': filepath,
'line_value': contents,
'file_data': {
filepath: {
'contents': contents,
'filetypes': [ filetype ]
}
}
}
for key, value in kwargs.iteritems():
if key in [ 'contents', 'filetype', 'filepath' ]:
continue
request[ key ] = value
if key == 'line_num':
lines = contents.splitlines()
if len( lines ) > 1:
# NOTE: assumes 0-based line_num
request[ 'line_value' ] = lines[ value ]
return request
def Setup():
handlers.SetServerStateToDefaults()
def ChangeSpecificOptions( options ):
current_options = dict( user_options_store.GetAll() )
current_options.update( options )
handlers.UpdateUserOptions( current_options )
def PathToTestDataDir():
dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) )
return os.path.join( dir_of_current_script, 'testdata' )
def PathToTestFile( test_basename ):
return os.path.join( PathToTestDataDir(), test_basename )
| gpl-3.0 |
sn1k/app_mundial | lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py | 72 | 1344 | from optparse import make_option
from django.conf import settings
from django.core.management.commands.runserver import Command as RunserverCommand
from django.contrib.staticfiles.handlers import StaticFilesHandler
class Command(RunserverCommand):
option_list = RunserverCommand.option_list + (
make_option('--nostatic', action="store_false", dest='use_static_handler', default=True,
help='Tells Django to NOT automatically serve static files at STATIC_URL.'),
make_option('--insecure', action="store_true", dest='insecure_serving', default=False,
help='Allows serving static files even if DEBUG is False.'),
)
help = "Starts a lightweight Web server for development and also serves static files."
def get_handler(self, *args, **options):
"""
Returns the static files serving handler wrapping the default handler,
if static files should be served. Otherwise just returns the default
handler.
"""
handler = super(Command, self).get_handler(*args, **options)
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if use_static_handler and (settings.DEBUG or insecure_serving):
return StaticFilesHandler(handler)
return handler
| gpl-2.0 |
soldag/home-assistant | homeassistant/components/awair/sensor.py | 10 | 8129 | """Support for Awair sensors."""
from typing import Callable, List, Optional
from python_awair.devices import AwairDevice
import voluptuous as vol
from homeassistant.components.awair import AwairDataUpdateCoordinator, AwairResult
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_DEVICE_CLASS, CONF_ACCESS_TOKEN
from homeassistant.helpers import device_registry as dr
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
API_DUST,
API_PM25,
API_SCORE,
API_TEMP,
API_VOC,
ATTR_ICON,
ATTR_LABEL,
ATTR_UNIQUE_ID,
ATTR_UNIT,
ATTRIBUTION,
DOMAIN,
DUST_ALIASES,
LOGGER,
SENSOR_TYPES,
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_ACCESS_TOKEN): cv.string},
extra=vol.ALLOW_EXTRA,
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Import Awair configuration from YAML."""
LOGGER.warning(
"Loading Awair via platform setup is deprecated. Please remove it from your configuration."
)
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=config,
)
)
async def async_setup_entry(
hass: HomeAssistantType,
config_entry: ConfigType,
async_add_entities: Callable[[List[Entity], bool], None],
):
"""Set up Awair sensor entity based on a config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
sensors = []
data: List[AwairResult] = coordinator.data.values()
for result in data:
if result.air_data:
sensors.append(AwairSensor(API_SCORE, result.device, coordinator))
device_sensors = result.air_data.sensors.keys()
for sensor in device_sensors:
if sensor in SENSOR_TYPES:
sensors.append(AwairSensor(sensor, result.device, coordinator))
# The "DUST" sensor for Awair is a combo pm2.5/pm10 sensor only
# present on first-gen devices in lieu of separate pm2.5/pm10 sensors.
# We handle that by creating fake pm2.5/pm10 sensors that will always
# report identical values, and we let users decide how they want to use
# that data - because we can't really tell what kind of particles the
# "DUST" sensor actually detected. However, it's still useful data.
if API_DUST in device_sensors:
for alias_kind in DUST_ALIASES:
sensors.append(AwairSensor(alias_kind, result.device, coordinator))
async_add_entities(sensors)
class AwairSensor(CoordinatorEntity):
"""Defines an Awair sensor entity."""
def __init__(
self,
kind: str,
device: AwairDevice,
coordinator: AwairDataUpdateCoordinator,
) -> None:
"""Set up an individual AwairSensor."""
super().__init__(coordinator)
self._kind = kind
self._device = device
@property
def name(self) -> str:
"""Return the name of the sensor."""
name = SENSOR_TYPES[self._kind][ATTR_LABEL]
if self._device.name:
name = f"{self._device.name} {name}"
return name
@property
def unique_id(self) -> str:
"""Return the uuid as the unique_id."""
unique_id_tag = SENSOR_TYPES[self._kind][ATTR_UNIQUE_ID]
# This integration used to create a sensor that was labelled as a "PM2.5"
# sensor for first-gen Awair devices, but its unique_id reflected the truth:
# under the hood, it was a "DUST" sensor. So we preserve that specific unique_id
# for users with first-gen devices that are upgrading.
if self._kind == API_PM25 and API_DUST in self._air_data.sensors:
unique_id_tag = "DUST"
return f"{self._device.uuid}_{unique_id_tag}"
@property
def available(self) -> bool:
"""Determine if the sensor is available based on API results."""
# If the last update was successful...
if self.coordinator.last_update_success and self._air_data:
# and the results included our sensor type...
if self._kind in self._air_data.sensors:
# then we are available.
return True
# or, we're a dust alias
if self._kind in DUST_ALIASES and API_DUST in self._air_data.sensors:
return True
# or we are API_SCORE
if self._kind == API_SCORE:
# then we are available.
return True
# Otherwise, we are not.
return False
@property
def state(self) -> float:
"""Return the state, rounding off to reasonable values."""
state: float
# Special-case for "SCORE", which we treat as the AQI
if self._kind == API_SCORE:
state = self._air_data.score
elif self._kind in DUST_ALIASES and API_DUST in self._air_data.sensors:
state = self._air_data.sensors.dust
else:
state = self._air_data.sensors[self._kind]
if self._kind == API_VOC or self._kind == API_SCORE:
return round(state)
if self._kind == API_TEMP:
return round(state, 1)
return round(state, 2)
@property
def icon(self) -> str:
"""Return the icon."""
return SENSOR_TYPES[self._kind][ATTR_ICON]
@property
def device_class(self) -> str:
"""Return the device_class."""
return SENSOR_TYPES[self._kind][ATTR_DEVICE_CLASS]
@property
def unit_of_measurement(self) -> str:
"""Return the unit the value is expressed in."""
return SENSOR_TYPES[self._kind][ATTR_UNIT]
@property
def device_state_attributes(self) -> dict:
"""Return the Awair Index alongside state attributes.
The Awair Index is a subjective score ranging from 0-4 (inclusive) that
is is used by the Awair app when displaying the relative "safety" of a
given measurement. Each value is mapped to a color indicating the safety:
0: green
1: yellow
2: light-orange
3: orange
4: red
The API indicates that both positive and negative values may be returned,
but the negative values are mapped to identical colors as the positive values.
Knowing that, we just return the absolute value of a given index so that
users don't have to handle positive/negative values that ultimately "mean"
the same thing.
https://docs.developer.getawair.com/?version=latest#awair-score-and-index
"""
attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
if self._kind in self._air_data.indices:
attrs["awair_index"] = abs(self._air_data.indices[self._kind])
elif self._kind in DUST_ALIASES and API_DUST in self._air_data.indices:
attrs["awair_index"] = abs(self._air_data.indices.dust)
return attrs
@property
def device_info(self) -> dict:
"""Device information."""
info = {
"identifiers": {(DOMAIN, self._device.uuid)},
"manufacturer": "Awair",
"model": self._device.model,
}
if self._device.name:
info["name"] = self._device.name
if self._device.mac_address:
info["connections"] = {
(dr.CONNECTION_NETWORK_MAC, self._device.mac_address)
}
return info
@property
def _air_data(self) -> Optional[AwairResult]:
"""Return the latest data for our device, or None."""
result: Optional[AwairResult] = self.coordinator.data.get(self._device.uuid)
if result:
return result.air_data
return None
| apache-2.0 |
kohnle-lernmodule/exe201based | exe/webui/freetextfpdblock.py | 11 | 4251 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# ===========================================================================
# eXe
# Copyright 2004-2006, University of Auckland
#
# 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
# ===========================================================================
"""
FPD - FreeTextBlock
can render and process FreeTextIdevices as XHTML
"""
import logging
from exe.webui.block import Block
from exe.webui.element import TextAreaElement
from exe.webui import common
log = logging.getLogger(__name__)
# ===========================================================================
class FreeTextfpdBlock(Block):
"""
FPD - FreeTextBlock can render and process FreeTextIdevices as XHTML
GenericBlock will replace it..... one day
"""
def __init__(self, parent, idevice):
Block.__init__(self, parent, idevice)
if idevice.content.idevice is None:
# due to the loading process's timing, idevice wasn't yet set;
# set it here for the TextAreaElement's tinyMCE editor
idevice.content.idevice = idevice
self.contentElement = TextAreaElement(idevice.content)
self.contentElement.height = 250
if not hasattr(self.idevice,'undo'):
self.idevice.undo = True
def process(self, request):
"""
Process the request arguments from the web server to see if any
apply to this block
"""
is_cancel = common.requestHasCancel(request)
if is_cancel:
self.idevice.edit = False
# but double-check for first-edits, and ensure proper attributes:
if not hasattr(self.idevice.content, 'content_w_resourcePaths'):
self.idevice.content.content_w_resourcePaths = ""
if not hasattr(self.idevice.content, 'content_wo_resourcePaths'):
self.idevice.content.content_wo_resourcePaths = ""
return
Block.process(self, request)
if (u"action" not in request.args or
request.args[u"action"][0] != u"delete"):
content = self.contentElement.process(request)
if content:
self.idevice.content = content
def renderEdit(self, style):
"""
Returns an XHTML string with the form element for editing this block
"""
html = u"<div>\n"
html += self.contentElement.renderEdit()
html += self.renderEditButtons()
html += u"</div>\n"
return html
def renderPreview(self, style):
"""
Returns an XHTML string for previewing this block
"""
html = u"<div class=\"iDevice "
html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
html += self.contentElement.renderPreview()
html += self.renderViewButtons()
html += "</div>\n"
return html
def renderView(self, style):
"""
Returns an XHTML string for viewing this block
"""
html = u"<div class=\"iDevice "
html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
html += self.contentElement.renderView()
html += u"</div>\n"
return html
from exe.engine.freetextfpdidevice import FreeTextfpdIdevice
from exe.webui.blockfactory import g_blockFactory
g_blockFactory.registerBlockType(FreeTextfpdBlock, FreeTextfpdIdevice)
# ===========================================================================
| gpl-2.0 |
40223247/2015cd_midterm-master | static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_program.py | 738 | 10833 | import io
import os
import sys
import unittest
class Test_TestProgram(unittest.TestCase):
def test_discovery_from_dotted_path(self):
loader = unittest.TestLoader()
tests = [self]
expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__))
self.wasRun = False
def _find_tests(start_dir, pattern):
self.wasRun = True
self.assertEqual(start_dir, expectedPath)
return tests
loader._find_tests = _find_tests
suite = loader.discover('unittest.test')
self.assertTrue(self.wasRun)
self.assertEqual(suite._tests, tests)
# Horrible white box test
def testNoExit(self):
result = object()
test = object()
class FakeRunner(object):
def run(self, test):
self.test = test
return result
runner = FakeRunner()
oldParseArgs = unittest.TestProgram.parseArgs
def restoreParseArgs():
unittest.TestProgram.parseArgs = oldParseArgs
unittest.TestProgram.parseArgs = lambda *args: None
self.addCleanup(restoreParseArgs)
def removeTest():
del unittest.TestProgram.test
unittest.TestProgram.test = test
self.addCleanup(removeTest)
program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2)
self.assertEqual(program.result, result)
self.assertEqual(runner.test, test)
self.assertEqual(program.verbosity, 2)
class FooBar(unittest.TestCase):
def testPass(self):
assert True
def testFail(self):
assert False
class FooBarLoader(unittest.TestLoader):
"""Test loader that returns a suite containing FooBar."""
def loadTestsFromModule(self, module):
return self.suiteClass(
[self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
def test_NonExit(self):
program = unittest.main(exit=False,
argv=["foobar"],
testRunner=unittest.TextTestRunner(stream=io.StringIO()),
testLoader=self.FooBarLoader())
self.assertTrue(hasattr(program, 'result'))
def test_Exit(self):
self.assertRaises(
SystemExit,
unittest.main,
argv=["foobar"],
testRunner=unittest.TextTestRunner(stream=io.StringIO()),
exit=True,
testLoader=self.FooBarLoader())
def test_ExitAsDefault(self):
self.assertRaises(
SystemExit,
unittest.main,
argv=["foobar"],
testRunner=unittest.TextTestRunner(stream=io.StringIO()),
testLoader=self.FooBarLoader())
class InitialisableProgram(unittest.TestProgram):
exit = False
result = None
verbosity = 1
defaultTest = None
testRunner = None
testLoader = unittest.defaultTestLoader
module = '__main__'
progName = 'test'
test = 'test'
def __init__(self, *args):
pass
RESULT = object()
class FakeRunner(object):
initArgs = None
test = None
raiseError = False
def __init__(self, **kwargs):
FakeRunner.initArgs = kwargs
if FakeRunner.raiseError:
FakeRunner.raiseError = False
raise TypeError
def run(self, test):
FakeRunner.test = test
return RESULT
class TestCommandLineArgs(unittest.TestCase):
def setUp(self):
self.program = InitialisableProgram()
self.program.createTests = lambda: None
FakeRunner.initArgs = None
FakeRunner.test = None
FakeRunner.raiseError = False
def testVerbosity(self):
program = self.program
for opt in '-q', '--quiet':
program.verbosity = 1
program.parseArgs([None, opt])
self.assertEqual(program.verbosity, 0)
for opt in '-v', '--verbose':
program.verbosity = 1
program.parseArgs([None, opt])
self.assertEqual(program.verbosity, 2)
def testBufferCatchFailfast(self):
program = self.program
for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'),
('catch', 'catchbreak')):
if attr == 'catch' and not hasInstallHandler:
continue
short_opt = '-%s' % arg[0]
long_opt = '--%s' % arg
for opt in short_opt, long_opt:
setattr(program, attr, None)
program.parseArgs([None, opt])
self.assertTrue(getattr(program, attr))
for opt in short_opt, long_opt:
not_none = object()
setattr(program, attr, not_none)
program.parseArgs([None, opt])
self.assertEqual(getattr(program, attr), not_none)
def testWarning(self):
"""Test the warnings argument"""
# see #10535
class FakeTP(unittest.TestProgram):
def parseArgs(self, *args, **kw): pass
def runTests(self, *args, **kw): pass
warnoptions = sys.warnoptions[:]
try:
sys.warnoptions[:] = []
# no warn options, no arg -> default
self.assertEqual(FakeTP().warnings, 'default')
# no warn options, w/ arg -> arg value
self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
sys.warnoptions[:] = ['somevalue']
# warn options, no arg -> None
# warn options, w/ arg -> arg value
self.assertEqual(FakeTP().warnings, None)
self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
finally:
sys.warnoptions[:] = warnoptions
def testRunTestsRunnerClass(self):
program = self.program
program.testRunner = FakeRunner
program.verbosity = 'verbosity'
program.failfast = 'failfast'
program.buffer = 'buffer'
program.warnings = 'warnings'
program.runTests()
self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',
'failfast': 'failfast',
'buffer': 'buffer',
'warnings': 'warnings'})
self.assertEqual(FakeRunner.test, 'test')
self.assertIs(program.result, RESULT)
def testRunTestsRunnerInstance(self):
program = self.program
program.testRunner = FakeRunner()
FakeRunner.initArgs = None
program.runTests()
# A new FakeRunner should not have been instantiated
self.assertIsNone(FakeRunner.initArgs)
self.assertEqual(FakeRunner.test, 'test')
self.assertIs(program.result, RESULT)
def testRunTestsOldRunnerClass(self):
program = self.program
FakeRunner.raiseError = True
program.testRunner = FakeRunner
program.verbosity = 'verbosity'
program.failfast = 'failfast'
program.buffer = 'buffer'
program.test = 'test'
program.runTests()
# If initialising raises a type error it should be retried
# without the new keyword arguments
self.assertEqual(FakeRunner.initArgs, {})
self.assertEqual(FakeRunner.test, 'test')
self.assertIs(program.result, RESULT)
def testCatchBreakInstallsHandler(self):
module = sys.modules['unittest.main']
original = module.installHandler
def restore():
module.installHandler = original
self.addCleanup(restore)
self.installed = False
def fakeInstallHandler():
self.installed = True
module.installHandler = fakeInstallHandler
program = self.program
program.catchbreak = True
program.testRunner = FakeRunner
program.runTests()
self.assertTrue(self.installed)
def _patch_isfile(self, names, exists=True):
def isfile(path):
return path in names
original = os.path.isfile
os.path.isfile = isfile
def restore():
os.path.isfile = original
self.addCleanup(restore)
def testParseArgsFileNames(self):
# running tests with filenames instead of module names
program = self.program
argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt']
self._patch_isfile(argv)
program.createTests = lambda: None
program.parseArgs(argv)
# note that 'wing.txt' is not a Python file so the name should
# *not* be converted to a module name
expected = ['foo', 'bar', 'baz', 'wing.txt']
self.assertEqual(program.testNames, expected)
def testParseArgsFilePaths(self):
program = self.program
argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
self._patch_isfile(argv)
program.createTests = lambda: None
program.parseArgs(argv)
expected = ['foo.bar.baz', 'green.red']
self.assertEqual(program.testNames, expected)
def testParseArgsNonExistentFiles(self):
program = self.program
argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
self._patch_isfile([])
program.createTests = lambda: None
program.parseArgs(argv)
self.assertEqual(program.testNames, argv[1:])
def testParseArgsAbsolutePathsThatCanBeConverted(self):
cur_dir = os.getcwd()
program = self.program
def _join(name):
return os.path.join(cur_dir, name)
argv = ['progname', _join('foo/bar/baz.py'), _join('green\\red.py')]
self._patch_isfile(argv)
program.createTests = lambda: None
program.parseArgs(argv)
expected = ['foo.bar.baz', 'green.red']
self.assertEqual(program.testNames, expected)
def testParseArgsAbsolutePathsThatCannotBeConverted(self):
program = self.program
# even on Windows '/...' is considered absolute by os.path.abspath
argv = ['progname', '/foo/bar/baz.py', '/green/red.py']
self._patch_isfile(argv)
program.createTests = lambda: None
program.parseArgs(argv)
self.assertEqual(program.testNames, argv[1:])
# it may be better to use platform specific functions to normalise paths
# rather than accepting '.PY' and '\' as file seprator on Linux / Mac
# it would also be better to check that a filename is a valid module
# identifier (we have a regex for this in loader.py)
# for invalid filenames should we raise a useful error rather than
# leaving the current error message (import of filename fails) in place?
if __name__ == '__main__':
unittest.main()
| agpl-3.0 |
clero/parameter-framework | test/functional-tests-legacy/PfwTestCase/Domains/tDomain_creation_deletion.py | 10 | 14853 | # -*-coding:utf-8 -*
# Copyright (c) 2011-2015, Intel Corporation
# 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 holder 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 HOLDER 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.
"""
Creation, renaming and deletion configuration testcases
List of tested functions :
--------------------------
- [createDomain] function
- [deleteDomain] function
Test cases :
------------
- Testing nominal cases
- Testing domain creation error
- Testing domain deletion error
"""
import os
from Util.PfwUnitTestLib import PfwTestCase
from Util import ACTLogging
log=ACTLogging.Logger()
# Test of Domains - Basic operations (creations/deletions)
class TestCases(PfwTestCase):
def setUp(self):
self.pfw.sendCmd("setTuningMode", "on")
self.new_domains_number = 4
self.new_domain_name = "Domain"
def tearDown(self):
self.pfw.sendCmd("setTuningMode", "off")
def test_Domain_Creation_Error(self):
"""
Testing domain creation error
-----------------------------
Test case description :
~~~~~~~~~~~~~~~~~~~~~~~
- Create an already existent domain
Tested commands :
~~~~~~~~~~~~~~~~~
- [createDomain] function
- [listDomains] function
Expected result :
~~~~~~~~~~~~~~~~~
- Error detected when creating an already existent domain
- No domains list update
"""
log.D(self.test_Domain_Creation_Error.__doc__)
# New domain creation
log.I("New domain creation")
log.I("command [createDomain]")
domain_name = 'Test_Domain'
out, err = self.pfw.sendCmd("createDomain",domain_name, "")
assert out == "Done", out
assert err == None, "ERROR : command [createDomain] - Error while creating domain %s" % (domain_name)
log.I("command [createDomain] correctly executed")
# Domains listing using "listDomains" command
log.I("Current domains listing")
log.I("command [listDomains]")
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
log.I("command [listDomains] - correctly executed")
# Domains listing backup
f_Domains_Backup = open("f_Domains_Backup", "w")
f_Domains_Backup.write(out)
f_Domains_Backup.close()
f_Domains_Backup = open("f_Domains_Backup", "r")
domains_nbr_init = 0
line=f_Domains_Backup.readline()
while line!="":
line=f_Domains_Backup.readline()
domains_nbr_init+=1
f_Domains_Backup.close()
log.I("Actual domains number : %s" % domains_nbr_init)
# Trying to add an existent domain name
log.I("Adding an already existent domain name")
log.I("command [createDomain]")
domain_name = 'Test_Domain'
out, err = self.pfw.sendCmd("createDomain",domain_name, "", expectSuccess=False)
assert out != "Done", "ERROR : command [createDomain] - Error not detected when creating an already existent domain"
assert err == None, err
log.I("command [createDomain] - error correctly detected")
# Checking domains list integrity
log.I("Checking domains listing integrity after domain creation error")
## Domains listing using "listDomains" command
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
f_Domains = open("f_Domains", "w")
f_Domains.write(out)
f_Domains.close()
## Domains listing integrity check
f_Domains = open("f_Domains", "r")
domains_nbr = 0
line=f_Domains.readline()
while line!="":
line=f_Domains.readline()
domains_nbr+=1
f_Domains.close()
assert domains_nbr == domains_nbr_init, "ERROR : Domains number error, expected %s, found %s" % (domains_nbr_init,domains_nbr)
log.I("Test OK - Domains number not updated")
f_Domains = open("f_Domains", "r")
f_Domains_Backup = open("f_Domains_Backup", "r")
for line in range(domains_nbr):
domain_backup_name = f_Domains_Backup.readline().strip('\r\n'),
domain_name = f_Domains.readline().strip('\r\n'),
assert domain_backup_name==domain_name, "ERROR : Error while reading domain %s" % (domain_backup_name)
log.I("Test OK - Domains listing not affected by domain creation error")
# Closing and deleting temp files
f_Domains_Backup.close()
f_Domains.close()
os.remove("f_Domains_Backup")
os.remove("f_Domains")
def test_Domain_Deletion_Error(self):
"""
Testing domain deletion error
-----------------------------
Test case description :
~~~~~~~~~~~~~~~~~~~~~~~
- Delete a non existent domain
Tested commands :
~~~~~~~~~~~~~~~~~
- [deleteDomain] function
- [listDomains] function
Expected result :
~~~~~~~~~~~~~~~~~
- Error detected when deleting a non-existent domain
- No domains list update
"""
log.D(self.test_Domain_Deletion_Error.__doc__)
# Domains listing using "listDomains" command
log.I("Current domains listing")
log.I("command [listDomains]")
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
log.I("command [listDomains] correctly executed")
# Domains listing backup
f_Domains_Backup = open("f_Domains_Backup", "w")
f_Domains_Backup.write(out)
f_Domains_Backup.close()
f_Domains_Backup = open("f_Domains_Backup", "r")
domains_nbr_init = 0
line=f_Domains_Backup.readline()
while line!="":
line=f_Domains_Backup.readline()
domains_nbr_init+=1
f_Domains_Backup.close()
log.I("Actual domains number : %s" % domains_nbr_init)
# Trying to delete a non-existent domain name
log.I("Deleting a non-existent domain name")
log.I("command [deleteDomain]")
domain_name = 'Wrong_Domain_Name'
out, err = self.pfw.sendCmd("deleteDomain",domain_name, "", expectSuccess=False)
assert out != "Done", "ERROR : command [deleteDomain] - Error not detected when deleting a non-existent domain"
assert err == None, err
log.I("command [deleteDomain] - error correctly detected")
# Checking domains list integrity
log.I("Checking domains listing integrity after domain deletion error")
## Domains listing using "listDomains" command
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
f_Domains = open("f_Domains", "w")
f_Domains.write(out)
f_Domains.close()
## Domains listing integrity check
f_Domains = open("f_Domains", "r")
domains_nbr = 0
line=f_Domains.readline()
while line!="":
line=f_Domains.readline()
domains_nbr+=1
f_Domains.close()
assert domains_nbr == domains_nbr_init, "ERROR : Domains number error, expected %s, found %s" % (domains_nbr_init,domains_nbr)
log.I("Test OK - Domains number not updated")
f_Domains = open("f_Domains", "r")
f_Domains_Backup = open("f_Domains_Backup", "r")
for line in range(domains_nbr):
domain_backup_name = f_Domains_Backup.readline().strip('\r\n'),
domain_name = f_Domains.readline().strip('\r\n'),
assert domain_backup_name==domain_name, "Error while reading domain %s" % (domain_backup_name)
log.I("Test OK - Domains listing not affected by domain deletion error")
# Closing and deleting temp files
f_Domains_Backup.close()
f_Domains.close()
os.remove("f_Domains_Backup")
os.remove("f_Domains")
def test_Nominal_Case(self):
"""
Testing nominal cases
---------------------
Test case description :
~~~~~~~~~~~~~~~~~~~~~~~
- Create X new domains
- Delete X domains
Tested commands :
~~~~~~~~~~~~~~~~~
- [createDomain] function
- [deleteDomain] function
- [listDomains] function
Expected result :
~~~~~~~~~~~~~~~~~
- X new domains created
- X domains deleted
"""
log.D(self.test_Nominal_Case.__doc__)
# Initial domains listing using "listDomains" command
log.I("Initial domains listing")
log.I("command [listDomains]")
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
log.I("command [listDomains] correctly executed")
# Initial domains number count
f_init_domains = open("f_init_domains", "w")
f_init_domains.write(out)
f_init_domains.close()
init_domains_nbr = 0
f_init_domains = open("f_init_domains", "r")
line=f_init_domains.readline()
while line!="":
line=f_init_domains.readline()
init_domains_nbr+=1
f_init_domains.close()
log.I("Initial domains number : %s" % (init_domains_nbr))
# New domains creation
log.I("New domains creation")
log.I("PFW command : [createDomain]")
for index in range (self.new_domains_number):
domain_name = "".join([self.new_domain_name, "_", str(index+init_domains_nbr)])
out, err = self.pfw.sendCmd("createDomain",domain_name, "")
assert out == "Done", "ERROR : %s" % (out)
assert err == None, "ERROR : command [createDomain] - Error while creating domain %s" % (domain_name)
log.I("command [createDomain] correctly executed")
# New domain creation check
log.I("New domains creation check :")
log.I("command [listDomains]")
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing new domains"
log.I("command [listDomains] correctly executed")
# Working on a temporary files to record domains listing
tempfile = open("tempfile", "w")
tempfile.write(out)
tempfile.close()
# Checking last added entries in the listing
tempfile = open("tempfile", "r")
domains_nbr = 0
line=tempfile.readline()
while line!="":
line=tempfile.readline()
domains_nbr+=1
tempfile.close()
log.I("New domains conformity check")
tempfile = open("tempfile", "r")
for line in range(domains_nbr):
if (line >= (domains_nbr - self.new_domains_number)):
domain_name = "".join([self.new_domain_name,"_",str(line)]),
domain_created = tempfile.readline().strip('\n\r'),
assert domain_name==domain_created, "ERROR : Error while creating domain %s %s" % (domain_created, domain_name)
else:
domain_created = tempfile.readline()
log.I("New domains conform to expected values")
created_domains_number = domains_nbr - init_domains_nbr
log.I("%s new domains created" % created_domains_number)
tempfile.close()
os.remove("tempfile")
# New domains deletion
log.I("New domains deletion")
log.I("command [deleteDomain]")
for index in range (self.new_domains_number):
domain_name = "".join([self.new_domain_name, "_", str(index+init_domains_nbr)])
out, err = self.pfw.sendCmd("deleteDomain",domain_name, "")
assert out == "Done", "ERROR : %s" % (out)
assert err == None, "ERROR : command [deleteDomain] - Error while deleting domain %s" % (domain_name)
log.I("command [deleteDomain] correctly executed")
# New domains deletion check
f_init_domains = open("f_init_domains", "r")
tempfile = open("tempfile", "w")
log.I("New domains deletion check :")
log.I("command [listDomains]")
out, err = self.pfw.sendCmd("listDomains","","")
assert err == None, "ERROR : command [listDomains] - Error while listing domains"
log.I("command [listDomains] correctly executed")
tempfile.write(out)
tempfile.close()
tempfile = open("tempfile", "r")
line=tempfile.readline()
line_init=f_init_domains.readline()
while line!="":
line=tempfile.readline()
line_init=f_init_domains.readline()
assert line == line_init, "ERROR : Domain deletion error"
if line=="":
assert line_init == "", "ERROR : Wrong domains deletion number"
log.I("Deletion completed - %s domains deleted" % created_domains_number)
# Temporary files deletion
tempfile.close()
f_init_domains.close()
os.remove("tempfile")
os.remove("f_init_domains")
| bsd-3-clause |
bmun/huxley | huxley/api/tests/test_country.py | 1 | 4197 | # Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from huxley.api import tests
from huxley.api.tests import auto
from huxley.utils.test import models
class CountryDetailGetTestCase(auto.RetrieveAPIAutoTestCase):
url_name = 'api:country_detail'
@classmethod
def get_test_object(cls):
return models.new_country()
def test_anonymous_user(self):
self.do_test()
class CountryListGetTestCase(tests.ListAPITestCase):
url_name = 'api:country_list'
def test_anonymous_user(self):
'''Anyone should be able to access a list of all the countries.'''
country1 = models.new_country(name='USA')
country2 = models.new_country(name='China')
country3 = models.new_country(name='Barbara Boxer', special=True)
response = self.get_response()
self.assertEqual(response.data, [
{'id': country1.id,
'special': country1.special,
'name': country1.name},
{'id': country2.id,
'special': country2.special,
'name': country2.name},
{'id': country3.id,
'special': country3.special,
'name': country3.name}])
class CountryDetailDeleteTestCase(auto.DestroyAPIAutoTestCase):
url_name = 'api:country_detail'
@classmethod
def get_test_object(cls):
return models.new_country()
def test_anonymous_user(self):
'''Anonymous users cannot delete countries.'''
self.do_test(expected_error=auto.EXP_DELETE_NOT_ALLOWED)
def test_authenticated_user(self):
'''Authenticated users cannot delete countries.'''
self.as_default_user().do_test(expected_error=auto.EXP_DELETE_NOT_ALLOWED)
def test_superuser(self):
'''Superusers cannot delete countries.'''
self.as_superuser().do_test(expected_error=auto.EXP_DELETE_NOT_ALLOWED)
class CountryDetailPatchTestCase(tests.PartialUpdateAPITestCase):
url_name = 'api:country_detail'
params = {'name': 'Barbara Boxer',
'special': True}
def setUp(self):
self.country = models.new_country(name='USA', special=False)
def test_anonymous_user(self):
'''Unauthenticated users shouldn't be able to update countries.'''
response = self.get_response(self.country.id, params=self.params)
self.assertMethodNotAllowed(response, 'PATCH')
def test_authenticated_user(self):
'''Authenticated users shouldn't be able to update countries.'''
models.new_user(username='user', password='user')
self.client.login(username='user', password='user')
response = self.get_response(self.country.id, params=self.params)
self.assertMethodNotAllowed(response, 'PATCH')
def test_superuser(self):
'''Superusers shouldn't be able to update countries.'''
models.new_superuser(username='user', password='user')
self.client.login(username='user', password='user')
response = self.get_response(self.country.id, params=self.params)
self.assertMethodNotAllowed(response, 'PATCH')
class CountryListPostTestCase(tests.CreateAPITestCase):
url_name = 'api:country_list'
params = {'name': 'USA',
'special': False}
def test_anonymous_user(self):
'''Unauthenticated users shouldn't be able to create countries.'''
response = self.get_response(self.params)
self.assertMethodNotAllowed(response, 'POST')
def test_self(self):
'''Authenticated users shouldn't be able to create countries.'''
models.new_user(username='user', password='user')
self.client.login(username='user', password='user')
response = self.get_response(self.params)
self.assertMethodNotAllowed(response, 'POST')
def test_super_user(self):
'''Superusers shouldn't be able to create countries.'''
models.new_superuser(username='user', password='user')
self.client.login(username='user', password='user')
response = self.get_response(self.params)
self.assertMethodNotAllowed(response, 'POST')
| bsd-3-clause |
Innovahn/odoo.old | addons/account/partner.py | 29 | 15414 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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 operator import itemgetter
import time
from openerp.osv import fields, osv
from openerp import api
class account_fiscal_position(osv.osv):
_name = 'account.fiscal.position'
_description = 'Fiscal Position'
_order = 'sequence'
_columns = {
'sequence': fields.integer('Sequence'),
'name': fields.char('Fiscal Position', required=True),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."),
'company_id': fields.many2one('res.company', 'Company'),
'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping', copy=True),
'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping', copy=True),
'note': fields.text('Notes'),
'auto_apply': fields.boolean('Automatic', help="Apply automatically this fiscal position."),
'vat_required': fields.boolean('VAT required', help="Apply only if partner has a VAT number."),
'country_id': fields.many2one('res.country', 'Countries', help="Apply only if delivery or invoicing country match."),
'country_group_id': fields.many2one('res.country.group', 'Country Group', help="Apply only if delivery or invocing country match the group."),
}
_defaults = {
'active': True,
}
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
if not taxes:
return []
if not fposition_id:
return map(lambda x: x.id, taxes)
result = set()
for t in taxes:
ok = False
for tax in fposition_id.tax_ids:
if tax.tax_src_id.id == t.id:
if tax.tax_dest_id:
result.add(tax.tax_dest_id.id)
ok=True
if not ok:
result.add(t.id)
return list(result)
@api.v8 # noqa
def map_tax(self, taxes):
result = self.env['account.tax'].browse()
for tax in taxes:
for t in self.tax_ids:
if t.tax_src_id == tax:
if t.tax_dest_id:
result |= t.tax_dest_id
break
else:
result |= tax
return result
@api.v7
def map_account(self, cr, uid, fposition_id, account_id, context=None):
if not fposition_id:
return account_id
for pos in fposition_id.account_ids:
if pos.account_src_id.id == account_id:
account_id = pos.account_dest_id.id
break
return account_id
@api.v8
def map_account(self, account):
for pos in self.account_ids:
if pos.account_src_id == account:
return pos.account_dest_id
return account
def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None):
if not partner_id:
return False
# This can be easily overriden to apply more complex fiscal rules
part_obj = self.pool['res.partner']
partner = part_obj.browse(cr, uid, partner_id, context=context)
# partner manually set fiscal position always win
if partner.property_account_position:
return partner.property_account_position.id
# if no delivery use invocing
if delivery_id:
delivery = part_obj.browse(cr, uid, delivery_id, context=context)
else:
delivery = partner
domain = [
('auto_apply', '=', True),
'|', ('vat_required', '=', False), ('vat_required', '=', partner.vat_subjected),
'|', ('country_id', '=', None), ('country_id', '=', delivery.country_id.id),
'|', ('country_group_id', '=', None), ('country_group_id.country_ids', '=', delivery.country_id.id)
]
fiscal_position_ids = self.search(cr, uid, domain, context=context)
if fiscal_position_ids:
return fiscal_position_ids[0]
return False
class account_fiscal_position_tax(osv.osv):
_name = 'account.fiscal.position.tax'
_description = 'Taxes Fiscal Position'
_rec_name = 'position_id'
_columns = {
'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True),
'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax')
}
_sql_constraints = [
('tax_src_dest_uniq',
'unique (position_id,tax_src_id,tax_dest_id)',
'A tax fiscal position could be defined only once time on same taxes.')
]
class account_fiscal_position_account(osv.osv):
_name = 'account.fiscal.position.account'
_description = 'Accounts Fiscal Position'
_rec_name = 'position_id'
_columns = {
'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
}
_sql_constraints = [
('account_src_dest_uniq',
'unique (position_id,account_src_id,account_dest_id)',
'An account fiscal position could be defined only once time on same accounts.')
]
class res_partner(osv.osv):
_name = 'res.partner'
_inherit = 'res.partner'
_description = 'Partner'
def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
ctx = context.copy()
ctx['all_fiscalyear'] = True
query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
FROM account_move_line l
LEFT JOIN account_account a ON (l.account_id=a.id)
WHERE a.type IN ('receivable','payable')
AND l.partner_id IN %s
AND l.reconcile_id IS NULL
AND """ + query + """
GROUP BY l.partner_id, a.type
""",
(tuple(ids),))
maps = {'receivable':'credit', 'payable':'debit' }
res = {}
for id in ids:
res[id] = {}.fromkeys(field_names, 0)
for pid,type,val in cr.fetchall():
if val is None: val=0
res[pid][maps[type]] = (type=='receivable') and val or -val
return res
def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
if not args:
return []
having_values = tuple(map(itemgetter(2), args))
where = ' AND '.join(
map(lambda x: '(SUM(bal2) %(operator)s %%s)' % {
'operator':x[1]},args))
query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
cr.execute(('SELECT pid AS partner_id, SUM(bal2) FROM ' \
'(SELECT CASE WHEN bal IS NOT NULL THEN bal ' \
'ELSE 0.0 END AS bal2, p.id as pid FROM ' \
'(SELECT (debit-credit) AS bal, partner_id ' \
'FROM account_move_line l ' \
'WHERE account_id IN ' \
'(SELECT id FROM account_account '\
'WHERE type=%s AND active) ' \
'AND reconcile_id IS NULL ' \
'AND '+query+') AS l ' \
'RIGHT JOIN res_partner p ' \
'ON p.id = partner_id ) AS pl ' \
'GROUP BY pid HAVING ' + where),
(type,) + having_values)
res = cr.fetchall()
if not res:
return [('id','=','0')]
return [('id','in',map(itemgetter(0), res))]
def _credit_search(self, cr, uid, obj, name, args, context=None):
return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context)
def _debit_search(self, cr, uid, obj, name, args, context=None):
return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context)
def _invoice_total(self, cr, uid, ids, field_name, arg, context=None):
result = {}
account_invoice_report = self.pool.get('account.invoice.report')
for partner in self.browse(cr, uid, ids, context=context):
domain = [('partner_id', 'child_of', partner.id)]
invoice_ids = account_invoice_report.search(cr, uid, domain, context=context)
invoices = account_invoice_report.browse(cr, uid, invoice_ids, context=context)
result[partner.id] = sum(inv.user_currency_price_total for inv in invoices)
return result
def _journal_item_count(self, cr, uid, ids, field_name, arg, context=None):
MoveLine = self.pool('account.move.line')
AnalyticAccount = self.pool('account.analytic.account')
return {
partner_id: {
'journal_item_count': MoveLine.search_count(cr, uid, [('partner_id', '=', partner_id)], context=context),
'contracts_count': AnalyticAccount.search_count(cr,uid, [('partner_id', '=', partner_id)], context=context)
}
for partner_id in ids
}
def has_something_to_reconcile(self, cr, uid, partner_id, context=None):
'''
at least a debit, a credit and a line older than the last reconciliation date of the partner
'''
cr.execute('''
SELECT l.partner_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit
FROM account_move_line l
RIGHT JOIN account_account a ON (a.id = l.account_id)
RIGHT JOIN res_partner p ON (l.partner_id = p.id)
WHERE a.reconcile IS TRUE
AND p.id = %s
AND l.reconcile_id IS NULL
AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
AND l.state <> 'draft'
GROUP BY l.partner_id''', (partner_id,))
res = cr.dictfetchone()
if res:
return bool(res['debit'] and res['credit'])
return False
def mark_as_reconciled(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
_columns = {
'vat_subjected': fields.boolean('VAT Legal Statement', help="Check this box if the partner is subjected to the VAT. It will be used for the VAT legal statement."),
'credit': fields.function(_credit_debit_get,
fnct_search=_credit_search, string='Total Receivable', multi='dc', help="Total amount this customer owes you."),
'debit': fields.function(_credit_debit_get, fnct_search=_debit_search, string='Total Payable', multi='dc', help="Total amount you have to pay to this supplier."),
'debit_limit': fields.float('Payable Limit'),
'total_invoiced': fields.function(_invoice_total, string="Total Invoiced", type='float', groups='account.group_account_invoice'),
'contracts_count': fields.function(_journal_item_count, string="Contracts", type='integer', multi="invoice_journal"),
'journal_item_count': fields.function(_journal_item_count, string="Journal Items", type="integer", multi="invoice_journal"),
'property_account_payable': fields.property(
type='many2one',
relation='account.account',
string="Account Payable",
domain="[('type', '=', 'payable')]",
help="This account will be used instead of the default one as the payable account for the current partner",
required=True),
'property_account_receivable': fields.property(
type='many2one',
relation='account.account',
string="Account Receivable",
domain="[('type', '=', 'receivable')]",
help="This account will be used instead of the default one as the receivable account for the current partner",
required=True),
'property_account_position': fields.property(
type='many2one',
relation='account.fiscal.position',
string="Fiscal Position",
help="The fiscal position will determine taxes and accounts used for the partner.",
),
'property_payment_term': fields.property(
type='many2one',
relation='account.payment.term',
string ='Customer Payment Term',
help="This payment term will be used instead of the default one for sale orders and customer invoices"),
'property_supplier_payment_term': fields.property(
type='many2one',
relation='account.payment.term',
string ='Supplier Payment Term',
help="This payment term will be used instead of the default one for purchase orders and supplier invoices"),
'ref_companies': fields.one2many('res.company', 'partner_id',
'Companies that refers to partner'),
'last_reconciliation_date': fields.datetime(
'Latest Full Reconciliation Date', copy=False,
help='Date on which the partner accounting entries were fully reconciled last time. '
'It differs from the last date where a reconciliation has been made for this partner, '
'as here we depict the fact that nothing more was to be reconciled at this date. '
'This can be achieved in 2 different ways: either the last unreconciled debit/credit '
'entry of this partner was reconciled, either the user pressed the button '
'"Nothing more to reconcile" during the manual reconciliation process.')
}
def _commercial_fields(self, cr, uid, context=None):
return super(res_partner, self)._commercial_fields(cr, uid, context=context) + \
['debit_limit', 'property_account_payable', 'property_account_receivable', 'property_account_position',
'property_payment_term', 'property_supplier_payment_term', 'last_reconciliation_date']
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
caotianwei/django | tests/update_only_fields/tests.py | 296 | 9780 | from __future__ import unicode_literals
from django.db.models.signals import post_save, pre_save
from django.test import TestCase
from .models import Account, Employee, Person, Profile, ProxyEmployee
class UpdateOnlyFieldsTests(TestCase):
def test_update_fields_basic(self):
s = Person.objects.create(name='Sara', gender='F')
self.assertEqual(s.gender, 'F')
s.gender = 'M'
s.name = 'Ian'
s.save(update_fields=['name'])
s = Person.objects.get(pk=s.pk)
self.assertEqual(s.gender, 'F')
self.assertEqual(s.name, 'Ian')
def test_update_fields_deferred(self):
s = Person.objects.create(name='Sara', gender='F', pid=22)
self.assertEqual(s.gender, 'F')
s1 = Person.objects.defer("gender", "pid").get(pk=s.pk)
s1.name = "Emily"
s1.gender = "M"
with self.assertNumQueries(1):
s1.save()
s2 = Person.objects.get(pk=s1.pk)
self.assertEqual(s2.name, "Emily")
self.assertEqual(s2.gender, "M")
def test_update_fields_only_1(self):
s = Person.objects.create(name='Sara', gender='F')
self.assertEqual(s.gender, 'F')
s1 = Person.objects.only('name').get(pk=s.pk)
s1.name = "Emily"
s1.gender = "M"
with self.assertNumQueries(1):
s1.save()
s2 = Person.objects.get(pk=s1.pk)
self.assertEqual(s2.name, "Emily")
self.assertEqual(s2.gender, "M")
def test_update_fields_only_2(self):
s = Person.objects.create(name='Sara', gender='F', pid=22)
self.assertEqual(s.gender, 'F')
s1 = Person.objects.only('name').get(pk=s.pk)
s1.name = "Emily"
s1.gender = "M"
with self.assertNumQueries(2):
s1.save(update_fields=['pid'])
s2 = Person.objects.get(pk=s1.pk)
self.assertEqual(s2.name, "Sara")
self.assertEqual(s2.gender, "F")
def test_update_fields_only_repeated(self):
s = Person.objects.create(name='Sara', gender='F')
self.assertEqual(s.gender, 'F')
s1 = Person.objects.only('name').get(pk=s.pk)
s1.gender = 'M'
with self.assertNumQueries(1):
s1.save()
# Test that the deferred class does not remember that gender was
# set, instead the instance should remember this.
s1 = Person.objects.only('name').get(pk=s.pk)
with self.assertNumQueries(1):
s1.save()
def test_update_fields_inheritance_defer(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
e1 = Employee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
e1 = Employee.objects.only('name').get(pk=e1.pk)
e1.name = 'Linda'
with self.assertNumQueries(1):
e1.save()
self.assertEqual(Employee.objects.get(pk=e1.pk).name,
'Linda')
def test_update_fields_fk_defer(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000)
e1 = Employee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
e1 = Employee.objects.only('profile').get(pk=e1.pk)
e1.profile = profile_receptionist
with self.assertNumQueries(1):
e1.save()
self.assertEqual(Employee.objects.get(pk=e1.pk).profile, profile_receptionist)
e1.profile_id = profile_boss.pk
with self.assertNumQueries(1):
e1.save()
self.assertEqual(Employee.objects.get(pk=e1.pk).profile, profile_boss)
def test_select_related_only_interaction(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
e1 = Employee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
e1 = Employee.objects.only('profile__salary').select_related('profile').get(pk=e1.pk)
profile_boss.name = 'Clerk'
profile_boss.salary = 1000
profile_boss.save()
# The loaded salary of 3000 gets saved, the name of 'Clerk' isn't
# overwritten.
with self.assertNumQueries(1):
e1.profile.save()
reloaded_profile = Profile.objects.get(pk=profile_boss.pk)
self.assertEqual(reloaded_profile.name, profile_boss.name)
self.assertEqual(reloaded_profile.salary, 3000)
def test_update_fields_m2m(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
e1 = Employee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
a1 = Account.objects.create(num=1)
a2 = Account.objects.create(num=2)
e1.accounts = [a1, a2]
with self.assertRaises(ValueError):
e1.save(update_fields=['accounts'])
def test_update_fields_inheritance(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000)
e1 = Employee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
e1.name = 'Ian'
e1.gender = 'M'
e1.save(update_fields=['name'])
e2 = Employee.objects.get(pk=e1.pk)
self.assertEqual(e2.name, 'Ian')
self.assertEqual(e2.gender, 'F')
self.assertEqual(e2.profile, profile_boss)
e2.profile = profile_receptionist
e2.name = 'Sara'
e2.save(update_fields=['profile'])
e3 = Employee.objects.get(pk=e1.pk)
self.assertEqual(e3.name, 'Ian')
self.assertEqual(e3.profile, profile_receptionist)
with self.assertNumQueries(1):
e3.profile = profile_boss
e3.save(update_fields=['profile_id'])
e4 = Employee.objects.get(pk=e3.pk)
self.assertEqual(e4.profile, profile_boss)
self.assertEqual(e4.profile_id, profile_boss.pk)
def test_update_fields_inheritance_with_proxy_model(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000)
e1 = ProxyEmployee.objects.create(name='Sara', gender='F',
employee_num=1, profile=profile_boss)
e1.name = 'Ian'
e1.gender = 'M'
e1.save(update_fields=['name'])
e2 = ProxyEmployee.objects.get(pk=e1.pk)
self.assertEqual(e2.name, 'Ian')
self.assertEqual(e2.gender, 'F')
self.assertEqual(e2.profile, profile_boss)
e2.profile = profile_receptionist
e2.name = 'Sara'
e2.save(update_fields=['profile'])
e3 = ProxyEmployee.objects.get(pk=e1.pk)
self.assertEqual(e3.name, 'Ian')
self.assertEqual(e3.profile, profile_receptionist)
def test_update_fields_signals(self):
p = Person.objects.create(name='Sara', gender='F')
pre_save_data = []
def pre_save_receiver(**kwargs):
pre_save_data.append(kwargs['update_fields'])
pre_save.connect(pre_save_receiver)
post_save_data = []
def post_save_receiver(**kwargs):
post_save_data.append(kwargs['update_fields'])
post_save.connect(post_save_receiver)
p.save(update_fields=['name'])
self.assertEqual(len(pre_save_data), 1)
self.assertEqual(len(pre_save_data[0]), 1)
self.assertIn('name', pre_save_data[0])
self.assertEqual(len(post_save_data), 1)
self.assertEqual(len(post_save_data[0]), 1)
self.assertIn('name', post_save_data[0])
pre_save.disconnect(pre_save_receiver)
post_save.disconnect(post_save_receiver)
def test_update_fields_incorrect_params(self):
s = Person.objects.create(name='Sara', gender='F')
with self.assertRaises(ValueError):
s.save(update_fields=['first_name'])
with self.assertRaises(ValueError):
s.save(update_fields="name")
def test_empty_update_fields(self):
s = Person.objects.create(name='Sara', gender='F')
pre_save_data = []
def pre_save_receiver(**kwargs):
pre_save_data.append(kwargs['update_fields'])
pre_save.connect(pre_save_receiver)
post_save_data = []
def post_save_receiver(**kwargs):
post_save_data.append(kwargs['update_fields'])
post_save.connect(post_save_receiver)
# Save is skipped.
with self.assertNumQueries(0):
s.save(update_fields=[])
# Signals were skipped, too...
self.assertEqual(len(pre_save_data), 0)
self.assertEqual(len(post_save_data), 0)
pre_save.disconnect(pre_save_receiver)
post_save.disconnect(post_save_receiver)
def test_num_queries_inheritance(self):
s = Employee.objects.create(name='Sara', gender='F')
s.employee_num = 1
s.name = 'Emily'
with self.assertNumQueries(1):
s.save(update_fields=['employee_num'])
s = Employee.objects.get(pk=s.pk)
self.assertEqual(s.employee_num, 1)
self.assertEqual(s.name, 'Sara')
s.employee_num = 2
s.name = 'Emily'
with self.assertNumQueries(1):
s.save(update_fields=['name'])
s = Employee.objects.get(pk=s.pk)
self.assertEqual(s.name, 'Emily')
self.assertEqual(s.employee_num, 1)
# A little sanity check that we actually did updates...
self.assertEqual(Employee.objects.count(), 1)
self.assertEqual(Person.objects.count(), 1)
with self.assertNumQueries(2):
s.save(update_fields=['name', 'employee_num'])
| bsd-3-clause |
TritonSailor/btce-api | btceapi/common.py | 4 | 5264 | # Copyright (c) 2013 Alan McIntyre
import httplib
import json
import decimal
import re
decimal.getcontext().rounding = decimal.ROUND_DOWN
exps = [decimal.Decimal("1e-%d" % i) for i in range(16)]
btce_domain = "btc-e.com"
all_currencies = ("btc", "usd", "rur", "ltc", "nmc", "eur", "nvc",
"trc", "ppc", "ftc", "xpm")
all_pairs = ("btc_usd", "btc_rur", "btc_eur", "ltc_btc", "ltc_usd",
"ltc_rur", "ltc_eur", "nmc_btc", "nmc_usd", "nvc_btc",
"nvc_usd", "usd_rur", "eur_usd", "trc_btc", "ppc_btc",
"ppc_usd", "ftc_btc", "xpm_btc")
max_digits = {"btc_usd": 3,
"btc_rur": 5,
"btc_eur": 5,
"ltc_btc": 5,
"ltc_usd": 6,
"ltc_rur": 5,
"ltc_eur": 3,
"nmc_btc": 5,
"nmc_usd": 3,
"nvc_btc": 5,
"nvc_usd": 3,
"usd_rur": 5,
"eur_usd": 5,
"trc_btc": 5,
"ppc_btc": 5,
"ppc_usd": 3,
"ftc_btc": 5,
"xpm_btc": 5}
min_orders = {"btc_usd": decimal.Decimal("0.01"),
"btc_rur": decimal.Decimal("0.1"),
"btc_eur": decimal.Decimal("0.1"),
"ltc_btc": decimal.Decimal("0.1"),
"ltc_usd": decimal.Decimal("0.1"),
"ltc_rur": decimal.Decimal("0.1"),
"ltc_eur": decimal.Decimal("0.1"),
"nmc_btc": decimal.Decimal("0.1"),
"nmc_usd": decimal.Decimal("0.1"),
"nvc_btc": decimal.Decimal("0.1"),
"nvc_usd": decimal.Decimal("0.1"),
"usd_rur": decimal.Decimal("0.1"),
"eur_usd": decimal.Decimal("0.1"),
"trc_btc": decimal.Decimal("0.1"),
"ppc_btc": decimal.Decimal("0.1"),
"ppc_usd": decimal.Decimal("0.1"),
"ftc_btc": decimal.Decimal("0.1"),
"xpm_btc": decimal.Decimal("0.1")}
def parseJSONResponse(response):
def parse_decimal(var):
return decimal.Decimal(var)
try:
r = json.loads(response, parse_float=parse_decimal,
parse_int=parse_decimal)
except Exception as e:
msg = "Error while attempting to parse JSON response:"\
" %s\nResponse:\n%r" % (e, response)
raise Exception(msg)
return r
HEADER_COOKIE_RE = re.compile(r'__cfduid=([a-f0-9]{46})')
BODY_COOKIE_RE = re.compile(r'document\.cookie="a=([a-f0-9]{32});path=/;";')
class BTCEConnection:
def __init__(self, timeout=30):
self.conn = httplib.HTTPSConnection(btce_domain, timeout=timeout)
self.cookie = None
def close(self):
self.conn.close()
def getCookie(self):
self.cookie = ""
self.conn.request("GET", '/')
response = self.conn.getresponse()
setCookieHeader = response.getheader("Set-Cookie")
match = HEADER_COOKIE_RE.search(setCookieHeader)
if match:
self.cookie = "__cfduid=" + match.group(1)
match = BODY_COOKIE_RE.search(response.read())
if match:
if self.cookie != "":
self.cookie += '; '
self.cookie += "a=" + match.group(1)
def makeRequest(self, url, extra_headers=None, params="", with_cookie=False):
headers = {"Content-type": "application/x-www-form-urlencoded"}
if extra_headers is not None:
headers.update(extra_headers)
if with_cookie:
if self.cookie is None:
self.getCookie()
headers.update({"Cookie": self.cookie})
self.conn.request("POST", url, params, headers)
response = self.conn.getresponse().read()
return response
def makeJSONRequest(self, url, extra_headers=None, params=""):
response = self.makeRequest(url, extra_headers, params)
return parseJSONResponse(response)
def validatePair(pair):
if pair not in all_pairs:
if "_" in pair:
a, b = pair.split("_")
swapped_pair = "%s_%s" % (b, a)
if swapped_pair in all_pairs:
msg = "Unrecognized pair: %r (did you mean %s?)"
msg = msg % (pair, swapped_pair)
raise Exception(msg)
raise Exception("Unrecognized pair: %r" % pair)
def validateOrder(pair, trade_type, rate, amount):
validatePair(pair)
if trade_type not in ("buy", "sell"):
raise Exception("Unrecognized trade type: %r" % trade_type)
minimum_amount = min_orders[pair]
formatted_min_amount = formatCurrency(minimum_amount, pair)
if amount < minimum_amount:
msg = "Trade amount too small; should be >= %s" % formatted_min_amount
raise Exception(msg)
def truncateAmountDigits(value, digits):
quantum = exps[digits]
return decimal.Decimal(value).quantize(quantum)
def truncateAmount(value, pair):
return truncateAmountDigits(value, max_digits[pair])
def formatCurrencyDigits(value, digits):
s = str(truncateAmountDigits(value, digits))
dot = s.index(".")
while s[-1] == "0" and len(s) > dot + 2:
s = s[:-1]
return s
def formatCurrency(value, pair):
return formatCurrencyDigits(value, max_digits[pair])
| mit |
mlperf/inference_results_v0.5 | closed/Google/code/gnmt/tpu-gnmt/home/kbuilder/mlperf-inference/google3/third_party/mlperf/inference/gnmt/nmt/tpu/utils/nmt_utils.py | 1 | 1467 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility functions specifically for NMT."""
from __future__ import print_function
from tpu.utils import misc_utils as utils
__all__ = ["get_translation"]
def get_translation(nmt_outputs, tgt_eos, subword_option):
"""Given batch decoding outputs, select a sentence and turn to text."""
if tgt_eos: tgt_eos = tgt_eos.encode("utf-8")
# Select a sentence
output = nmt_outputs.tolist()
# If there is an eos symbol in outputs, cut them at that point.
if tgt_eos and tgt_eos in output:
output = output[:output.index(tgt_eos)]
if subword_option == "bpe": # BPE
translation = utils.format_bpe_text(output)
elif subword_option == "spm": # SPM
translation = utils.format_spm_text(output)
else:
translation = utils.format_text(output)
return translation
| apache-2.0 |
sander76/home-assistant | homeassistant/components/ps4/__init__.py | 4 | 7131 | """Support for PlayStation 4 consoles."""
import logging
import os
from pyps4_2ndscreen.ddp import async_create_ddp_endpoint
from pyps4_2ndscreen.media_art import COUNTRIES
import voluptuous as vol
from homeassistant.components.media_player.const import (
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_TITLE,
MEDIA_TYPE_GAME,
)
from homeassistant.const import (
ATTR_COMMAND,
ATTR_ENTITY_ID,
ATTR_LOCKED,
CONF_REGION,
CONF_TOKEN,
)
from homeassistant.core import split_entity_id
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import location
from homeassistant.util.json import load_json, save_json
from .config_flow import PlayStation4FlowHandler # noqa: F401
from .const import ATTR_MEDIA_IMAGE_URL, COMMANDS, DOMAIN, GAMES_FILE, PS4_DATA
_LOGGER = logging.getLogger(__name__)
SERVICE_COMMAND = "send_command"
PS4_COMMAND_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_COMMAND): vol.In(list(COMMANDS)),
}
)
class PS4Data:
"""Init Data Class."""
def __init__(self):
"""Init Class."""
self.devices = []
self.protocol = None
async def async_setup(hass, config):
"""Set up the PS4 Component."""
hass.data[PS4_DATA] = PS4Data()
transport, protocol = await async_create_ddp_endpoint()
hass.data[PS4_DATA].protocol = protocol
_LOGGER.debug("PS4 DDP endpoint created: %s, %s", transport, protocol)
service_handle(hass)
return True
async def async_setup_entry(hass, config_entry):
"""Set up PS4 from a config entry."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, "media_player")
)
return True
async def async_unload_entry(hass, entry):
"""Unload a PS4 config entry."""
await hass.config_entries.async_forward_entry_unload(entry, "media_player")
return True
async def async_migrate_entry(hass, entry):
"""Migrate old entry."""
config_entries = hass.config_entries
data = entry.data
version = entry.version
_LOGGER.debug("Migrating PS4 entry from Version %s", version)
reason = {
1: "Region codes have changed",
2: "Format for Unique ID for entity registry has changed",
}
# Migrate Version 1 -> Version 2: New region codes.
if version == 1:
loc = await location.async_detect_location_info(
hass.helpers.aiohttp_client.async_get_clientsession()
)
if loc:
country = loc.country_name
if country in COUNTRIES:
for device in data["devices"]:
device[CONF_REGION] = country
version = entry.version = 2
config_entries.async_update_entry(entry, data=data)
_LOGGER.info(
"PlayStation 4 Config Updated: \
Region changed to: %s",
country,
)
# Migrate Version 2 -> Version 3: Update identifier format.
if version == 2:
# Prevent changing entity_id. Updates entity registry.
registry = await entity_registry.async_get_registry(hass)
for entity_id, e_entry in registry.entities.items():
if e_entry.config_entry_id == entry.entry_id:
unique_id = e_entry.unique_id
# Remove old entity entry.
registry.async_remove(entity_id)
# Format old unique_id.
unique_id = format_unique_id(entry.data[CONF_TOKEN], unique_id)
# Create new entry with old entity_id.
new_id = split_entity_id(entity_id)[1]
registry.async_get_or_create(
"media_player",
DOMAIN,
unique_id,
suggested_object_id=new_id,
config_entry=entry,
device_id=e_entry.device_id,
)
entry.version = 3
_LOGGER.info(
"PlayStation 4 identifier for entity: %s \
has changed",
entity_id,
)
config_entries.async_update_entry(entry)
return True
msg = f"""{reason[version]} for the PlayStation 4 Integration.
Please remove the PS4 Integration and re-configure
[here](/config/integrations)."""
hass.components.persistent_notification.async_create(
title="PlayStation 4 Integration Configuration Requires Update",
message=msg,
notification_id="config_entry_migration",
)
return False
def format_unique_id(creds, mac_address):
"""Use last 4 Chars of credential as suffix. Unique ID per PSN user."""
suffix = creds[-4:]
return f"{mac_address}_{suffix}"
def load_games(hass: HomeAssistantType, unique_id: str) -> dict:
"""Load games for sources."""
g_file = hass.config.path(GAMES_FILE.format(unique_id))
try:
games = load_json(g_file)
except HomeAssistantError as error:
games = {}
_LOGGER.error("Failed to load games file: %s", error)
if not isinstance(games, dict):
_LOGGER.error("Games file was not parsed correctly")
games = {}
# If file exists
if os.path.isfile(g_file):
games = _reformat_data(hass, games, unique_id)
return games
def save_games(hass: HomeAssistantType, games: dict, unique_id: str):
"""Save games to file."""
g_file = hass.config.path(GAMES_FILE.format(unique_id))
try:
save_json(g_file, games)
except OSError as error:
_LOGGER.error("Could not save game list, %s", error)
def _reformat_data(hass: HomeAssistantType, games: dict, unique_id: str) -> dict:
"""Reformat data to correct format."""
data_reformatted = False
for game, data in games.items():
# Convert str format to dict format.
if not isinstance(data, dict):
# Use existing title. Assign defaults.
games[game] = {
ATTR_LOCKED: False,
ATTR_MEDIA_TITLE: data,
ATTR_MEDIA_IMAGE_URL: None,
ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_GAME,
}
data_reformatted = True
_LOGGER.debug("Reformatting media data for item: %s, %s", game, data)
if data_reformatted:
save_games(hass, games, unique_id)
return games
def service_handle(hass: HomeAssistantType):
"""Handle for services."""
async def async_service_command(call):
"""Service for sending commands."""
entity_ids = call.data[ATTR_ENTITY_ID]
command = call.data[ATTR_COMMAND]
for device in hass.data[PS4_DATA].devices:
if device.entity_id in entity_ids:
await device.async_send_command(command)
hass.services.async_register(
DOMAIN, SERVICE_COMMAND, async_service_command, schema=PS4_COMMAND_SCHEMA
)
| apache-2.0 |
mach327/chirp_fork | chirp/drivers/icp7.py | 2 | 6806 | # Copyright 2017 SASANO Takayoshi (JG1UAA) <uaa@uaa.org.uk>
#
# 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/>.
from chirp.drivers import icf
from chirp import chirp_common, directory, bitwise
# memory nuber:
# 000 - 999 regular memory channels (supported, others not)
# 1000 - 1049 scan edges
# 1050 - 1249 auto write channels
# 1250 call channel (C0)
# 1251 call channel (C1)
MEM_FORMAT = """
struct {
ul32 freq;
ul32 offset;
ul16 train_sql:2,
tmode:3,
duplex:2,
train_tone:9;
ul16 tuning_step:4,
rtone:6,
ctone:6;
ul16 unknown0:6,
mode:3,
dtcs:7;
u8 unknown1:6,
dtcs_polarity:2;
char name[6];
} memory[1251];
#seekto 0x6b1e;
struct {
u8 bank;
u8 index;
} banks[1050];
#seekto 0x689e;
u8 used[132];
#seekto 0x6922;
u8 skips[132];
#seekto 0x69a6;
u8 pskips[132];
#seekto 0x7352;
struct {
char name[6];
} bank_names[18];
"""
MODES = ["FM", "WFM", "AM", "Auto"]
TMODES = ["", "Tone", "TSQL", "", "DTCS"]
DUPLEX = ["", "-", "+"]
DTCS_POLARITY = ["NN", "NR", "RN", "RR"]
TUNING_STEPS = [5.0, 6.25, 8.33, 9.0, 10.0, 12.5, 15.0, 20.0,
25.0, 30.0, 50.0, 100.0, 200.0, 0.0] # 0.0 as "Auto"
class ICP7Bank(icf.IcomBank):
"""ICP7 bank"""
def get_name(self):
_bank = self._model._radio._memobj.bank_names[self.index]
return str(_bank.name).rstrip()
def set_name(self, name):
_bank = self._model._radio._memobj.bank_names[self.index]
_bank.name = name.ljust(6)[:6]
@directory.register
class ICP7Radio(icf.IcomCloneModeRadio):
"""Icom IC-P7"""
VENDOR = "Icom"
MODEL = "IC-P7"
_model = "\x28\x69\x00\x01"
_memsize = 0x7500
_endframe = "Icom Inc\x2e\x41\x38"
_ranges = [(0x0000, 0x7500, 32)]
_num_banks = 18
_bank_class = ICP7Bank
_can_hispeed = True
def _get_bank(self, loc):
_bank = self._memobj.banks[loc]
if _bank.bank != 0xff:
return _bank.bank
else:
return None
def _set_bank(self, loc, bank):
_bank = self._memobj.banks[loc]
if bank is None:
_bank.bank = 0xff
else:
_bank.bank = bank
def _get_bank_index(self, loc):
_bank = self._memobj.banks[loc]
return _bank.index
def _set_bank_index(self, loc, index):
_bank = self._memobj.banks[loc]
_bank.index = index
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (0, 999)
rf.valid_tmodes = TMODES
rf.valid_duplexes = DUPLEX
rf.valid_modes = MODES
rf.valid_bands = [(495000, 999990000)]
rf.valid_skips = ["", "S", "P"]
rf.valid_tuning_steps = TUNING_STEPS
rf.valid_name_length = 6
rf.has_settings = True
rf.has_ctone = True
rf.has_bank = True
rf.has_bank_index = True
rf.has_bank_names = True
return rf
def process_mmap(self):
self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
def get_memory(self, number):
bit = 1 << (number % 8)
byte = int(number / 8)
_mem = self._memobj.memory[number]
_usd = self._memobj.used[byte]
_skp = self._memobj.skips[byte]
_psk = self._memobj.pskips[byte]
mem = chirp_common.Memory()
mem.number = number
if _usd & bit:
mem.empty = True
return mem
mem.freq = _mem.freq / 3
mem.offset = _mem.offset / 3
mem.tmode = TMODES[_mem.tmode]
mem.duplex = DUPLEX[_mem.duplex]
mem.tuning_step = TUNING_STEPS[_mem.tuning_step]
mem.rtone = chirp_common.TONES[_mem.rtone]
mem.ctone = chirp_common.TONES[_mem.ctone]
mem.mode = MODES[_mem.mode]
mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs]
mem.dtcs_polarity = DTCS_POLARITY[_mem.dtcs_polarity]
mem.name = str(_mem.name).rstrip()
if _skp & bit:
mem.skip = "P" if _psk & bit else "S"
else:
mem.skip = ""
return mem
def set_memory(self, mem):
bit = 1 << (mem.number % 8)
byte = int(mem.number / 8)
_mem = self._memobj.memory[mem.number]
_usd = self._memobj.used[byte]
_skp = self._memobj.skips[byte]
_psk = self._memobj.pskips[byte]
if mem.empty:
_usd |= bit
# We use default value instead of zero-fill
# to avoid unexpected behavior.
_mem.freq = 15000
_mem.offset = 479985000
_mem.train_sql = ~0
_mem.tmode = ~0
_mem.duplex = ~0
_mem.train_tone = ~0
_mem.tuning_step = ~0
_mem.rtone = ~0
_mem.ctone = ~0
_mem.unknown0 = 0
_mem.mode = ~0
_mem.dtcs = ~0
_mem.unknown1 = ~0
_mem.dtcs_polarity = ~0
_mem.name = " "
_skp |= bit
_psk |= bit
else:
_usd &= ~bit
_mem.freq = mem.freq * 3
_mem.offset = mem.offset * 3
_mem.train_sql = 0 # Train SQL mode (0:off 1:Tone 2:MSK)
_mem.tmode = TMODES.index(mem.tmode)
_mem.duplex = DUPLEX.index(mem.duplex)
_mem.train_tone = 228 # Train SQL Tone (x10Hz)
_mem.tuning_step = TUNING_STEPS.index(mem.tuning_step)
_mem.rtone = chirp_common.TONES.index(mem.rtone)
_mem.ctone = chirp_common.TONES.index(mem.ctone)
_mem.unknown0 = 0 # unknown (always zero)
_mem.mode = MODES.index(mem.mode)
_mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs)
_mem.unknown1 = ~0 # unknown (always one)
_mem.dtcs_polarity = DTCS_POLARITY.index(mem.dtcs_polarity)
_mem.name = mem.name.ljust(6)[:6]
if mem.skip == "S":
_skp |= bit
_psk &= ~bit
elif mem.skip == "P":
_skp |= bit
_psk |= bit
else:
_skp &= ~bit
_psk &= ~bit
| gpl-3.0 |
neerajvashistha/pa-dude | lib/python2.7/site-packages/pygments/styles/colorful.py | 50 | 2778 | # -*- coding: utf-8 -*-
"""
pygments.styles.colorful
~~~~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by CodeRay.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace
class ColorfulStyle(Style):
"""
A colorful style, inspired by CodeRay.
"""
default_style = ""
styles = {
Whitespace: "#bbbbbb",
Comment: "#888",
Comment.Preproc: "#579",
Comment.Special: "bold #cc0000",
Keyword: "bold #080",
Keyword.Pseudo: "#038",
Keyword.Type: "#339",
Operator: "#333",
Operator.Word: "bold #000",
Name.Builtin: "#007020",
Name.Function: "bold #06B",
Name.Class: "bold #B06",
Name.Namespace: "bold #0e84b5",
Name.Exception: "bold #F00",
Name.Variable: "#963",
Name.Variable.Instance: "#33B",
Name.Variable.Class: "#369",
Name.Variable.Global: "bold #d70",
Name.Constant: "bold #036",
Name.Label: "bold #970",
Name.Entity: "bold #800",
Name.Attribute: "#00C",
Name.Tag: "#070",
Name.Decorator: "bold #555",
String: "bg:#fff0f0",
String.Char: "#04D bg:",
String.Doc: "#D42 bg:",
String.Interpol: "bg:#eee",
String.Escape: "bold #666",
String.Regex: "bg:#fff0ff #000",
String.Symbol: "#A60 bg:",
String.Other: "#D20",
Number: "bold #60E",
Number.Integer: "bold #00D",
Number.Float: "bold #60E",
Number.Hex: "bold #058",
Number.Oct: "bold #40E",
Generic.Heading: "bold #000080",
Generic.Subheading: "bold #800080",
Generic.Deleted: "#A00000",
Generic.Inserted: "#00A000",
Generic.Error: "#FF0000",
Generic.Emph: "italic",
Generic.Strong: "bold",
Generic.Prompt: "bold #c65d09",
Generic.Output: "#888",
Generic.Traceback: "#04D",
Error: "#F00 bg:#FAA"
}
| mit |
feist/pcs | pcs/cli/booth/test/test_env.py | 1 | 4130 | from unittest import mock, TestCase
from pcs.cli.booth import env
from pcs.common import report_codes, env_file_role_codes
from pcs.lib.errors import LibraryEnvError, ReportItem
from pcs.test.tools.misc import create_setup_patch_mixin
SetupPatchMixin = create_setup_patch_mixin(env)
class BoothConfTest(TestCase, SetupPatchMixin):
def setUp(self):
self.write = self.setup_patch("env_file.write")
self.read = self.setup_patch("env_file.read")
self.process_no_existing_file_expectation = self.setup_patch(
"env_file.process_no_existing_file_expectation"
)
def test_sucessfully_care_about_local_file(self):
def next_in_line(_env):
_env.booth["modified_env"] = {
"config_file": {
"content": "file content",
"no_existing_file_expected": False,
},
"key_file": {
"content": "key file content",
"no_existing_file_expected": False,
}
}
return "call result"
mock_env = mock.MagicMock()
booth_conf_middleware = env.middleware_config(
"booth-name",
"/local/file/path.conf",
"/local/file/path.key",
)
self.assertEqual(
"call result",
booth_conf_middleware(next_in_line, mock_env)
)
self.assertEqual(self.read.mock_calls, [
mock.call('/local/file/path.conf'),
mock.call('/local/file/path.key', is_binary=True),
])
self.assertEqual(self.process_no_existing_file_expectation.mock_calls, [
mock.call(
'booth config file',
{
'content': 'file content',
'no_existing_file_expected': False
},
'/local/file/path.conf'
),
mock.call(
'booth key file',
{
'content': 'key file content',
'no_existing_file_expected': False
},
'/local/file/path.key'
),
])
self.assertEqual(self.write.mock_calls, [
mock.call(
{
'content': 'key file content',
'no_existing_file_expected': False
},
'/local/file/path.key'
),
mock.call(
{
'content': 'file content',
'no_existing_file_expected': False
},
'/local/file/path.conf'
)
])
def test_catch_exactly_his_exception(self):
report_missing = self.setup_patch("env_file.report_missing")
next_in_line = mock.Mock(side_effect=LibraryEnvError(
ReportItem.error(report_codes.FILE_DOES_NOT_EXIST, info={
"file_role": env_file_role_codes.BOOTH_CONFIG,
}),
ReportItem.error(report_codes.FILE_DOES_NOT_EXIST, info={
"file_role": env_file_role_codes.BOOTH_KEY,
}),
ReportItem.error("OTHER ERROR", info={}),
))
mock_env = mock.MagicMock()
self.read.return_value = {"content": None}
booth_conf_middleware = env.middleware_config(
"booth-name",
"/local/file/path.conf",
"/local/file/path.key",
)
raised_exception = []
def run_middleware():
try:
booth_conf_middleware(next_in_line, mock_env)
except Exception as exc:
raised_exception.append(exc)
raise exc
self.assertRaises(LibraryEnvError, run_middleware)
self.assertEqual(1, len(raised_exception[0].unprocessed))
self.assertEqual("OTHER ERROR", raised_exception[0].unprocessed[0].code)
self.assertEqual(report_missing.mock_calls, [
mock.call('Booth config file', '/local/file/path.conf'),
mock.call('Booth key file', '/local/file/path.key'),
])
| gpl-2.0 |
CydarLtd/ansible | lib/ansible/modules/cloud/cloudstack/cs_securitygroup_rule.py | 78 | 14217 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cs_securitygroup_rule
short_description: Manages security group rules on Apache CloudStack based clouds.
description:
- Add and remove security group rules.
version_added: '2.0'
author: "René Moser (@resmo)"
options:
security_group:
description:
- Name of the security group the rule is related to. The security group must be existing.
required: true
state:
description:
- State of the security group rule.
required: false
default: 'present'
choices: [ 'present', 'absent' ]
protocol:
description:
- Protocol of the security group rule.
required: false
default: 'tcp'
choices: [ 'tcp', 'udp', 'icmp', 'ah', 'esp', 'gre' ]
type:
description:
- Ingress or egress security group rule.
required: false
default: 'ingress'
choices: [ 'ingress', 'egress' ]
cidr:
description:
- CIDR (full notation) to be used for security group rule.
required: false
default: '0.0.0.0/0'
user_security_group:
description:
- Security group this rule is based of.
required: false
default: null
start_port:
description:
- Start port for this rule. Required if C(protocol=tcp) or C(protocol=udp).
required: false
default: null
aliases: [ 'port' ]
end_port:
description:
- End port for this rule. Required if C(protocol=tcp) or C(protocol=udp), but C(start_port) will be used if not set.
required: false
default: null
icmp_type:
description:
- Type of the icmp message being sent. Required if C(protocol=icmp).
required: false
default: null
icmp_code:
description:
- Error code for this icmp message. Required if C(protocol=icmp).
required: false
default: null
project:
description:
- Name of the project the security group to be created in.
required: false
default: null
poll_async:
description:
- Poll async jobs until job has finished.
required: false
default: true
extends_documentation_fragment: cloudstack
'''
EXAMPLES = '''
---
# Allow inbound port 80/tcp from 1.2.3.4 added to security group 'default'
- local_action:
module: cs_securitygroup_rule
security_group: default
port: 80
cidr: 1.2.3.4/32
# Allow tcp/udp outbound added to security group 'default'
- local_action:
module: cs_securitygroup_rule
security_group: default
type: egress
start_port: 1
end_port: 65535
protocol: '{{ item }}'
with_items:
- tcp
- udp
# Allow inbound icmp from 0.0.0.0/0 added to security group 'default'
- local_action:
module: cs_securitygroup_rule
security_group: default
protocol: icmp
icmp_code: -1
icmp_type: -1
# Remove rule inbound port 80/tcp from 0.0.0.0/0 from security group 'default'
- local_action:
module: cs_securitygroup_rule
security_group: default
port: 80
state: absent
# Allow inbound port 80/tcp from security group web added to security group 'default'
- local_action:
module: cs_securitygroup_rule
security_group: default
port: 80
user_security_group: web
'''
RETURN = '''
---
id:
description: UUID of the of the rule.
returned: success
type: string
sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f
security_group:
description: security group of the rule.
returned: success
type: string
sample: default
type:
description: type of the rule.
returned: success
type: string
sample: ingress
cidr:
description: CIDR of the rule.
returned: success and cidr is defined
type: string
sample: 0.0.0.0/0
user_security_group:
description: user security group of the rule.
returned: success and user_security_group is defined
type: string
sample: default
protocol:
description: protocol of the rule.
returned: success
type: string
sample: tcp
start_port:
description: start port of the rule.
returned: success
type: int
sample: 80
end_port:
description: end port of the rule.
returned: success
type: int
sample: 80
'''
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackSecurityGroupRule(AnsibleCloudStack):
def __init__(self, module):
super(AnsibleCloudStackSecurityGroupRule, self).__init__(module)
self.returns = {
'icmptype': 'icmp_type',
'icmpcode': 'icmp_code',
'endport': 'end_port',
'startport': 'start_port',
'protocol': 'protocol',
'cidr': 'cidr',
'securitygroupname': 'user_security_group',
}
def _tcp_udp_match(self, rule, protocol, start_port, end_port):
return protocol in ['tcp', 'udp'] \
and protocol == rule['protocol'] \
and start_port == int(rule['startport']) \
and end_port == int(rule['endport'])
def _icmp_match(self, rule, protocol, icmp_code, icmp_type):
return protocol == 'icmp' \
and protocol == rule['protocol'] \
and icmp_code == int(rule['icmpcode']) \
and icmp_type == int(rule['icmptype'])
def _ah_esp_gre_match(self, rule, protocol):
return protocol in ['ah', 'esp', 'gre'] \
and protocol == rule['protocol']
def _type_security_group_match(self, rule, security_group_name):
return security_group_name \
and 'securitygroupname' in rule \
and security_group_name == rule['securitygroupname']
def _type_cidr_match(self, rule, cidr):
return 'cidr' in rule \
and cidr == rule['cidr']
def _get_rule(self, rules):
user_security_group_name = self.module.params.get('user_security_group')
cidr = self.module.params.get('cidr')
protocol = self.module.params.get('protocol')
start_port = self.module.params.get('start_port')
end_port = self.get_or_fallback('end_port', 'start_port')
icmp_code = self.module.params.get('icmp_code')
icmp_type = self.module.params.get('icmp_type')
if protocol in ['tcp', 'udp'] and (start_port is None or end_port is None):
self.module.fail_json(msg="no start_port or end_port set for protocol '%s'" % protocol)
if protocol == 'icmp' and (icmp_type is None or icmp_code is None):
self.module.fail_json(msg="no icmp_type or icmp_code set for protocol '%s'" % protocol)
for rule in rules:
if user_security_group_name:
type_match = self._type_security_group_match(rule, user_security_group_name)
else:
type_match = self._type_cidr_match(rule, cidr)
protocol_match = ( self._tcp_udp_match(rule, protocol, start_port, end_port) \
or self._icmp_match(rule, protocol, icmp_code, icmp_type) \
or self._ah_esp_gre_match(rule, protocol)
)
if type_match and protocol_match:
return rule
return None
def get_security_group(self, security_group_name=None):
if not security_group_name:
security_group_name = self.module.params.get('security_group')
args = {}
args['securitygroupname'] = security_group_name
args['projectid'] = self.get_project('id')
sgs = self.cs.listSecurityGroups(**args)
if not sgs or 'securitygroup' not in sgs:
self.module.fail_json(msg="security group '%s' not found" % security_group_name)
return sgs['securitygroup'][0]
def add_rule(self):
security_group = self.get_security_group()
args = {}
user_security_group_name = self.module.params.get('user_security_group')
# the user_security_group and cidr are mutually_exclusive, but cidr is defaulted to 0.0.0.0/0.
# that is why we ignore if we have a user_security_group.
if user_security_group_name:
args['usersecuritygrouplist'] = []
user_security_group = self.get_security_group(user_security_group_name)
args['usersecuritygrouplist'].append({
'group': user_security_group['name'],
'account': user_security_group['account'],
})
else:
args['cidrlist'] = self.module.params.get('cidr')
args['protocol'] = self.module.params.get('protocol')
args['startport'] = self.module.params.get('start_port')
args['endport'] = self.get_or_fallback('end_port', 'start_port')
args['icmptype'] = self.module.params.get('icmp_type')
args['icmpcode'] = self.module.params.get('icmp_code')
args['projectid'] = self.get_project('id')
args['securitygroupid'] = security_group['id']
rule = None
res = None
sg_type = self.module.params.get('type')
if sg_type == 'ingress':
if 'ingressrule' in security_group:
rule = self._get_rule(security_group['ingressrule'])
if not rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.cs.authorizeSecurityGroupIngress(**args)
elif sg_type == 'egress':
if 'egressrule' in security_group:
rule = self._get_rule(security_group['egressrule'])
if not rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.cs.authorizeSecurityGroupEgress(**args)
if res and 'errortext' in res:
self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
poll_async = self.module.params.get('poll_async')
if res and poll_async:
security_group = self.poll_job(res, 'securitygroup')
key = sg_type + "rule" # ingressrule / egressrule
if key in security_group:
rule = security_group[key][0]
return rule
def remove_rule(self):
security_group = self.get_security_group()
rule = None
res = None
sg_type = self.module.params.get('type')
if sg_type == 'ingress':
rule = self._get_rule(security_group['ingressrule'])
if rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.cs.revokeSecurityGroupIngress(id=rule['ruleid'])
elif sg_type == 'egress':
rule = self._get_rule(security_group['egressrule'])
if rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.cs.revokeSecurityGroupEgress(id=rule['ruleid'])
if res and 'errortext' in res:
self.module.fail_json(msg="Failed: '%s'" % res['errortext'])
poll_async = self.module.params.get('poll_async')
if res and poll_async:
res = self.poll_job(res, 'securitygroup')
return rule
def get_result(self, security_group_rule):
super(AnsibleCloudStackSecurityGroupRule, self).get_result(security_group_rule)
self.result['type'] = self.module.params.get('type')
self.result['security_group'] = self.module.params.get('security_group')
return self.result
def main():
argument_spec = cs_argument_spec()
argument_spec.update(dict(
security_group = dict(required=True),
type = dict(choices=['ingress', 'egress'], default='ingress'),
cidr = dict(default='0.0.0.0/0'),
user_security_group = dict(default=None),
protocol = dict(choices=['tcp', 'udp', 'icmp', 'ah', 'esp', 'gre'], default='tcp'),
icmp_type = dict(type='int', default=None),
icmp_code = dict(type='int', default=None),
start_port = dict(type='int', default=None, aliases=['port']),
end_port = dict(type='int', default=None),
state = dict(choices=['present', 'absent'], default='present'),
project = dict(default=None),
poll_async = dict(type='bool', default=True),
))
required_together = cs_required_together()
required_together.extend([
['icmp_type', 'icmp_code'],
])
module = AnsibleModule(
argument_spec=argument_spec,
required_together=required_together,
mutually_exclusive = (
['icmp_type', 'start_port'],
['icmp_type', 'end_port'],
['icmp_code', 'start_port'],
['icmp_code', 'end_port'],
),
supports_check_mode=True
)
try:
acs_sg_rule = AnsibleCloudStackSecurityGroupRule(module)
state = module.params.get('state')
if state in ['absent']:
sg_rule = acs_sg_rule.remove_rule()
else:
sg_rule = acs_sg_rule.add_rule()
result = acs_sg_rule.get_result(sg_rule)
except CloudStackException as e:
module.fail_json(msg='CloudStackException: %s' % str(e))
module.exit_json(**result)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| gpl-3.0 |
flh/odoo | addons/hw_scale/__init__.py | 1894 | 1075 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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/>.
#
##############################################################################
import controllers
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
malkavi/Flexget | flexget/tests/test_timeframe.py | 3 | 4626 | import datetime
from flexget.manager import Session
from flexget.plugins.filter.timeframe import EntryTimeFrame
def age_timeframe(**kwargs):
with Session() as session:
session.query(EntryTimeFrame).update(
{'first_seen': datetime.datetime.now() - datetime.timedelta(**kwargs)}
)
class TestTimeFrame:
config = """
templates:
global:
accept_all: yes
tasks:
wait:
timeframe:
wait: 1 day
target: 1080p
mock:
- {title: 'Movie.BRRip.x264.720p', 'media_id': 'Movie'}
- {title: 'Movie.720p WEB-DL X264 AC3', 'media_id': 'Movie'}
reached_and_backlog:
timeframe:
wait: 1 hour
target: 1080p
on_reached: accept
mock:
- {title: 'Movie.720p WEB-DL X264 AC3', 'media_id': 'Movie'}
- {title: 'Movie.BRRip.x264.720p', 'media_id': 'Movie'}
target1:
timeframe:
wait: 1 hour
target: 1080p
on_reached: accept
mock:
- {title: 'Movie.720p WEB-DL X264 AC3', 'media_id': 'Movie'}
- {title: 'Movie.BRRip.x264.720p', 'media_id': 'Movie'}
target2:
timeframe:
wait: 1 hour
target: 1080p
on_reached: accept
mock:
- {title: 'Movie.1080p WEB-DL X264 AC3', 'media_id': 'Movie'}
"""
def test_wait(self, execute_task):
task = execute_task('wait')
with Session() as session:
query = session.query(EntryTimeFrame).all()
assert len(query) == 1, 'There should be one tracked entity present.'
assert query[0].id == 'movie', 'Should have tracked name `Movie`.'
entry = task.find_entry('rejected', title='Movie.BRRip.x264.720p')
assert entry, 'Movie.BRRip.x264.720p should be rejected'
entry = task.find_entry('rejected', title='Movie.720p WEB-DL X264 AC3')
assert entry, 'Movie.720p WEB-DL X264 AC3 should be rejected'
def test_reached_and_backlog(self, manager, execute_task):
execute_task('reached_and_backlog')
age_timeframe(hours=1)
# simulate movie going away from the task/feed
del manager.config['tasks']['reached_and_backlog']['mock']
task = execute_task('reached_and_backlog')
entry = task.find_entry('accepted', title='Movie.BRRip.x264.720p')
assert entry, 'Movie.BRRip.x264.720p should be accepted, backlog not injecting'
def test_target(self, execute_task):
execute_task('target1')
task = execute_task('target2')
entry = task.find_entry('accepted', title='Movie.1080p WEB-DL X264 AC3')
assert entry, 'Movie.1080p WEB-DL X264 AC3 should be undecided'
def test_learn(self, execute_task):
execute_task('target2')
with Session() as session:
query = session.query(EntryTimeFrame).all()
assert len(query) == 1, 'There should be one tracked entity present.'
assert query[0].status == 'accepted', 'Should be accepted.'
class TestTimeFrameActions:
config = """
templates:
global:
accept_all: yes
tasks:
wait_reject:
timeframe:
wait: 1 day
target: 1080p
on_waiting: reject
mock:
- {title: 'Movie.BRRip.x264.720p', 'id': 'Movie'}
- {title: 'Movie.720p WEB-DL X264 AC3', 'id': 'Movie'}
reached_accept:
timeframe:
wait: 1 hour
target: 1080p
on_reached: accept
mock:
- {title: 'Movie.720p WEB-DL X264 AC3', 'id': 'Movie'}
- {title: 'Movie.BRRip.x264.720p', 'id': 'Movie'}
"""
def test_on_reject(self, execute_task):
task = execute_task('wait_reject')
entry = task.find_entry('rejected', title='Movie.BRRip.x264.720p')
assert entry, 'Movie.BRRip.x264.720p should be rejected'
entry = task.find_entry('rejected', title='Movie.720p WEB-DL X264 AC3')
assert entry, 'Movie.720p WEB-DL X264 AC3 should be rejected'
def test_on_reached(self, manager, execute_task):
execute_task('reached_accept')
age_timeframe(hours=1)
task = execute_task('reached_accept')
entry = task.find_entry('accepted', title='Movie.BRRip.x264.720p')
assert entry, 'Movie.BRRip.x264.720p should be undecided, backlog not injecting'
| mit |
genenetwork/genenetwork2 | scripts/maintenance/readProbeSetSE_v7.py | 3 | 6767 | #!/usr/bin/python2
"""This script use the nearest marker to the transcript as control, increasing permutation rounds according to the p-value"""
########################################################################
# Last Updated Sep 27, 2011 by Xiaodong
# This version fix the bug that incorrectly exclude the first 2 probesetIDs
########################################################################
import string
import sys
import MySQLdb
import getpass
import time
def translateAlias(str):
if str == "B6":
return "C57BL/6J"
elif str == "D2":
return "DBA/2J"
else:
return str
########################################################################
#
# Indicate Data Start Position, ProbeFreezeId, GeneChipId, DataFile
#
########################################################################
dataStart = 1
GeneChipId = int(input("Enter GeneChipId:"))
ProbeSetFreezeId = int(input("Enter ProbeSetFreezeId:"))
input_file_name = input("Enter file name with suffix:")
fp = open("%s" % input_file_name, 'rb')
try:
passwd = getpass.getpass('Please enter mysql password here : ')
con = MySQLdb.Connect(db='db_webqtl', host='localhost',
user='username', passwd=passwd)
db = con.cursor()
print("You have successfully connected to mysql.\n")
except:
print("You entered incorrect password.\n")
sys.exit(0)
time0 = time.time()
########################################################################
#
# Indicate Data Start Position, ProbeFreezeId, GeneChipId, DataFile
#
########################################################################
#GeneChipId = 4
#dataStart = 1
# ProbeSetFreezeId = 359 #JAX Liver 6C Affy M430 2.0 (Jul11) MDP
#fp = open("GSE10493_AllSamples_6C_Z_AvgSE.txt", 'rb')
#########################################################################
#
# Check if each line have same number of members
# generate the gene list of expression data here
#
#########################################################################
print('Checking if each line have same number of members')
GeneList = []
isCont = 1
header = fp.readline()
header = header.strip().split('\t')
header = [item.strip() for item in header]
nfield = len(header)
line = fp.readline()
kj = 0
while line:
line2 = line.strip().split('\t')
line2 = [item.strip() for item in line2]
if len(line2) != nfield:
isCont = 0
print(("Error : " + line))
GeneList.append(line2[0])
line = fp.readline()
kj += 1
if kj % 100000 == 0:
print(('checked ', kj, ' lines'))
GeneList = sorted(map(string.lower, GeneList))
if isCont == 0:
sys.exit(0)
print(('used ', time.time()-time0, ' seconds'))
#########################################################################
#
# Check if each strain exist in database
# generate the string id list of expression data here
#
#########################################################################
print('Checking if each strain exist in database')
isCont = 1
fp.seek(0)
header = fp.readline()
header = header.strip().split('\t')
header = [item.strip() for item in header]
header = list(map(translateAlias, header))
header = header[dataStart:]
Ids = []
for item in header:
try:
db.execute('select Id from Strain where Name = "%s"' % item)
Ids.append(db.fetchall()[0][0])
except:
isCont = 0
print((item, 'does not exist, check the if the strain name is correct'))
if isCont == 0:
sys.exit(0)
print(('used ', time.time()-time0, ' seconds'))
########################################################################
#
# Check if each ProbeSet exist in database
#
########################################################################
print('Check if each ProbeSet exist in database')
##---- find PID is name or target ----##
line = fp.readline()
line = fp.readline()
line2 = line.strip().split('\t')
line2 = [x.strip() for x in line2]
PId = line2[0]
db.execute('select Id from ProbeSet where Name="%s" and ChipId=%d' %
(PId, GeneChipId))
results = db.fetchall()
IdStr = 'TargetId'
if len(results) > 0:
IdStr = 'Name'
##---- get Name/TargetId list from database ----##
db.execute('select distinct(%s) from ProbeSet where ChipId=%d order by %s' % (
IdStr, GeneChipId, IdStr))
results = db.fetchall()
Names = []
for item in results:
Names.append(item[0])
Names = sorted(map(string.lower, Names))
##---- compare genelist with names ----##
x = y = 0
x1 = -1
GeneList2 = []
while x < len(GeneList) and y < len(Names):
if GeneList[x] == Names[y]:
x += 1
y += 1
elif GeneList[x] < Names[y]:
if x != x1:
GeneList2.append(GeneList[x])
x1 = x
x += 1
elif GeneList[x] > Names[y]:
y += 1
if x % 100000 == 0:
print(('check Name, checked %d lines' % x))
while x < len(GeneList):
GeneList2.append(GeneList[x])
x += 1
isCont = 1
ferror = open("ProbeSetError.txt", "wb")
for item in GeneList2:
ferror.write(item + " doesn't exist \n")
isCont = 0
print((item, " doesn't exist"))
if isCont == 0:
sys.exit(0)
print(('used ', time.time()-time0, ' seconds'))
#############################
# Insert new Data into SE
############################
db.execute("""
select ProbeSet.%s, ProbeSetXRef.DataId from ProbeSet, ProbeSetXRef
where ProbeSet.Id=ProbeSetXRef.ProbeSetId and ProbeSetXRef.ProbeSetFreezeId=%d"""
% (IdStr, ProbeSetFreezeId))
results = db.fetchall()
ProbeNameId = {}
for Name, Id in results:
ProbeNameId[Name] = Id
ferror = open("ProbeError.txt", "wb")
DataValues = []
fp.seek(0) # XZ add this line
line = fp.readline() # XZ add this line
line = fp.readline()
kj = 0
while line:
line2 = line.strip().split('\t')
line2 = [x.strip() for x in line2]
CellId = line2[0]
if CellId not in ProbeNameId:
ferror.write(CellId + " doesn't exist\n")
else:
DataId = ProbeNameId[CellId]
datasorig = line2[dataStart:]
i = 0
for item in datasorig:
if item != '':
value = '('+str(DataId)+','+str(Ids[i])+','+str(item)+')'
DataValues.append(value)
i += 1
kj += 1
if kj % 100 == 0:
Dataitems = ','.join(DataValues)
cmd = 'insert ProbeSetSE values %s' % Dataitems
db.execute(cmd)
DataValues = []
line = fp.readline()
print((CellId, " doesn't exist"))
print(('inserted ', kj, ' lines'))
print(('used ', time.time()-time0, ' seconds'))
if len(DataValues) > 0:
DataValues = ','.join(DataValues)
cmd = 'insert ProbeSetSE values %s' % DataValues
db.execute(cmd)
con.close()
| agpl-3.0 |
sixfeetup/cloud-custodian | tools/dev/license-headers.py | 3 | 2290 | # Copyright 2016-2017 Capital One Services, LLC
#
# 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.
"""Add License headers to all py files."""
import fnmatch
import os
import inspect
import sys
import c7n
header = """\
# Copyright 2017 Capital One Services, LLC
#
# 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
#
"""
suffix = """\
# 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.
"""
def update_headers(src_tree):
"""Main."""
print "src tree", src_tree
for root, dirs, files in os.walk(src_tree):
py_files = fnmatch.filter(files, "*.py")
for f in py_files:
print "checking", f
p = os.path.join(root, f)
with open(p) as fh:
contents = fh.read()
if suffix in contents:
continue
print("Adding license header to %s" % p)
with open(p, 'w') as fh:
fh.write(
'%s%s%s' % (header, suffix, contents))
def main():
explicit = False
if len(sys.argv) == 2:
explicit = True
srctree = os.path.abspath(sys.argv[1])
else:
srctree = os.path.dirname(inspect.getabsfile(c7n))
update_headers(srctree)
if not explicit:
update_headers(os.path.abspath('tests'))
update_headers(os.path.abspath('ftests'))
if __name__ == '__main__':
main()
| apache-2.0 |
metaml/nupic | src/nupic/encoders/scalar.py | 14 | 25279 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013-2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import math
import numbers
import numpy
from nupic.data import SENTINEL_VALUE_FOR_MISSING_DATA
from nupic.data.fieldmeta import FieldMetaType
from nupic.bindings.math import SM32, GetNTAReal
from nupic.encoders.base import Encoder, EncoderResult
DEFAULT_RADIUS = 0
DEFAULT_RESOLUTION = 0
class ScalarEncoder(Encoder):
"""
A scalar encoder encodes a numeric (floating point) value into an array
of bits. The output is 0's except for a contiguous block of 1's. The
location of this contiguous block varies continuously with the input value.
The encoding is linear. If you want a nonlinear encoding, just transform
the scalar (e.g. by applying a logarithm function) before encoding.
It is not recommended to bin the data as a pre-processing step, e.g.
"1" = $0 - $.20, "2" = $.21-$0.80, "3" = $.81-$1.20, etc. as this
removes a lot of information and prevents nearby values from overlapping
in the output. Instead, use a continuous transformation that scales
the data (a piecewise transformation is fine).
Parameters:
-----------------------------------------------------------------------------
w -- The number of bits that are set to encode a single value - the
"width" of the output signal
restriction: w must be odd to avoid centering problems.
minval -- The minimum value of the input signal.
maxval -- The upper bound of the input signal
periodic -- If true, then the input value "wraps around" such that minval = maxval
For a periodic value, the input must be strictly less than maxval,
otherwise maxval is a true upper bound.
There are three mutually exclusive parameters that determine the overall size of
of the output. Only one of these should be specifed to the constructor:
n -- The number of bits in the output. Must be greater than or equal to w
radius -- Two inputs separated by more than the radius have non-overlapping
representations. Two inputs separated by less than the radius will
in general overlap in at least some of their bits. You can think
of this as the radius of the input.
resolution -- Two inputs separated by greater than, or equal to the resolution are guaranteed
to have different representations.
Note: radius and resolution are specified w.r.t the input, not output. w is
specified w.r.t. the output.
Example:
day of week.
w = 3
Minval = 1 (Monday)
Maxval = 8 (Monday)
periodic = true
n = 14
[equivalently: radius = 1.5 or resolution = 0.5]
The following values would encode midnight -- the start of the day
monday (1) -> 11000000000001
tuesday(2) -> 01110000000000
wednesday(3) -> 00011100000000
...
sunday (7) -> 10000000000011
Since the resolution is 12 hours, we can also encode noon, as
monday noon -> 11100000000000
monday midnt-> 01110000000000
tuesday noon -> 00111000000000
etc.
It may not be natural to specify "n", especially with non-periodic
data. For example, consider encoding an input with a range of 1-10
(inclusive) using an output width of 5. If you specify resolution =
1, this means that inputs of 1 and 2 have different outputs, though
they overlap, but 1 and 1.5 might not have different outputs.
This leads to a 14-bit representation like this:
1 -> 11111000000000 (14 bits total)
2 -> 01111100000000
...
10-> 00000000011111
[resolution = 1; n=14; radius = 5]
You could specify resolution = 0.5, which gives
1 -> 11111000... (22 bits total)
1.5 -> 011111.....
2.0 -> 0011111....
[resolution = 0.5; n=22; radius=2.5]
You could specify radius = 1, which gives
1 -> 111110000000.... (50 bits total)
2 -> 000001111100....
3 -> 000000000011111...
...
10 -> .....000011111
[radius = 1; resolution = 0.2; n=50]
An N/M encoding can also be used to encode a binary value,
where we want more than one bit to represent each state.
For example, we could have: w = 5, minval = 0, maxval = 1,
radius = 1 (which is equivalent to n=10)
0 -> 1111100000
1 -> 0000011111
Implementation details:
--------------------------------------------------------------------------
range = maxval - minval
h = (w-1)/2 (half-width)
resolution = radius / w
n = w * range/radius (periodic)
n = w * range/radius + 2 * h (non-periodic)
"""
def __init__(self,
w,
minval,
maxval,
periodic=False,
n=0,
radius=DEFAULT_RADIUS,
resolution=DEFAULT_RESOLUTION,
name=None,
verbosity=0,
clipInput=False,
forced=False):
"""
w -- number of bits to set in output
minval -- minimum input value
maxval -- maximum input value (input is strictly less if periodic == True)
Exactly one of n, radius, resolution must be set. "0" is a special
value that means "not set".
n -- number of bits in the representation (must be > w)
radius -- inputs separated by more than, or equal to this distance will have non-overlapping
representations
resolution -- inputs separated by more than, or equal to this distance will have different
representations
name -- an optional string which will become part of the description
clipInput -- if true, non-periodic inputs smaller than minval or greater
than maxval will be clipped to minval/maxval
forced -- if true, skip some safety checks (for compatibility reasons), default false
See class documentation for more information.
"""
assert isinstance(w, numbers.Integral)
self.encoders = None
self.verbosity = verbosity
self.w = w
if (w % 2 == 0):
raise Exception("Width must be an odd number (%f)" % w)
self.minval = minval
self.maxval = maxval
self.periodic = periodic
self.clipInput = clipInput
self.halfwidth = (w - 1) / 2
# For non-periodic inputs, padding is the number of bits "outside" the range,
# on each side. I.e. the representation of minval is centered on some bit, and
# there are "padding" bits to the left of that centered bit; similarly with
# bits to the right of the center bit of maxval
if self.periodic:
self.padding = 0
else:
self.padding = self.halfwidth
if (minval is not None and maxval is not None):
if (minval >= maxval):
raise Exception("The encoder for %s is invalid. minval %s is greater than "
"or equal to maxval %s. minval must be strictly less "
"than maxval." % (name, minval, maxval))
self.rangeInternal = float(self.maxval - self.minval)
# There are three different ways of thinking about the representation. Handle
# each case here.
self._initEncoder(w, minval, maxval, n, radius, resolution)
# nInternal represents the output area excluding the possible padding on each
# side
if (minval is not None and maxval is not None):
self.nInternal = self.n - 2 * self.padding
# Our name
if name is not None:
self.name = name
else:
self.name = "[%s:%s]" % (self.minval, self.maxval)
# This matrix is used for the topDownCompute. We build it the first time
# topDownCompute is called
self._topDownMappingM = None
self._topDownValues = None
# This list is created by getBucketValues() the first time it is called,
# and re-created whenever our buckets would be re-arranged.
self._bucketValues = None
# checks for likely mistakes in encoder settings
if not forced:
self._checkReasonableSettings()
def _initEncoder(self, w, minval, maxval, n, radius, resolution):
""" (helper function) There are three different ways of thinking about the representation.
Handle each case here."""
if n != 0:
if (radius !=0 or resolution != 0):
raise ValueError("Only one of n/radius/resolution can be specified for a ScalarEncoder")
assert n > w
self.n = n
if (minval is not None and maxval is not None):
if not self.periodic:
self.resolution = float(self.rangeInternal) / (self.n - self.w)
else:
self.resolution = float(self.rangeInternal) / (self.n)
self.radius = self.w * self.resolution
if self.periodic:
self.range = self.rangeInternal
else:
self.range = self.rangeInternal + self.resolution
else:
if radius != 0:
if (resolution != 0):
raise ValueError("Only one of radius/resolution can be specified for a ScalarEncoder")
self.radius = radius
self.resolution = float(self.radius) / w
elif resolution != 0:
self.resolution = float(resolution)
self.radius = self.resolution * self.w
else:
raise Exception("One of n, radius, resolution must be specified for a ScalarEncoder")
if (minval is not None and maxval is not None):
if self.periodic:
self.range = self.rangeInternal
else:
self.range = self.rangeInternal + self.resolution
nfloat = self.w * (self.range / self.radius) + 2 * self.padding
self.n = int(math.ceil(nfloat))
def _checkReasonableSettings(self):
"""(helper function) check if the settings are reasonable for SP to work"""
# checks for likely mistakes in encoder settings
if self.w < 21:
raise ValueError("Number of bits in the SDR (%d) must be greater than 2, and recommended >= 21 (use forced=True to override)"
% self.w)
def getDecoderOutputFieldTypes(self):
""" [Encoder class virtual method override]
"""
return (FieldMetaType.float, )
def getWidth(self):
return self.n
def _recalcParams(self):
self.rangeInternal = float(self.maxval - self.minval)
if not self.periodic:
self.resolution = float(self.rangeInternal) / (self.n - self.w)
else:
self.resolution = float(self.rangeInternal) / (self.n)
self.radius = self.w * self.resolution
if self.periodic:
self.range = self.rangeInternal
else:
self.range = self.rangeInternal + self.resolution
name = "[%s:%s]" % (self.minval, self.maxval)
def getDescription(self):
return [(self.name, 0)]
def _getFirstOnBit(self, input):
""" Return the bit offset of the first bit to be set in the encoder output.
For periodic encoders, this can be a negative number when the encoded output
wraps around. """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return [None]
else:
if input < self.minval:
# Don't clip periodic inputs. Out-of-range input is always an error
if self.clipInput and not self.periodic:
if self.verbosity > 0:
print "Clipped input %s=%.2f to minval %.2f" % (self.name, input,
self.minval)
input = self.minval
else:
raise Exception('input (%s) less than range (%s - %s)' %
(str(input), str(self.minval), str(self.maxval)))
if self.periodic:
# Don't clip periodic inputs. Out-of-range input is always an error
if input >= self.maxval:
raise Exception('input (%s) greater than periodic range (%s - %s)' %
(str(input), str(self.minval), str(self.maxval)))
else:
if input > self.maxval:
if self.clipInput:
if self.verbosity > 0:
print "Clipped input %s=%.2f to maxval %.2f" % (self.name, input,
self.maxval)
input = self.maxval
else:
raise Exception('input (%s) greater than range (%s - %s)' %
(str(input), str(self.minval), str(self.maxval)))
if self.periodic:
centerbin = int((input - self.minval) * self.nInternal / self.range) \
+ self.padding
else:
centerbin = int(((input - self.minval) + self.resolution/2) \
/ self.resolution ) + self.padding
# We use the first bit to be set in the encoded output as the bucket index
minbin = centerbin - self.halfwidth
return [minbin]
def getBucketIndices(self, input):
""" See method description in base.py """
if type(input) is float and math.isnan(input):
input = SENTINEL_VALUE_FOR_MISSING_DATA
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return [None]
minbin = self._getFirstOnBit(input)[0]
# For periodic encoders, the bucket index is the index of the center bit
if self.periodic:
bucketIdx = minbin + self.halfwidth
if bucketIdx < 0:
bucketIdx += self.n
# for non-periodic encoders, the bucket index is the index of the left bit
else:
bucketIdx = minbin
return [bucketIdx]
def encodeIntoArray(self, input, output, learn=True):
""" See method description in base.py """
if input is not None and not isinstance(input, numbers.Number):
raise TypeError(
"Expected a scalar input but got input of type %s" % type(input))
if type(input) is float and math.isnan(input):
input = SENTINEL_VALUE_FOR_MISSING_DATA
# Get the bucket index to use
bucketIdx = self._getFirstOnBit(input)[0]
if bucketIdx is None:
# None is returned for missing value
output[0:self.n] = 0 #TODO: should all 1s, or random SDR be returned instead?
else:
# The bucket index is the index of the first bit to set in the output
output[:self.n] = 0
minbin = bucketIdx
maxbin = minbin + 2*self.halfwidth
if self.periodic:
# Handle the edges by computing wrap-around
if maxbin >= self.n:
bottombins = maxbin - self.n + 1
output[:bottombins] = 1
maxbin = self.n - 1
if minbin < 0:
topbins = -minbin
output[self.n - topbins:self.n] = 1
minbin = 0
assert minbin >= 0
assert maxbin < self.n
# set the output (except for periodic wraparound)
output[minbin:maxbin + 1] = 1
# Debug the decode() method
if self.verbosity >= 2:
print
print "input:", input
print "range:", self.minval, "-", self.maxval
print "n:", self.n, "w:", self.w, "resolution:", self.resolution, \
"radius", self.radius, "periodic:", self.periodic
print "output:",
self.pprint(output)
print "input desc:", self.decodedToStr(self.decode(output))
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
# For now, we simply assume any top-down output greater than 0
# is ON. Eventually, we will probably want to incorporate the strength
# of each top-down output.
tmpOutput = numpy.array(encoded[:self.n] > 0).astype(encoded.dtype)
if not tmpOutput.any():
return (dict(), [])
# ------------------------------------------------------------------------
# First, assume the input pool is not sampled 100%, and fill in the
# "holes" in the encoded representation (which are likely to be present
# if this is a coincidence that was learned by the SP).
# Search for portions of the output that have "holes"
maxZerosInARow = self.halfwidth
for i in xrange(maxZerosInARow):
searchStr = numpy.ones(i + 3, dtype=encoded.dtype)
searchStr[1:-1] = 0
subLen = len(searchStr)
# Does this search string appear in the output?
if self.periodic:
for j in xrange(self.n):
outputIndices = numpy.arange(j, j + subLen)
outputIndices %= self.n
if numpy.array_equal(searchStr, tmpOutput[outputIndices]):
tmpOutput[outputIndices] = 1
else:
for j in xrange(self.n - subLen + 1):
if numpy.array_equal(searchStr, tmpOutput[j:j + subLen]):
tmpOutput[j:j + subLen] = 1
if self.verbosity >= 2:
print "raw output:", encoded[:self.n]
print "filtered output:", tmpOutput
# ------------------------------------------------------------------------
# Find each run of 1's.
nz = tmpOutput.nonzero()[0]
runs = [] # will be tuples of (startIdx, runLength)
run = [nz[0], 1]
i = 1
while (i < len(nz)):
if nz[i] == run[0] + run[1]:
run[1] += 1
else:
runs.append(run)
run = [nz[i], 1]
i += 1
runs.append(run)
# If we have a periodic encoder, merge the first and last run if they
# both go all the way to the edges
if self.periodic and len(runs) > 1:
if runs[0][0] == 0 and runs[-1][0] + runs[-1][1] == self.n:
runs[-1][1] += runs[0][1]
runs = runs[1:]
# ------------------------------------------------------------------------
# Now, for each group of 1's, determine the "left" and "right" edges, where
# the "left" edge is inset by halfwidth and the "right" edge is inset by
# halfwidth.
# For a group of width w or less, the "left" and "right" edge are both at
# the center position of the group.
ranges = []
for run in runs:
(start, runLen) = run
if runLen <= self.w:
left = right = start + runLen / 2
else:
left = start + self.halfwidth
right = start + runLen - 1 - self.halfwidth
# Convert to input space.
if not self.periodic:
inMin = (left - self.padding) * self.resolution + self.minval
inMax = (right - self.padding) * self.resolution + self.minval
else:
inMin = (left - self.padding) * self.range / self.nInternal + self.minval
inMax = (right - self.padding) * self.range / self.nInternal + self.minval
# Handle wrap-around if periodic
if self.periodic:
if inMin >= self.maxval:
inMin -= self.range
inMax -= self.range
# Clip low end
if inMin < self.minval:
inMin = self.minval
if inMax < self.minval:
inMax = self.minval
# If we have a periodic encoder, and the max is past the edge, break into
# 2 separate ranges
if self.periodic and inMax >= self.maxval:
ranges.append([inMin, self.maxval])
ranges.append([self.minval, inMax - self.range])
else:
if inMax > self.maxval:
inMax = self.maxval
if inMin > self.maxval:
inMin = self.maxval
ranges.append([inMin, inMax])
desc = self._generateRangeDescription(ranges)
# Return result
if parentFieldName != '':
fieldName = "%s.%s" % (parentFieldName, self.name)
else:
fieldName = self.name
return ({fieldName: (ranges, desc)}, [fieldName])
def _generateRangeDescription(self, ranges):
"""generate description from a text description of the ranges"""
desc = ""
numRanges = len(ranges)
for i in xrange(numRanges):
if ranges[i][0] != ranges[i][1]:
desc += "%.2f-%.2f" % (ranges[i][0], ranges[i][1])
else:
desc += "%.2f" % (ranges[i][0])
if i < numRanges - 1:
desc += ", "
return desc
def _getTopDownMapping(self):
""" Return the interal _topDownMappingM matrix used for handling the
bucketInfo() and topDownCompute() methods. This is a matrix, one row per
category (bucket) where each row contains the encoded output for that
category.
"""
# Do we need to build up our reverse mapping table?
if self._topDownMappingM is None:
# The input scalar value corresponding to each possible output encoding
if self.periodic:
self._topDownValues = numpy.arange(self.minval + self.resolution / 2.0,
self.maxval,
self.resolution)
else:
#Number of values is (max-min)/resolutions
self._topDownValues = numpy.arange(self.minval,
self.maxval + self.resolution / 2.0,
self.resolution)
# Each row represents an encoded output pattern
numCategories = len(self._topDownValues)
self._topDownMappingM = SM32(numCategories, self.n)
outputSpace = numpy.zeros(self.n, dtype=GetNTAReal())
for i in xrange(numCategories):
value = self._topDownValues[i]
value = max(value, self.minval)
value = min(value, self.maxval)
self.encodeIntoArray(value, outputSpace, learn=False)
self._topDownMappingM.setRowFromDense(i, outputSpace)
return self._topDownMappingM
def getBucketValues(self):
""" See the function description in base.py """
# Need to re-create?
if self._bucketValues is None:
topDownMappingM = self._getTopDownMapping()
numBuckets = topDownMappingM.nRows()
self._bucketValues = []
for bucketIdx in range(numBuckets):
self._bucketValues.append(self.getBucketInfo([bucketIdx])[0].value)
return self._bucketValues
def getBucketInfo(self, buckets):
""" See the function description in base.py """
# Get/generate the topDown mapping table
#NOTE: although variable topDownMappingM is unused, some (bad-style) actions
#are executed during _getTopDownMapping() so this line must stay here
topDownMappingM = self._getTopDownMapping()
# The "category" is simply the bucket index
category = buckets[0]
encoding = self._topDownMappingM.getRow(category)
# Which input value does this correspond to?
if self.periodic:
inputVal = (self.minval + (self.resolution / 2.0) +
(category * self.resolution))
else:
inputVal = self.minval + (category * self.resolution)
return [EncoderResult(value=inputVal, scalar=inputVal, encoding=encoding)]
def topDownCompute(self, encoded):
""" See the function description in base.py
"""
# Get/generate the topDown mapping table
topDownMappingM = self._getTopDownMapping()
# See which "category" we match the closest.
category = topDownMappingM.rightVecProd(encoded).argmax()
# Return that bucket info
return self.getBucketInfo([category])
def closenessScores(self, expValues, actValues, fractional=True):
""" See the function description in base.py
"""
expValue = expValues[0]
actValue = actValues[0]
if self.periodic:
expValue = expValue % self.maxval
actValue = actValue % self.maxval
err = abs(expValue - actValue)
if self.periodic:
err = min(err, self.maxval - err)
if fractional:
pctErr = float(err) / (self.maxval - self.minval)
pctErr = min(1.0, pctErr)
closeness = 1.0 - pctErr
else:
closeness = err
return numpy.array([closeness])
def dump(self):
print "ScalarEncoder:"
print " min: %f" % self.minval
print " max: %f" % self.maxval
print " w: %d" % self.w
print " n: %d" % self.n
print " resolution: %f" % self.resolution
print " radius: %f" % self.radius
print " periodic: %s" % self.periodic
print " nInternal: %d" % self.nInternal
print " rangeInternal: %f" % self.rangeInternal
print " padding: %d" % self.padding
@classmethod
def read(cls, proto):
if proto.n is not None:
radius = DEFAULT_RADIUS
resolution = DEFAULT_RESOLUTION
else:
radius = proto.radius
resolution = proto.resolution
return cls(w=proto.w,
minval=proto.minval,
maxval=proto.maxval,
periodic=proto.periodic,
n=proto.n,
name=proto.name,
verbosity=proto.verbosity,
clipInput=proto.clipInput,
forced=True)
def write(self, proto):
proto.w = self.w
proto.minval = self.minval
proto.maxval = self.maxval
proto.periodic = self.periodic
# Radius and resolution can be recalculated based on n
proto.n = self.n
proto.name = self.name
proto.verbosity = self.verbosity
proto.clipInput = self.clipInput
| agpl-3.0 |
davidmueller13/Vindicator-flo-aosp | scripts/gcc-wrapper.py | 473 | 3422 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT 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.
# Invoke gcc, looking for warnings, and causing a failure if there are
# non-whitelisted warnings.
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"alignment.c:327",
"mmu.c:602",
"return_address.c:62",
])
# Capture the name of the object file, can find it.
ofile = None
warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''')
def interpret_warning(line):
"""Decode the message from gcc. The messages we care about have a filename, and a warning"""
line = line.rstrip('\n')
m = warning_re.match(line)
if m and m.group(2) not in allowed_warnings:
print "error, forbidden warning:", m.group(2)
# If there is a warning, remove any object if it exists.
if ofile:
try:
os.remove(ofile)
except OSError:
pass
sys.exit(1)
def run_gcc():
args = sys.argv[1:]
# Look for -o
try:
i = args.index('-o')
global ofile
ofile = args[i+1]
except (ValueError, IndexError):
pass
compiler = sys.argv[0]
try:
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
for line in proc.stderr:
print line,
interpret_warning(line)
result = proc.wait()
except OSError as e:
result = e.errno
if result == errno.ENOENT:
print args[0] + ':',e.strerror
print 'Is your PATH set correctly?'
else:
print ' '.join(args), str(e)
return result
if __name__ == '__main__':
status = run_gcc()
sys.exit(status)
| gpl-2.0 |
DaniilLeksin/theblog | env/lib/python2.7/site-packages/django/core/urlresolvers.py | 43 | 23384 | """
This module converts requested URLs to callback view functions.
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
a string) and returns a tuple in this format:
(view_function, function_args, function_kwargs)
"""
from __future__ import unicode_literals
import functools
from importlib import import_module
import re
from threading import local
from django.http import Http404
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text, iri_to_uri
from django.utils.functional import lazy
from django.utils.http import urlquote
from django.utils.module_loading import module_has_submodule
from django.utils.regex_helper import normalize
from django.utils import six, lru_cache
from django.utils.translation import get_language
# SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for
# the current thread (which is the only one we ever access), it is assumed to
# be empty.
_prefixes = local()
# Overridden URLconfs for each thread are stored here.
_urlconfs = local()
class ResolverMatch(object):
def __init__(self, func, args, kwargs, url_name=None, app_name=None, namespaces=None):
self.func = func
self.args = args
self.kwargs = kwargs
self.app_name = app_name
if namespaces:
self.namespaces = [x for x in namespaces if x]
else:
self.namespaces = []
if not url_name:
if not hasattr(func, '__name__'):
# An instance of a callable class
url_name = '.'.join([func.__class__.__module__, func.__class__.__name__])
else:
# A function
url_name = '.'.join([func.__module__, func.__name__])
self.url_name = url_name
@property
def namespace(self):
return ':'.join(self.namespaces)
@property
def view_name(self):
return ':'.join(filter(bool, (self.namespace, self.url_name)))
def __getitem__(self, index):
return (self.func, self.args, self.kwargs)[index]
def __repr__(self):
return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name='%s', app_name='%s', namespace='%s')" % (
self.func, self.args, self.kwargs, self.url_name, self.app_name, self.namespace)
class Resolver404(Http404):
pass
class NoReverseMatch(Exception):
pass
@lru_cache.lru_cache(maxsize=None)
def get_callable(lookup_view, can_fail=False):
"""
Convert a string version of a function name to the callable object.
If the lookup_view is not an import path, it is assumed to be a URL pattern
label and the original string is returned.
If can_fail is True, lookup_view might be a URL pattern label, so errors
during the import fail and the string is returned.
"""
if not callable(lookup_view):
mod_name, func_name = get_mod_func(lookup_view)
if func_name == '':
return lookup_view
try:
mod = import_module(mod_name)
except ImportError:
parentmod, submod = get_mod_func(mod_name)
if (not can_fail and submod != '' and
not module_has_submodule(import_module(parentmod), submod)):
raise ViewDoesNotExist(
"Could not import %s. Parent module %s does not exist." %
(lookup_view, mod_name))
if not can_fail:
raise
else:
try:
lookup_view = getattr(mod, func_name)
if not callable(lookup_view):
raise ViewDoesNotExist(
"Could not import %s.%s. View is not callable." %
(mod_name, func_name))
except AttributeError:
if not can_fail:
raise ViewDoesNotExist(
"Could not import %s. View does not exist in module %s." %
(lookup_view, mod_name))
return lookup_view
@lru_cache.lru_cache(maxsize=None)
def get_resolver(urlconf):
if urlconf is None:
from django.conf import settings
urlconf = settings.ROOT_URLCONF
return RegexURLResolver(r'^/', urlconf)
@lru_cache.lru_cache(maxsize=None)
def get_ns_resolver(ns_pattern, resolver):
# Build a namespaced resolver for the given parent urlconf pattern.
# This makes it possible to have captured parameters in the parent
# urlconf pattern.
ns_resolver = RegexURLResolver(ns_pattern, resolver.url_patterns)
return RegexURLResolver(r'^/', [ns_resolver])
def get_mod_func(callback):
# Converts 'django.views.news.stories.story_detail' to
# ['django.views.news.stories', 'story_detail']
try:
dot = callback.rindex('.')
except ValueError:
return callback, ''
return callback[:dot], callback[dot + 1:]
class LocaleRegexProvider(object):
"""
A mixin to provide a default regex property which can vary by active
language.
"""
def __init__(self, regex):
# regex is either a string representing a regular expression, or a
# translatable string (using ugettext_lazy) representing a regular
# expression.
self._regex = regex
self._regex_dict = {}
@property
def regex(self):
"""
Returns a compiled regular expression, depending upon the activated
language-code.
"""
language_code = get_language()
if language_code not in self._regex_dict:
if isinstance(self._regex, six.string_types):
regex = self._regex
else:
regex = force_text(self._regex)
try:
compiled_regex = re.compile(regex, re.UNICODE)
except re.error as e:
raise ImproperlyConfigured(
'"%s" is not a valid regular expression: %s' %
(regex, six.text_type(e)))
self._regex_dict[language_code] = compiled_regex
return self._regex_dict[language_code]
class RegexURLPattern(LocaleRegexProvider):
def __init__(self, regex, callback, default_args=None, name=None):
LocaleRegexProvider.__init__(self, regex)
# callback is either a string like 'foo.views.news.stories.story_detail'
# which represents the path to a module and a view function name, or a
# callable object (view).
if callable(callback):
self._callback = callback
else:
self._callback = None
self._callback_str = callback
self.default_args = default_args or {}
self.name = name
def __repr__(self):
return force_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
def add_prefix(self, prefix):
"""
Adds the prefix string to a string-based callback.
"""
if not prefix or not hasattr(self, '_callback_str'):
return
self._callback_str = prefix + '.' + self._callback_str
def resolve(self, path):
match = self.regex.search(path)
if match:
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments as
# positional arguments.
kwargs = match.groupdict()
if kwargs:
args = ()
else:
args = match.groups()
# In both cases, pass any extra_kwargs as **kwargs.
kwargs.update(self.default_args)
return ResolverMatch(self.callback, args, kwargs, self.name)
@property
def callback(self):
if self._callback is not None:
return self._callback
self._callback = get_callable(self._callback_str)
return self._callback
class RegexURLResolver(LocaleRegexProvider):
def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
LocaleRegexProvider.__init__(self, regex)
# urlconf_name is a string representing the module containing URLconfs.
self.urlconf_name = urlconf_name
if not isinstance(urlconf_name, six.string_types):
self._urlconf_module = self.urlconf_name
self.callback = None
self.default_kwargs = default_kwargs or {}
self.namespace = namespace
self.app_name = app_name
self._reverse_dict = {}
self._namespace_dict = {}
self._app_dict = {}
# set of dotted paths to all functions and classes that are used in
# urlpatterns
self._callback_strs = set()
self._populated = False
def __repr__(self):
if isinstance(self.urlconf_name, list) and len(self.urlconf_name):
# Don't bother to output the whole list, it can be huge
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
else:
urlconf_repr = repr(self.urlconf_name)
return str('<%s %s (%s:%s) %s>') % (
self.__class__.__name__, urlconf_repr, self.app_name,
self.namespace, self.regex.pattern)
def _populate(self):
lookups = MultiValueDict()
namespaces = {}
apps = {}
language_code = get_language()
for pattern in reversed(self.url_patterns):
if hasattr(pattern, '_callback_str'):
self._callback_strs.add(pattern._callback_str)
elif hasattr(pattern, '_callback'):
callback = pattern._callback
if isinstance(callback, functools.partial):
callback = callback.func
if not hasattr(callback, '__name__'):
lookup_str = callback.__module__ + "." + callback.__class__.__name__
else:
lookup_str = callback.__module__ + "." + callback.__name__
self._callback_strs.add(lookup_str)
p_pattern = pattern.regex.pattern
if p_pattern.startswith('^'):
p_pattern = p_pattern[1:]
if isinstance(pattern, RegexURLResolver):
if pattern.namespace:
namespaces[pattern.namespace] = (p_pattern, pattern)
if pattern.app_name:
apps.setdefault(pattern.app_name, []).append(pattern.namespace)
else:
parent_pat = pattern.regex.pattern
for name in pattern.reverse_dict:
for matches, pat, defaults in pattern.reverse_dict.getlist(name):
new_matches = normalize(parent_pat + pat)
lookups.appendlist(name, (new_matches, p_pattern + pat, dict(defaults, **pattern.default_kwargs)))
for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():
namespaces[namespace] = (p_pattern + prefix, sub_pattern)
for app_name, namespace_list in pattern.app_dict.items():
apps.setdefault(app_name, []).extend(namespace_list)
self._callback_strs.update(pattern._callback_strs)
else:
bits = normalize(p_pattern)
lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))
if pattern.name is not None:
lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))
self._reverse_dict[language_code] = lookups
self._namespace_dict[language_code] = namespaces
self._app_dict[language_code] = apps
self._populated = True
@property
def reverse_dict(self):
language_code = get_language()
if language_code not in self._reverse_dict:
self._populate()
return self._reverse_dict[language_code]
@property
def namespace_dict(self):
language_code = get_language()
if language_code not in self._namespace_dict:
self._populate()
return self._namespace_dict[language_code]
@property
def app_dict(self):
language_code = get_language()
if language_code not in self._app_dict:
self._populate()
return self._app_dict[language_code]
def _is_callback(self, name):
if not self._populated:
self._populate()
return name in self._callback_strs
def resolve(self, path):
path = force_text(path) # path may be a reverse_lazy object
tried = []
match = self.regex.search(path)
if match:
new_path = path[match.end():]
for pattern in self.url_patterns:
try:
sub_match = pattern.resolve(new_path)
except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
tried.extend([pattern] + t for t in sub_tried)
else:
tried.append([pattern])
else:
if sub_match:
sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
sub_match_dict.update(sub_match.kwargs)
return ResolverMatch(sub_match.func, sub_match.args, sub_match_dict, sub_match.url_name, self.app_name or sub_match.app_name, [self.namespace] + sub_match.namespaces)
tried.append([pattern])
raise Resolver404({'tried': tried, 'path': new_path})
raise Resolver404({'path': path})
@property
def urlconf_module(self):
try:
return self._urlconf_module
except AttributeError:
self._urlconf_module = import_module(self.urlconf_name)
return self._urlconf_module
@property
def url_patterns(self):
# urlconf_module might be a valid set of patterns, so we default to it
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
try:
iter(patterns)
except TypeError:
msg = (
"The included urlconf '{name}' does not appear to have any "
"patterns in it. If you see valid patterns in the file then "
"the issue is probably caused by a circular import."
)
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
return patterns
def _resolve_special(self, view_type):
callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
if not callback:
# No handler specified in file; use default
# Lazy import, since django.urls imports this file
from django.conf import urls
callback = getattr(urls, 'handler%s' % view_type)
return get_callable(callback), {}
def resolve400(self):
return self._resolve_special('400')
def resolve403(self):
return self._resolve_special('403')
def resolve404(self):
return self._resolve_special('404')
def resolve500(self):
return self._resolve_special('500')
def reverse(self, lookup_view, *args, **kwargs):
return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
if args and kwargs:
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
text_args = [force_text(v) for v in args]
text_kwargs = dict((k, force_text(v)) for (k, v) in kwargs.items())
if not self._populated:
self._populate()
try:
if self._is_callback(lookup_view):
lookup_view = get_callable(lookup_view, True)
except (ImportError, AttributeError) as e:
raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
possibilities = self.reverse_dict.getlist(lookup_view)
prefix_norm, prefix_args = normalize(urlquote(_prefix))[0]
for possibility, pattern, defaults in possibilities:
for result, params in possibility:
if args:
if len(args) != len(params) + len(prefix_args):
continue
candidate_subs = dict(zip(prefix_args + params, text_args))
else:
if set(kwargs.keys()) | set(defaults.keys()) != set(params) | set(defaults.keys()) | set(prefix_args):
continue
matches = True
for k, v in defaults.items():
if kwargs.get(k, v) != v:
matches = False
break
if not matches:
continue
candidate_subs = text_kwargs
# WSGI provides decoded URLs, without %xx escapes, and the URL
# resolver operates on such URLs. First substitute arguments
# without quoting to build a decoded URL and look for a match.
# Then, if we have a match, redo the substitution with quoted
# arguments in order to return a properly encoded URL.
candidate_pat = prefix_norm.replace('%', '%%') + result
if re.search('^%s%s' % (prefix_norm, pattern), candidate_pat % candidate_subs, re.UNICODE):
candidate_subs = dict((k, urlquote(v)) for (k, v) in candidate_subs.items())
url = candidate_pat % candidate_subs
# Don't allow construction of scheme relative urls.
if url.startswith('//'):
url = '/%%2F%s' % url[2:]
return url
# lookup_view can be URL label, or dotted path, or callable, Any of
# these can be passed in at the top, but callables are not friendly in
# error messages.
m = getattr(lookup_view, '__module__', None)
n = getattr(lookup_view, '__name__', None)
if m is not None and n is not None:
lookup_view_s = "%s.%s" % (m, n)
else:
lookup_view_s = lookup_view
patterns = [pattern for (possibility, pattern, defaults) in possibilities]
raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
"arguments '%s' not found. %d pattern(s) tried: %s" %
(lookup_view_s, args, kwargs, len(patterns), patterns))
class LocaleRegexURLResolver(RegexURLResolver):
"""
A URL resolver that always matches the active language code as URL prefix.
Rather than taking a regex argument, we just override the ``regex``
function to always return the active language-code as regex.
"""
def __init__(self, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
super(LocaleRegexURLResolver, self).__init__(
None, urlconf_name, default_kwargs, app_name, namespace)
@property
def regex(self):
language_code = get_language()
if language_code not in self._regex_dict:
regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
self._regex_dict[language_code] = regex_compiled
return self._regex_dict[language_code]
def resolve(path, urlconf=None):
if urlconf is None:
urlconf = get_urlconf()
return get_resolver(urlconf).resolve(path)
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
if urlconf is None:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
if prefix is None:
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view = viewname
else:
parts = viewname.split(':')
parts.reverse()
view = parts[0]
path = parts[1:]
resolved_path = []
ns_pattern = ''
while path:
ns = path.pop()
# Lookup the name to see if it could be an app identifier
try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver
if current_app and current_app in app_list:
# If we are reversing for a particular app,
# use that namespace
ns = current_app
elif ns not in app_list:
# The name isn't shared by one of the instances
# (i.e., the default) so just pick the first instance
# as the default.
ns = app_list[0]
except KeyError:
pass
try:
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError as key:
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
(key, ':'.join(resolved_path)))
else:
raise NoReverseMatch("%s is not a registered namespace" %
key)
if ns_pattern:
resolver = get_ns_resolver(ns_pattern, resolver)
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
reverse_lazy = lazy(reverse, str)
def clear_url_caches():
get_callable.cache_clear()
get_resolver.cache_clear()
get_ns_resolver.cache_clear()
def set_script_prefix(prefix):
"""
Sets the script prefix for the current thread.
"""
if not prefix.endswith('/'):
prefix += '/'
_prefixes.value = prefix
def get_script_prefix():
"""
Returns the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
"""
return getattr(_prefixes, "value", '/')
def clear_script_prefix():
"""
Unsets the script prefix for the current thread.
"""
try:
del _prefixes.value
except AttributeError:
pass
def set_urlconf(urlconf_name):
"""
Sets the URLconf for the current thread (overriding the default one in
settings). Set to None to revert back to the default.
"""
if urlconf_name:
_urlconfs.value = urlconf_name
else:
if hasattr(_urlconfs, "value"):
del _urlconfs.value
def get_urlconf(default=None):
"""
Returns the root URLconf to use for the current thread if it has been
changed from the default one.
"""
return getattr(_urlconfs, "value", default)
def is_valid_path(path, urlconf=None):
"""
Returns True if the given path resolves against the default URL resolver,
False otherwise.
This is a convenience method to make working with "is this a match?" cases
easier, avoiding unnecessarily indented try...except blocks.
"""
try:
resolve(path, urlconf)
return True
except Resolver404:
return False
| gpl-2.0 |
tkinz27/ansible | v1/ansible/runner/connection_plugins/fireball.py | 110 | 4841 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
import json
import os
import base64
from ansible.callbacks import vvv
from ansible import utils
from ansible import errors
from ansible import constants
HAVE_ZMQ=False
try:
import zmq
HAVE_ZMQ=True
except ImportError:
pass
class Connection(object):
''' ZeroMQ accelerated connection '''
def __init__(self, runner, host, port, *args, **kwargs):
self.runner = runner
self.has_pipelining = False
# attempt to work around shared-memory funness
if getattr(self.runner, 'aes_keys', None):
utils.AES_KEYS = self.runner.aes_keys
self.host = host
self.key = utils.key_for_hostname(host)
self.context = None
self.socket = None
if port is None:
self.port = constants.ZEROMQ_PORT
else:
self.port = port
self.become_methods_supported=[]
def connect(self):
''' activates the connection object '''
if not HAVE_ZMQ:
raise errors.AnsibleError("zmq is not installed")
# this is rough/temporary and will likely be optimized later ...
self.context = zmq.Context()
socket = self.context.socket(zmq.REQ)
addr = "tcp://%s:%s" % (self.host, self.port)
socket.connect(addr)
self.socket = socket
return self
def exec_command(self, cmd, tmp_path, become_user, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the remote host '''
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
vvv("EXEC COMMAND %s" % cmd)
if self.runner.become and sudoable:
raise errors.AnsibleError(
"When using fireball, do not specify sudo or su to run your tasks. " +
"Instead sudo the fireball action with sudo. " +
"Task will communicate with the fireball already running in sudo mode."
)
data = dict(
mode='command',
cmd=cmd,
tmp_path=tmp_path,
executable=executable,
)
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
return (response.get('rc',None), '', response.get('stdout',''), response.get('stderr',''))
def put_file(self, in_path, out_path):
''' transfer a file from local to remote '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
data = file(in_path).read()
data = base64.b64encode(data)
data = dict(mode='put', data=data, out_path=out_path)
# TODO: support chunked file transfer
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
# no meaningful response needed for this
def fetch_file(self, in_path, out_path):
''' save a remote file to the specified path '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
data = dict(mode='fetch', in_path=in_path)
data = utils.jsonify(data)
data = utils.encrypt(self.key, data)
self.socket.send(data)
response = self.socket.recv()
response = utils.decrypt(self.key, response)
response = utils.parse_json(response)
response = response['data']
response = base64.b64decode(response)
fh = open(out_path, "w")
fh.write(response)
fh.close()
def close(self):
''' terminate the connection '''
# Be a good citizen
try:
self.socket.close()
self.context.term()
except:
pass
| gpl-3.0 |
madhurrajn/samashthi | lib/django/db/backends/mysql/features.py | 176 | 2682 | from django.db.backends.base.features import BaseDatabaseFeatures
from django.utils.functional import cached_property
from .base import Database
try:
import pytz
except ImportError:
pytz = None
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
update_can_self_select = False
allows_group_by_pk = True
related_fields_match_type = True
allow_sliced_subqueries = False
has_bulk_insert = True
has_select_for_update = True
has_select_for_update_nowait = False
supports_forward_references = False
supports_regex_backreferencing = False
supports_date_lookup_using_string = False
can_introspect_autofield = True
can_introspect_binary_field = False
can_introspect_small_integer_field = True
supports_timezones = False
requires_explicit_null_ordering_when_grouping = True
allows_auto_pk_0 = False
uses_savepoints = True
can_release_savepoints = True
atomic_transactions = False
supports_column_check_constraints = False
can_clone_databases = True
@cached_property
def _mysql_storage_engine(self):
"Internal method used in Django tests. Don't rely on this from your code"
with self.connection.cursor() as cursor:
cursor.execute("SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'")
result = cursor.fetchone()
return result[0]
@cached_property
def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != 'MyISAM'
@cached_property
def supports_microsecond_precision(self):
# See https://github.com/farcepest/MySQLdb1/issues/24 for the reason
# about requiring MySQLdb 1.2.5
return self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5)
@cached_property
def has_zoneinfo_database(self):
# MySQL accepts full time zones names (eg. Africa/Nairobi) but rejects
# abbreviations (eg. EAT). When pytz isn't installed and the current
# time zone is LocalTimezone (the only sensible value in this
# context), the current time zone name will be an abbreviation. As a
# consequence, MySQL cannot perform time zone conversions reliably.
if pytz is None:
return False
# Test if the time zone definitions are installed.
with self.connection.cursor() as cursor:
cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1")
return cursor.fetchone() is not None
def introspected_boolean_field_type(self, *args, **kwargs):
return 'IntegerField'
| bsd-3-clause |
sbalde/edx-platform | lms/djangoapps/ccx/overrides.py | 20 | 5407 | """
API related to providing field overrides for individual students. This is used
by the individual custom courses feature.
"""
import json
import logging
from django.db import transaction, IntegrityError
from courseware.field_overrides import FieldOverrideProvider # pylint: disable=import-error
from opaque_keys.edx.keys import CourseKey, UsageKey
from ccx_keys.locator import CCXLocator, CCXBlockUsageLocator
from .models import CcxFieldOverride, CustomCourseForEdX
log = logging.getLogger(__name__)
class CustomCoursesForEdxOverrideProvider(FieldOverrideProvider):
"""
A concrete implementation of
:class:`~courseware.field_overrides.FieldOverrideProvider` which allows for
overrides to be made on a per user basis.
"""
def get(self, block, name, default):
"""
Just call the get_override_for_ccx method if there is a ccx
"""
# The incoming block might be a CourseKey instance of some type, a
# UsageKey instance of some type, or it might be something that has a
# location attribute. That location attribute will be a UsageKey
ccx = course_key = None
identifier = getattr(block, 'id', None)
if isinstance(identifier, CourseKey):
course_key = block.id
elif isinstance(identifier, UsageKey):
course_key = block.id.course_key
elif hasattr(block, 'location'):
course_key = block.location.course_key
else:
msg = "Unable to get course id when calculating ccx overide for block type %r"
log.error(msg, type(block))
if course_key is not None:
ccx = get_current_ccx(course_key)
if ccx:
return get_override_for_ccx(ccx, block, name, default)
return default
@classmethod
def enabled_for(cls, course):
"""CCX field overrides are enabled per-course
protect against missing attributes
"""
return getattr(course, 'enable_ccx', False)
def get_current_ccx(course_key):
"""
Return the ccx that is active for this course.
course_key is expected to be an instance of an opaque CourseKey, a
ValueError is raised if this expectation is not met.
"""
if not isinstance(course_key, CourseKey):
raise ValueError("get_current_ccx requires a CourseKey instance")
if not isinstance(course_key, CCXLocator):
return None
return CustomCourseForEdX.objects.get(pk=course_key.ccx)
def get_override_for_ccx(ccx, block, name, default=None):
"""
Gets the value of the overridden field for the `ccx`. `block` and `name`
specify the block and the name of the field. If the field is not
overridden for the given ccx, returns `default`.
"""
if not hasattr(block, '_ccx_overrides'):
block._ccx_overrides = {} # pylint: disable=protected-access
overrides = block._ccx_overrides.get(ccx.id) # pylint: disable=protected-access
if overrides is None:
overrides = _get_overrides_for_ccx(ccx, block)
block._ccx_overrides[ccx.id] = overrides # pylint: disable=protected-access
return overrides.get(name, default)
def _get_overrides_for_ccx(ccx, block):
"""
Returns a dictionary mapping field name to overriden value for any
overrides set on this block for this CCX.
"""
overrides = {}
# block as passed in may have a location specific to a CCX, we must strip
# that for this query
location = block.location
if isinstance(block.location, CCXBlockUsageLocator):
location = block.location.to_block_locator()
query = CcxFieldOverride.objects.filter(
ccx=ccx,
location=location
)
for override in query:
field = block.fields[override.field]
value = field.from_json(json.loads(override.value))
overrides[override.field] = value
return overrides
@transaction.commit_on_success
def override_field_for_ccx(ccx, block, name, value):
"""
Overrides a field for the `ccx`. `block` and `name` specify the block
and the name of the field on that block to override. `value` is the
value to set for the given field.
"""
field = block.fields[name]
value = json.dumps(field.to_json(value))
try:
override = CcxFieldOverride.objects.create(
ccx=ccx,
location=block.location,
field=name,
value=value)
except IntegrityError:
transaction.commit()
override = CcxFieldOverride.objects.get(
ccx=ccx,
location=block.location,
field=name)
override.value = value
override.save()
if hasattr(block, '_ccx_overrides'):
del block._ccx_overrides[ccx.id] # pylint: disable=protected-access
def clear_override_for_ccx(ccx, block, name):
"""
Clears a previously set field override for the `ccx`. `block` and `name`
specify the block and the name of the field on that block to clear.
This function is idempotent--if no override is set, nothing action is
performed.
"""
try:
CcxFieldOverride.objects.get(
ccx=ccx,
location=block.location,
field=name).delete()
if hasattr(block, '_ccx_overrides'):
del block._ccx_overrides[ccx.id] # pylint: disable=protected-access
except CcxFieldOverride.DoesNotExist:
pass
| agpl-3.0 |
nishad-jobsglobal/odoo-marriot | addons/fleet/__openerp__.py | 267 | 2245 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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/>.
#
##############################################################################
{
'name' : 'Fleet Management',
'version' : '0.1',
'author' : 'OpenERP S.A.',
'sequence': 110,
'category': 'Managing vehicles and contracts',
'website' : 'https://www.odoo.com/page/fleet',
'summary' : 'Vehicle, leasing, insurances, costs',
'description' : """
Vehicle, leasing, insurances, cost
==================================
With this module, Odoo helps you managing all your vehicles, the
contracts associated to those vehicle as well as services, fuel log
entries, costs and many other features necessary to the management
of your fleet of vehicle(s)
Main Features
-------------
* Add vehicles to your fleet
* Manage contracts for vehicles
* Reminder when a contract reach its expiration date
* Add services, fuel log entry, odometer values for all vehicles
* Show all costs associated to a vehicle or to a type of service
* Analysis graph for costs
""",
'depends' : [
'base',
'mail',
'board'
],
'data' : [
'security/fleet_security.xml',
'security/ir.model.access.csv',
'fleet_view.xml',
'fleet_cars.xml',
'fleet_data.xml',
'fleet_board_view.xml',
],
'demo': ['fleet_demo.xml'],
'installable' : True,
'application' : True,
}
| agpl-3.0 |
Neil741/ryu-master | ryu/services/protocols/bgp/operator/views/fields.py | 38 | 1875 | import importlib
import inspect
class Field(object):
def __init__(self, field_name):
self.field_name = field_name
def get(self, obj):
return getattr(obj, self.field_name)
class RelatedViewField(Field):
def __init__(self, field_name, operator_view_class):
super(RelatedViewField, self).__init__(field_name)
self.__operator_view_class = operator_view_class
@property
def _operator_view_class(self):
if inspect.isclass(self.__operator_view_class):
return self.__operator_view_class
elif isinstance(self.__operator_view_class, basestring):
try:
module_name, class_name =\
self.__operator_view_class.rsplit('.', 1)
return class_for_name(module_name, class_name)
except (AttributeError, ValueError, ImportError):
raise WrongOperatorViewClassError(
'There is no "%s" class' % self.__operator_view_class
)
def retrieve_and_wrap(self, obj):
related_obj = self.get(obj)
return self.wrap(related_obj)
def wrap(self, obj):
return self._operator_view_class(obj)
class RelatedListViewField(RelatedViewField):
pass
class RelatedDictViewField(RelatedViewField):
pass
class DataField(Field):
pass
class OptionalDataField(DataField):
def get(self, obj):
if hasattr(obj, self.field_name):
return getattr(obj, self.field_name)
else:
return None
class WrongOperatorViewClassError(Exception):
pass
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
| apache-2.0 |
guiraldelli/MSc | data_analyzer/gui.py | 1 | 1599 | #!/usr/bin/env python
from Tkinter import *
import tkFileDialog
import data_analyzer
class App:
def __init__(self, master):
# initializing variables
self.filepath_open = None
frame_1 = Frame(master)
frame_2 = Frame(master)
frame_3 = Frame(master)
frame_4 = Frame(master)
# creating widgets
self.label_data_analyzer = Label(frame_1, text="Data Analyzer")
self.button_open_nexus = Button(frame_2, text="Open Nexus file", command=self.command_button_open_nexus)
self.button_save_file = Button(frame_3, text="Save file as...", command=self.command_button_save_file)
self.button_analyze = Button(frame_4, text="Analyze!", command=self.command_button_analyze)
# configuring widgets
# packing widgets
frame_1.pack()
frame_2.pack()
frame_3.pack()
frame_4.pack()
self.label_data_analyzer.pack(side=TOP)
self.button_open_nexus.pack(side=LEFT)
self.button_save_file.pack(side=LEFT)
self.button_analyze.pack(side=TOP)
def command_button_open_nexus(self):
self.filepath_open = tkFileDialog.askopenfilename(filetypes=[("Nexus", "*.nex")], title="Open File...")
def command_button_save_file(self):
self.filepath_save = tkFileDialog.asksaveasfilename(filetypes=[("Comma-Separated File", "*.csv")], initialfile="data_analysis.csv", title="Save File As...")
def command_button_analyze(self):
data_analyzer.analyze_data(self.filepath_open, self.filepath_save)
root = Tk()
app = App(root)
root.mainloop()
| bsd-2-clause |
htzy/bigfour | common/djangoapps/track/management/tracked_command.py | 255 | 2063 | """Provides management command calling info to tracking context."""
from django.core.management.base import BaseCommand
from eventtracking import tracker
class TrackedCommand(BaseCommand):
"""
Provides management command calling info to tracking context.
Information provided to context includes the following value:
'command': the program name and the subcommand used to run a management command.
In future, other values (such as args and options) could be added as needed.
An example tracking log entry resulting from running the 'create_user' management command:
{
"username": "anonymous",
"host": "",
"event_source": "server",
"event_type": "edx.course.enrollment.activated",
"context": {
"course_id": "edX/Open_DemoX/edx_demo_course",
"org_id": "edX",
"command": "./manage.py create_user",
},
"time": "2014-01-06T15:59:49.599522+00:00",
"ip": "",
"event": {
"course_id": "edX/Open_DemoX/edx_demo_course",
"user_id": 29,
"mode": "verified"
},
"agent": "",
"page": null
}
The name of the context used to add (and remove) these values is "edx.mgmt.command".
The context name is used to allow the context additions to be scoped, but doesn't
appear in the context itself.
"""
prog_name = 'unknown'
def create_parser(self, prog_name, subcommand):
"""Wraps create_parser to snag command line info."""
self.prog_name = "{} {}".format(prog_name, subcommand)
return super(TrackedCommand, self).create_parser(prog_name, subcommand)
def execute(self, *args, **options):
"""Wraps base execute() to add command line to tracking context."""
context = {
'command': self.prog_name,
}
COMMAND_CONTEXT_NAME = 'edx.mgmt.command'
with tracker.get_tracker().context(COMMAND_CONTEXT_NAME, context):
super(TrackedCommand, self).execute(*args, **options)
| agpl-3.0 |
gllort/xtrack | src/old_gui/convexhull.py | 3 | 4972 | #!/usr/bin/env python
"""convexhull.py
Calculate the convex hull of a set of n 2D-points in O(n log n) time.
Taken from Berg et al., Computational Geometry, Springer-Verlag, 1997.
Prints output as EPS file.
When run from the command line it generates a random set of points
inside a square of given length and finds the convex hull for those,
printing the result as an EPS file.
Usage:
convexhull.py <numPoints> <squareLength> <outFile>
Dinu C. Gherman
"""
import sys, string, random
######################################################################
# Helpers
######################################################################
def _myDet(p, q, r):
"""Calc. determinant of a special matrix with three 2D points.
The sign, "-" or "+", determines the side, right or left,
respectivly, on which the point r lies, when measured against
a directed vector from p to q.
"""
# We use Sarrus' Rule to calculate the determinant.
# (could also use the Numeric package...)
sum1 = q[0]*r[1] + p[0]*q[1] + r[0]*p[1]
sum2 = q[0]*p[1] + r[0]*q[1] + p[0]*r[1]
return sum1 - sum2
def _isRightTurn((p, q, r)):
"Do the vectors pq:qr form a right turn, or not?"
assert p != q and q != r and p != r
if _myDet(p, q, r) < 0:
return 1
else:
return 0
def _isPointInPolygon(r, P):
"Is point r inside a given polygon P?"
# We assume the polygon is a list of points, listed clockwise!
for i in xrange(len(P[:-1])):
p, q = P[i], P[i+1]
if not _isRightTurn((p, q, r)):
return 0 # Out!
return 1 # It's within!
def _makeRandomData(numPoints=10, sqrLength=100, addCornerPoints=0):
"Generate a list of random points within a square."
# Fill a square with random points.
min, max = 0, sqrLength
P = []
for i in xrange(numPoints):
rand = random.randint
x = rand(min+1, max-1)
y = rand(min+1, max-1)
P.append((x, y))
# Add some "outmost" corner points.
if addCornerPoints != 0:
P = P + [(min, min), (max, max), (min, max), (max, min)]
return P
######################################################################
# Output
######################################################################
epsHeader = """%%!PS-Adobe-2.0 EPSF-2.0
%%%%BoundingBox: %d %d %d %d
/r 2 def %% radius
/circle %% circle, x, y, r --> -
{
0 360 arc %% draw circle
} def
/cross %% cross, x, y --> -
{
0 360 arc %% draw cross hair
} def
1 setlinewidth %% thin line
newpath %% open page
0 setgray %% black color
"""
def saveAsEps(P, H, boxSize, path):
"Save some points and their convex hull into an EPS file."
# Save header.
f = open(path, 'w')
f.write(epsHeader % (0, 0, boxSize, boxSize))
format = "%3d %3d"
# Save the convex hull as a connected path.
if H:
f.write("%s moveto\n" % format % H[0])
for p in H:
f.write("%s lineto\n" % format % p)
f.write("%s lineto\n" % format % H[0])
f.write("stroke\n\n")
# Save the whole list of points as individual dots.
for p in P:
f.write("%s r circle\n" % format % p)
f.write("stroke\n")
# Save footer.
f.write("\nshowpage\n")
######################################################################
# Public interface
######################################################################
def convexHull(P):
"Calculate the convex hull of a set of points."
# Get a local list copy of the points and sort them lexically.
points = map(None, P)
points.sort()
# Build upper half of the hull.
upper = [points[0], points[1]]
for p in points[2:]:
upper.append(p)
while len(upper) > 2 and not _isRightTurn(upper[-3:]):
del upper[-2]
# Build lower half of the hull.
points.reverse()
lower = [points[0], points[1]]
for p in points[2:]:
lower.append(p)
while len(lower) > 2 and not _isRightTurn(lower[-3:]):
del lower[-2]
# Remove duplicates.
del lower[0]
del lower[-1]
# Concatenate both halfs and return.
return tuple(upper + lower)
######################################################################
# Test
######################################################################
def test():
a = 200
p = _makeRandomData(30, a, 0)
c = convexHull(p)
saveAsEps(p, c, a, file)
######################################################################
if __name__ == '__main__':
try:
numPoints = string.atoi(sys.argv[1])
squareLength = string.atoi(sys.argv[2])
path = sys.argv[3]
except IndexError:
numPoints = 30
squareLength = 200
path = "sample.eps"
p = _makeRandomData(numPoints, squareLength, addCornerPoints=0)
c = convexHull(p)
saveAsEps(p, c, squareLength, path)
| gpl-3.0 |
juhasch/myhdl | myhdl/test/core/test_Signal.py | 5 | 18498 | # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl 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
""" Run the unit tests for Signal """
from __future__ import absolute_import
import copy
import operator
import random
import sys
from random import randrange
import pytest
from myhdl import Signal, intbv
from myhdl._compat import long
from myhdl._simulator import _siglist
random.seed(1) # random, but deterministic
maxint = sys.maxsize
class TestSig:
def setup_method(self, method):
self.vals = [0, 0, 1, 1, 1, 2, 3, 5, intbv(0), intbv(1), intbv(2)]
self.nexts = [0, 1, 1, 0, 1, 0, 4, 5, intbv(1), intbv(0), intbv(0)]
self.vals += [intbv(0), intbv(1), intbv(0), intbv(1), 2 ]
self.nexts += [intbv(0), intbv(1), 1 , 0 , intbv(3) ]
self.vals += [ [1,2,3], (1,2,3), {1:1, 2:2}, (0, [2, 3], (1, 2)) ]
self.nexts += [ [4,5,6], (4,5,5), {3:3, 4:4}, (1, (0, 1), [2, 3]) ]
self.vals += [bool(0), bool(1), bool(0), bool(1), bool(0), bool(1)]
self.nexts += [bool(0), bool(1), bool(1), bool(0), 1 , 0 ]
self.sigs = [Signal(i) for i in self.vals]
self.incompatibleVals = [ [3, 4], (1, 2), 3 , intbv(0), [1] ]
self.incompatibleNexts = [ 4 , 3 , "3", (0) , intbv(1) ]
self.incompatibleSigs = [Signal(i) for i in self.incompatibleVals]
self.eventWaiters = [object() for i in range(3)]
self.posedgeWaiters = [object() for i in range(5)]
self.negedgeWaiters = [object() for i in range(7)]
def testValAttrReadOnly(self):
""" val attribute should not be writable"""
s1 = Signal(1)
with pytest.raises(AttributeError):
s1.val = 1
def testDrivenAttrValue(self):
""" driven attribute only accepts value 'reg' or 'wire' """
s1 = Signal(1)
with pytest.raises(ValueError):
s1.driven = "signal"
def testPosedgeAttrReadOnly(self):
""" posedge attribute should not be writable"""
s1 = Signal(1)
with pytest.raises(AttributeError):
s1.posedge = 1
def testNegedgeAttrReadOnly(self):
""" negedge attribute should not be writable"""
s1 = Signal(1)
with pytest.raises(AttributeError):
s1.negedge = 1
def testInitDefault(self):
""" initial value is None by default """
s1 = Signal()
assert s1 == None
def testInitialization(self):
""" initial val and next should be equal """
for s in self.sigs:
assert s.val == s.next
def testUpdate(self):
""" _update() should assign next into val """
for s, n in zip(self.sigs, self.nexts):
cur = copy.copy(s.val)
s.next = n
# assigning to next should not change current value ...
assert s.val == cur
s._update()
assert s.val == n
def testNextType(self):
""" sig.next = n should fail on access if type(n) incompatible """
i = 0
for s in (self.sigs + self.incompatibleSigs):
for n in (self.vals + self.incompatibleVals):
assert isinstance(s.val, s._type)
if isinstance(s.val, (int, long, intbv)):
t = (int, long, intbv)
else:
t = s._type
if not isinstance(n, t):
i += 1
with pytest.raises((TypeError, ValueError)):
oldval = s.val
s.next = n
assert i >= len(self.incompatibleSigs), "Nothing tested %s" %i
def testAfterUpdate(self):
""" updated val and next should be equal but not identical """
for s, n in zip(self.sigs, self.nexts):
s.next = n
s._update()
assert s.val == s.next
def testModify(self):
""" Modifying mutable next should be on a copy """
for s in self.sigs:
mutable = 0
try:
hash(s.val)
except TypeError:
mutable = 1
if not mutable:
continue
if type(s.val) is list:
s.next.append(1)
elif type(s.val) is dict:
s.next[3] = 5
else:
s.next # plain read access
assert s.val is not s.next, repr(s.val)
def testUpdatePosedge(self):
""" update on posedge should return event and posedge waiters """
s1 = Signal(1)
s1.next = 0
s1._update()
s1.next = 1
s1._eventWaiters = self.eventWaiters[:]
s1._posedgeWaiters = self.posedgeWaiters[:]
s1._negedgeWaiters = self.negedgeWaiters[:]
waiters = s1._update()
expected = self.eventWaiters + self.posedgeWaiters
assert set(waiters) == set(expected)
assert s1._eventWaiters == []
assert s1._posedgeWaiters == []
assert s1._negedgeWaiters == self.negedgeWaiters
def testUpdateNegedge(self):
""" update on negedge should return event and negedge waiters """
s1 = Signal(1)
s1.next = 1
s1._update()
s1.next = 0
s1._eventWaiters = self.eventWaiters[:]
s1._posedgeWaiters = self.posedgeWaiters[:]
s1._negedgeWaiters = self.negedgeWaiters[:]
waiters = s1._update()
expected = self.eventWaiters + self.negedgeWaiters
assert set(waiters) == set(expected)
assert s1._eventWaiters == []
assert s1._posedgeWaiters == self.posedgeWaiters
assert s1._negedgeWaiters == []
def testUpdateEvent(self):
""" update on non-edge event should return event waiters """
s1 = Signal(1)
s1.next = 4
s1._update()
s1.next = 5
s1._eventWaiters = self.eventWaiters[:]
s1._posedgeWaiters = self.posedgeWaiters[:]
s1._negedgeWaiters = self.negedgeWaiters[:]
waiters = s1._update()
expected = self.eventWaiters
assert set(waiters) == set(expected)
assert s1._eventWaiters == []
assert s1._posedgeWaiters == self.posedgeWaiters
assert s1._negedgeWaiters == self.negedgeWaiters
def testUpdateNoEvent(self):
""" update without value change should not return event waiters """
s1 = Signal(1)
s1.next = 4
s1._update()
s1.next = 4
s1._eventWaiters = self.eventWaiters[:]
s1._posedgeWaiters = self.posedgeWaiters[:]
s1._negedgeWaiters = self.negedgeWaiters[:]
waiters = s1._update()
assert waiters == []
assert s1._eventWaiters == self.eventWaiters
assert s1._posedgeWaiters == self.posedgeWaiters
assert s1._negedgeWaiters == self.negedgeWaiters
def testNextAccess(self):
""" each next attribute access puts a sig in a global siglist """
del _siglist[:]
s = [None] * 4
for i in range(len(s)):
s[i] = Signal(i)
s[1].next # read access
s[2].next = 1
s[2].next
s[3].next = 0
s[3].next = 1
s[3].next = 3
for i in range(len(s)):
assert _siglist.count(s[i]) == i
class TestSignalAsNum:
def seqSetup(self, imin, imax, jmin=0, jmax=None):
seqi = [imin, imin, 12, 34]
seqj = [jmin, 12 , jmin, 34]
if not imax and not jmax:
l = 2222222222222222222222222222
seqi.append(l)
seqj.append(l)
# first some smaller ints
for n in range(100):
ifirstmax = jfirstmax = 100000
if imax:
ifirstmax = min(imax, ifirstmax)
if jmax:
jfirstmax = min(jmax, jfirstmax)
i = randrange(imin, ifirstmax)
j = randrange(jmin, jfirstmax)
seqi.append(i)
seqj.append(j)
# then some potentially longs
for n in range(100):
if not imax:
i = randrange(maxint) + randrange(maxint)
else:
i = randrange(imin, imax)
if not jmax:
j = randrange(maxint) + randrange(maxint)
else:
j = randrange(jmin, jmax)
seqi.append(i)
seqj.append(j)
self.seqi = seqi
self.seqj = seqj
def binaryCheck(self, op, imin=0, imax=None, jmin=0, jmax=None):
self.seqSetup(imin=imin, imax=imax, jmin=jmin, jmax=jmax)
for i, j in zip(self.seqi, self.seqj):
bi = Signal(long(i))
bj = Signal(long(j))
ref = op(long(i), j)
r1 = op(bi, j)
r2 = op(long(i), bj)
r3 = op(bi, bj)
assert type(r1) == type(ref)
assert type(r2) == type(ref)
assert type(r3) == type(ref)
assert r1 == ref
assert r2 == ref
assert r3 == ref
def augmentedAssignCheck(self, op, imin=0, imax=None, jmin=0, jmax=None):
self.seqSetup(imin=imin, imax=imax, jmin=jmin, jmax=jmax)
for i, j in zip(self.seqi, self.seqj):
bj = Signal(j)
ref = long(i)
ref = op(ref, j)
r1 = bi1 = Signal(i)
with pytest.raises(TypeError):
r1 = op(r1, j)
r2 = long(i)
r2 = op(r2, bj)
r3 = bi3 = Signal(i)
with pytest.raises(TypeError):
r3 = op(r3, bj)
assert r2 == ref
def unaryCheck(self, op, imin=0, imax=None):
self.seqSetup(imin=imin, imax=imax)
for i in self.seqi:
bi = Signal(i)
ref = op(i)
r1 = op(bi)
assert type(r1) == type(ref)
assert r1 == ref
def conversionCheck(self, op, imin=0, imax=None):
self.seqSetup(imin=imin, imax=imax)
for i in self.seqi:
bi = Signal(i)
ref = op(i)
r1 = op(bi)
assert type(r1) == type(ref)
assert r1 == ref
def comparisonCheck(self, op, imin=0, imax=None, jmin=0, jmax=None):
self.seqSetup(imin=imin, imax=imax, jmin=jmin, jmax=jmax)
for i, j in zip(self.seqi, self.seqj):
bi = Signal(i)
bj = Signal(j)
ref = op(i, j)
r1 = op(bi, j)
r2 = op(i, bj)
r3 = op(bi, bj)
assert r1 == ref
assert r2 == ref
assert r3 == ref
def testAdd(self):
self.binaryCheck(operator.add)
def testSub(self):
self.binaryCheck(operator.sub)
def testMul(self):
self.binaryCheck(operator.mul, imax=maxint) # XXX doesn't work for long i???
def testFloorDiv(self):
self.binaryCheck(operator.floordiv, jmin=1)
def testMod(self):
self.binaryCheck(operator.mod, jmin=1)
def testPow(self):
self.binaryCheck(pow, jmax=64)
def testLShift(self):
self.binaryCheck(operator.lshift, jmax=256)
def testRShift(self):
self.binaryCheck(operator.rshift, jmax=256)
def testAnd(self):
self.binaryCheck(operator.and_)
def testOr(self):
self.binaryCheck(operator.or_)
def testXor(self):
self.binaryCheck(operator.xor)
def testIAdd(self):
self.augmentedAssignCheck(operator.iadd)
def testISub(self):
self.augmentedAssignCheck(operator.isub)
def testIMul(self):
self.augmentedAssignCheck(operator.imul, imax=maxint) # XXX doesn't work for long i???
def testIFloorDiv(self):
self.augmentedAssignCheck(operator.ifloordiv, jmin=1)
def testIMod(self):
self.augmentedAssignCheck(operator.imod, jmin=1)
def testIPow(self):
self.augmentedAssignCheck(operator.ipow, jmax=64)
def testIAnd(self):
self.augmentedAssignCheck(operator.iand)
def testIOr(self):
self.augmentedAssignCheck(operator.ior)
def testIXor(self):
self.augmentedAssignCheck(operator.ixor)
def testILShift(self):
self.augmentedAssignCheck(operator.ilshift, jmax=256)
def testIRShift(self):
self.augmentedAssignCheck(operator.irshift, jmax=256)
def testNeg(self):
self.unaryCheck(operator.neg)
def testNeg(self):
self.unaryCheck(operator.pos)
def testAbs(self):
self.unaryCheck(operator.abs)
def testInvert(self):
self.unaryCheck(operator.inv)
def testInt(self):
self.conversionCheck(int, imax=maxint)
def testLong(self):
self.conversionCheck(long)
def testFloat(self):
self.conversionCheck(float)
# XXX __complex__ seems redundant ??? (complex() works as such?)
def testOct(self):
self.conversionCheck(oct)
def testHex(self):
self.conversionCheck(hex)
def testLt(self):
self.comparisonCheck(operator.lt)
def testLe(self):
self.comparisonCheck(operator.le)
def testGt(self):
self.comparisonCheck(operator.gt)
def testGe(self):
self.comparisonCheck(operator.ge)
def testEq(self):
self.comparisonCheck(operator.eq)
def testNe(self):
self.comparisonCheck(operator.ne)
def getItem(s, i):
ext = '0' * (i-len(s)+1)
exts = ext + s
si = len(exts)-1-i
return exts[si]
def getSlice(s, i, j):
ext = '0' * (i-len(s)+1)
exts = ext + s
si = len(exts)-i
sj = len(exts)-j
return exts[si:sj]
class TestSignalIntBvIndexing:
def seqsSetup(self):
seqs = ["0", "1", "000", "111", "010001", "110010010", "011010001110010"]
seqs.extend(["0101010101", "1010101010", "00000000000", "11111111111111"])
seqs.append("11100101001001101000101011011101001101")
seqs.append("00101011101001011111010100010100100101010001001")
self.seqs = seqs
seqv = ["0", "1", "10", "101", "1111", "1010"]
seqv.extend(["11001", "00111010", "100111100"])
seqv.append("0110101001111010101110011010011")
seqv.append("1101101010101101010101011001101101001100110011")
self.seqv = seqv
def testGetItem(self):
self.seqsSetup()
for s in self.seqs:
n = long(s, 2)
sbv = Signal(intbv(n))
sbvi = Signal(intbv(~n))
for i in range(len(s)+20):
ref = long(getItem(s, i), 2)
res = sbv[i]
resi = sbvi[i]
assert res == ref
assert type(res) == bool
assert resi == ref^1
assert type(resi) == bool
def testGetSlice(self):
self.seqsSetup()
for s in self.seqs:
n = long(s, 2)
sbv = Signal(intbv(n))
sbvi = Signal(intbv(~n))
for i in range(1, len(s)+20):
for j in range(0,len(s)+20):
try:
res = sbv[i:j]
resi = sbvi[i:j]
except ValueError:
assert i<=j
continue
ref = long(getSlice(s, i, j), 2)
assert res == ref
assert type(res) == intbv
mask = (2**(i-j))-1
assert resi == ref ^ mask
assert type(resi) == intbv
def testSetItem(self):
sbv = Signal(intbv(5))
with pytest.raises(TypeError):
sbv[1] = 1
def testSetSlice(self):
sbv = Signal(intbv(5))
with pytest.raises(TypeError):
sbv[1:0] = 1
class TestSignalNrBits:
def testBool(self):
if type(bool) is not type : # bool not a type in 2.2
return
s = Signal(bool())
assert s._nrbits == 1
def testIntbvSlice(self):
for n in range(1, 40):
for m in range(0, n):
s = Signal(intbv()[n:m])
assert s._nrbits == n-m
def testIntbvBounds(self):
for n in range(1, 40):
s = Signal(intbv(min=-(2**n)))
assert s._nrbits == 0
s = Signal(intbv(max=2**n))
assert s._nrbits == 0
s = Signal(intbv(min=0, max=2**n))
assert s._nrbits == n
s = Signal(intbv(1, min=1, max=2**n))
assert s._nrbits == n
s = Signal(intbv(min=0, max=2**n+1))
assert s._nrbits == n+1
s = Signal(intbv(min=-(2**n), max=2**n-1))
assert s._nrbits == n+1
s = Signal(intbv(min=-(2**n), max=1))
assert s._nrbits == n+1
s = Signal(intbv(min=-(2**n)-1, max=2**n-1))
assert s._nrbits == n+2
class TestSignalBoolBounds:
def testSignalBoolBounds(self):
if type(bool) is not type: # bool not a type in 2.2
return
s = Signal(bool())
s.next = 1
s.next = 0
for v in (-1, -8, 2, 5):
with pytest.raises(ValueError):
s.next = v
class TestSignalIntbvBounds:
def testSliceAssign(self):
s = Signal(intbv(min=-24, max=34))
for i in (-24, -2, 13, 33):
for k in (6, 9, 10):
s.next[:] = 0
s.next[k:] = i
assert s.next == i
for i in (-25, -128, 34, 35, 229):
for k in (0, 9, 10):
with pytest.raises(ValueError):
s.next[k:] = i
s = Signal(intbv(5)[8:])
for v in (0, 2**8-1, 100):
s.next[:] = v
for v in (-1, 2**8, -10, 1000):
with pytest.raises(ValueError):
s.next[:] = v
| lgpl-2.1 |
logost/mbed | workspace_tools/libraries.py | 40 | 3646 | """
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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.
"""
from workspace_tools.paths import *
from workspace_tools.data.support import *
from workspace_tools.tests import TEST_MBED_LIB
LIBRARIES = [
# RTOS libraries
{
"id": "rtx",
"source_dir": MBED_RTX,
"build_dir": RTOS_LIBRARIES,
"dependencies": [MBED_LIBRARIES],
},
{
"id": "rtos",
"source_dir": RTOS_ABSTRACTION,
"build_dir": RTOS_LIBRARIES,
"dependencies": [MBED_LIBRARIES, MBED_RTX],
},
# USB Device libraries
{
"id": "usb",
"source_dir": USB,
"build_dir": USB_LIBRARIES,
"dependencies": [MBED_LIBRARIES],
},
# USB Host libraries
{
"id": "usb_host",
"source_dir": USB_HOST,
"build_dir": USB_HOST_LIBRARIES,
"dependencies": [MBED_LIBRARIES, FAT_FS, MBED_RTX, RTOS_ABSTRACTION],
},
# DSP libraries
{
"id": "cmsis_dsp",
"source_dir": DSP_CMSIS,
"build_dir": DSP_LIBRARIES,
"dependencies": [MBED_LIBRARIES],
},
{
"id": "dsp",
"source_dir": DSP_ABSTRACTION,
"build_dir": DSP_LIBRARIES,
"dependencies": [MBED_LIBRARIES, DSP_CMSIS],
},
# File system libraries
{
"id": "fat",
"source_dir": [FAT_FS, SD_FS],
"build_dir": FS_LIBRARY,
"dependencies": [MBED_LIBRARIES]
},
# Network libraries
{
"id": "eth",
"source_dir": [ETH_SOURCES, LWIP_SOURCES],
"build_dir": ETH_LIBRARY,
"dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES]
},
{
"id": "ublox",
"source_dir": [UBLOX_SOURCES, CELLULAR_SOURCES, CELLULAR_USB_SOURCES, LWIP_SOURCES],
"build_dir": UBLOX_LIBRARY,
"dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, USB_HOST_LIBRARIES],
},
# Unit Testing library
{
"id": "cpputest",
"source_dir": [CPPUTEST_SRC, CPPUTEST_PLATFORM_SRC, CPPUTEST_TESTRUNNER_SCR],
"build_dir": CPPUTEST_LIBRARY,
"dependencies": [MBED_LIBRARIES],
'inc_dirs': [CPPUTEST_INC, CPPUTEST_PLATFORM_INC, CPPUTEST_TESTRUNNER_INC, TEST_MBED_LIB],
'inc_dirs_ext': [CPPUTEST_INC_EXT],
'macros': ["CPPUTEST_USE_MEM_LEAK_DETECTION=0", "CPPUTEST_USE_STD_CPP_LIB=0", "CPPUTEST=1"],
},
]
LIBRARY_MAP = dict([(library['id'], library) for library in LIBRARIES])
class Library:
DEFAULTS = {
"supported": DEFAULT_SUPPORT,
'dependencies': None,
'inc_dirs': None, # Include dirs required by library build
'inc_dirs_ext': None, # Include dirs required by others to use with this library
'macros': None, # Additional macros you want to define when building library
}
def __init__(self, lib_id):
self.__dict__.update(Library.DEFAULTS)
self.__dict__.update(LIBRARY_MAP[lib_id])
def is_supported(self, target, toolchain):
if not hasattr(self, 'supported'):
return True
return (target.name in self.supported) and (toolchain in self.supported[target.name])
| apache-2.0 |
zyz29/yzhou9-webapps | hw4/api/menus.py | 2 | 2630 | ''' Implements handler for /menus
Imported from handler for /restaurants/{id} '''
import os, os.path, json, logging, mysql.connector
import cherrypy
from jinja2 import Environment, FileSystemLoader
from menuid import MenuID
env = Environment(loader=FileSystemLoader(os.path.abspath(os.path.dirname(__file__))+'/templates/'))
class Menus(object):
''' Handles resources /menus/{menuID}
Allowed methods: GET, POST, PUT, DELETE '''
exposed = True
def __init__(self):
self.id = MenuID()
self.db=dict()
self.db['name']='feedND'
self.db['user']='root'
self.db['host']='127.0.0.1'
def getDataFromDB(self,id):
cnx = mysql.connector.connect(
user=self.db['user'],
host=self.db['host'],
database=self.db['name'],
)
cursor = cnx.cursor()
qn="select name from restaurants where restID=%s" % id
cursor.execute(qn)
restName=cursor.fetchone()[0]
q="select menuId, menu_name from menus where restID=%s order by menu_name" % id
cursor.execute(q)
result=cursor.fetchall()
return restName,result
def GET(self, restID):
''' Return list of menus for restaurant restID'''
# Return data in the format requested in the Accept header
# Fail with a status of 406 Not Acceptable if not HTML or JSON
output_format = cherrypy.lib.cptools.accept(['text/html', 'application/json'])
try:
restName,result=self.getDataFromDB(restID)
except mysql.connector.Error as e:
logging.error(e)
raise
if output_format == 'text/html':
return env.get_template('menus-tmpl.html').render(
rID=restID,
rName=restName,
menus=result,
base=cherrypy.request.base.rstrip('/') + '/'
)
else:
data = [{
'href': 'restaurants/%s/menus/%s/items' % (restID, menu_id),
'name': menu_name
} for menu_id, menu_name in result]
return json.dumps(data, encoding='utf-8')
def POST(self, **kwargs):
result= "POST /restaurants/{restID}/menus ... Menus.POST\n"
result+= "POST /restaurants/{restID}/menus body:\n"
for key, value in kwargs.items():
result+= "%s = %s \n" % (key,value)
# Validate form data
# Insert restaurant
# Prepare response
return result
def OPTIONS(self,restID):
return "<p>/restaurants/{restID}/menus/ allows GET, POST, and OPTIONS</p>"
| mit |
hamishwillee/ardupilot | Tools/autotest/param_metadata/xmlemit.py | 13 | 3306 | #!/usr/bin/env python
from xml.sax.saxutils import escape, quoteattr
from emit import Emit
from param import known_param_fields, known_units
# Emit APM documentation in an machine readable XML format
class XmlEmit(Emit):
def __init__(self):
Emit.__init__(self)
wiki_fname = 'apm.pdef.xml'
self.f = open(wiki_fname, mode='w')
preamble = '''<?xml version="1.0" encoding="utf-8"?>
<!-- Dynamically generated list of documented parameters (generated by param_parse.py) -->
<paramfile>
<vehicles>
'''
self.f.write(preamble)
def close(self):
self.f.write('</libraries>')
self.f.write('''</paramfile>\n''')
self.f.close()
def emit_comment(self, s):
self.f.write("<!-- " + s + " -->")
def start_libraries(self):
self.f.write('</vehicles>')
self.f.write('<libraries>')
def emit(self, g):
t = '''<parameters name=%s>\n''' % quoteattr(g.name) # i.e. ArduPlane
for param in g.params:
# Begin our parameter node
if hasattr(param, 'DisplayName'):
t += '<param humanName=%s name=%s' % (quoteattr(param.DisplayName), quoteattr(param.name)) # i.e. ArduPlane (ArduPlane:FOOPARM)
else:
t += '<param name=%s' % quoteattr(param.name)
if hasattr(param, 'Description'):
t += ' documentation=%s' % quoteattr(param.Description) # i.e. parameter docs
if hasattr(param, 'User'):
t += ' user=%s' % quoteattr(param.User) # i.e. Standard or Advanced
t += ">\n"
# Add values as chidren of this node
for field in param.__dict__.keys():
if field not in ['name', 'DisplayName', 'Description', 'User'] and field in known_param_fields:
if field == 'Values' and Emit.prog_values_field.match(param.__dict__[field]):
t += "<values>\n"
values = (param.__dict__[field]).split(',')
for value in values:
v = value.split(':')
if len(v) != 2:
raise ValueError("Bad value (%s)" % v)
t += '''<value code=%s>%s</value>\n''' % (quoteattr(v[0]), escape(v[1])) # i.e. numeric value, string label
t += "</values>\n"
elif field == 'Units':
abreviated_units = param.__dict__[field]
if abreviated_units != '':
units = known_units[abreviated_units] # use the known_units dictionary to convert the abreviated unit into a full textual one
t += '''<field name=%s>%s</field>\n''' % (quoteattr(field), escape(abreviated_units)) # i.e. A/s
t += '''<field name=%s>%s</field>\n''' % (quoteattr('UnitText'), escape(units)) # i.e. ampere per second
else:
t += '''<field name=%s>%s</field>\n''' % (quoteattr(field), escape(param.__dict__[field])) # i.e. Range: 0 10
t += '''</param>\n'''
t += '''</parameters>\n'''
# print t
self.f.write(t)
| gpl-3.0 |
Avinash-Raj/appengine-django-skeleton | lib/django/core/management/commands/test.py | 115 | 3952 | import logging
import os
import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from django.test.utils import get_runner
class Command(BaseCommand):
help = 'Discover and run tests in the specified modules or the current directory.'
requires_system_checks = False
def __init__(self):
self.test_runner = None
super(Command, self).__init__()
def run_from_argv(self, argv):
"""
Pre-parse the command line to extract the value of the --testrunner
option. This allows a test runner to define additional command line
arguments.
"""
option = '--testrunner='
for arg in argv[2:]:
if arg.startswith(option):
self.test_runner = arg[len(option):]
break
super(Command, self).run_from_argv(argv)
def add_arguments(self, parser):
parser.add_argument('args', metavar='test_label', nargs='*',
help='Module paths to test; can be modulename, modulename.TestCase or modulename.TestCase.test_method')
parser.add_argument('--noinput', '--no-input',
action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.'),
parser.add_argument('--failfast',
action='store_true', dest='failfast', default=False,
help='Tells Django to stop running the test suite after first '
'failed test.'),
parser.add_argument('--testrunner',
action='store', dest='testrunner',
help='Tells Django to use specified test runner class instead of '
'the one specified by the TEST_RUNNER setting.'),
parser.add_argument('--liveserver',
action='store', dest='liveserver', default=None,
help='Overrides the default address where the live server (used '
'with LiveServerTestCase) is expected to run from. The '
'default value is localhost:8081-8179.'),
test_runner_class = get_runner(settings, self.test_runner)
if hasattr(test_runner_class, 'option_list'):
# Keeping compatibility with both optparse and argparse at this level
# would be too heavy for a non-critical item
raise RuntimeError(
"The method to extend accepted command-line arguments by the "
"test management command has changed in Django 1.8. Please "
"create an add_arguments class method to achieve this.")
if hasattr(test_runner_class, 'add_arguments'):
test_runner_class.add_arguments(parser)
def execute(self, *args, **options):
if options['verbosity'] > 0:
# ensure that deprecation warnings are displayed during testing
# the following state is assumed:
# logging.capturewarnings is true
# a "default" level warnings filter has been added for
# DeprecationWarning. See django.conf.LazySettings._configure_logging
logger = logging.getLogger('py.warnings')
handler = logging.StreamHandler()
logger.addHandler(handler)
super(Command, self).execute(*args, **options)
if options['verbosity'] > 0:
# remove the testing-specific handler
logger.removeHandler(handler)
def handle(self, *test_labels, **options):
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings, options.get('testrunner'))
if options.get('liveserver') is not None:
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options['liveserver']
del options['liveserver']
test_runner = TestRunner(**options)
failures = test_runner.run_tests(test_labels)
if failures:
sys.exit(bool(failures))
| bsd-3-clause |
def-/commandergenius | project/jni/python/src/Tools/unicode/gencjkcodecs.py | 44 | 1988 | import os, string
codecs = {
'cn': ('gb2312', 'gbk', 'gb18030', 'hz'),
'tw': ('big5', 'cp950'),
'hk': ('big5hkscs',),
'jp': ('cp932', 'shift_jis', 'euc_jp', 'euc_jisx0213', 'shift_jisx0213',
'euc_jis_2004', 'shift_jis_2004'),
'kr': ('cp949', 'euc_kr', 'johab'),
'iso2022': ('iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2',
'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext',
'iso2022_kr'),
}
TEMPLATE = string.Template("""\
#
# $encoding.py: Python Unicode Codec for $ENCODING
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_$owner, codecs
import _multibytecodec as mbc
codec = _codecs_$owner.getcodec('$encoding')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder):
codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='$encoding',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
""")
def gencodecs(prefix):
for loc, encodings in codecs.iteritems():
for enc in encodings:
code = TEMPLATE.substitute(ENCODING=enc.upper(),
encoding=enc.lower(),
owner=loc)
codecpath = os.path.join(prefix, enc + '.py')
open(codecpath, 'w').write(code)
if __name__ == '__main__':
import sys
gencodecs(sys.argv[1])
| lgpl-2.1 |
thisisshi/cloud-custodian | tests/test_opsworks.py | 2 | 3347 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from .common import BaseTest
class TestOpsworksCM(BaseTest):
def test_query_CM(self):
factory = self.replay_flight_data("test_opswork-cm_query")
p = self.load_policy(
{"name": "get-opswork-cm", "resource": "opswork-cm"},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]["ServerName"], "test-delete-opswork-cm")
def test_delete_CM(self):
factory = self.replay_flight_data("test_opswork-cm_delete")
p = self.load_policy(
{
"name": "delete-opswork-cm",
"resource": "opswork-cm",
"actions": ["delete"],
},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]["ServerName"], "test-delete-opswork-cm")
client = factory().client("opsworkscm")
remainder = client.describe_servers()["Servers"]
self.assertEqual(len(remainder), 1)
self.assertEqual(remainder[0]["Status"], "DELETING")
class TestOpsWorksStack(BaseTest):
def test_query_opsworks_stacks(self):
factory = self.replay_flight_data("test_opswork-stack_query")
p = self.load_policy(
{"name": "get-opswork-stack", "resource": "opswork-stack"},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 2)
self.assertEqual(
sorted([r["Name"] for r in resources]),
["test-delete-opswork-stack", "test-delete-opswork-stack2"],
)
def test_stop_opsworks_stacks(self):
factory = self.replay_flight_data("test_opswork-stack_stop")
p = self.load_policy(
{
"name": "stop-opswork-stack",
"resource": "opswork-stack",
"filters": [{"Name": "test-delete-opswork-stack"}],
"actions": ["stop"],
},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]["Name"], "test-delete-opswork-stack")
client = factory().client("opsworks")
remainder = client.describe_stack_summary(StackId=resources[0]["StackId"])[
"StackSummary"
]
self.assertEqual(remainder["InstancesCount"]["Stopping"], 1)
def test_delete_opsworks_stacks(self):
factory = self.replay_flight_data("test_opswork-stack_delete")
p = self.load_policy(
{
"name": "delete-opswork-stack",
"resource": "opswork-stack",
"filters": [{"Name": "test-delete-opswork-stack"}],
"actions": ["delete"],
},
session_factory=factory,
)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]["Name"], "test-delete-opswork-stack")
client = factory().client("opsworks")
remainder = client.describe_stacks()["Stacks"]
self.assertEqual(len(remainder), 1)
self.assertNotEqual(remainder[0]["Name"], "test-delete-opswork-stack")
| apache-2.0 |
mattclark/osf.io | osf/migrations/0137_add_fm_record_to_osfstorage_files.py | 11 | 2054 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-09-26 15:18
from __future__ import unicode_literals
from math import ceil
import logging
from django.db import migrations, connection
logger = logging.getLogger(__name__)
increment = 500000
def remove_records_from_files(state, schema):
FileMetadataRecord = state.get_model('osf', 'filemetadatarecord')
FileMetadataRecord.objects.all().delete()
# Batching adapted from strategy in website/search_migration/migrate.py
def add_records_to_files_sql(state, schema):
FileMetadataSchema = state.get_model('osf', 'filemetadataschema')
datacite_schema_id = FileMetadataSchema.objects.filter(_id='datacite').values_list('id', flat=True)[0]
OsfStorageFile = state.get_model('osf', 'osfstoragefile')
max_fid = getattr(OsfStorageFile.objects.last(), 'id', 0)
sql = """
INSERT INTO osf_filemetadatarecord (created, modified, _id, metadata, file_id, schema_id)
SELECT NOW(), NOW(), generate_object_id(), '{{}}', OSF_FILE.id, %d
FROM osf_basefilenode OSF_FILE
WHERE (OSF_FILE.type = 'osf.osfstoragefile'
AND OSF_FILE.provider = 'osfstorage'
AND OSF_FILE.id > {}
AND OSF_FILE.id <= {}
);
""" % (datacite_schema_id)
total_pages = int(ceil(max_fid / float(increment)))
page_start = 0
page_end = 0
page = 0
while page_end <= (max_fid):
page += 1
page_end += increment
if page <= total_pages:
logger.info('Updating page {} / {}'.format(page_end / increment, total_pages))
with connection.cursor() as cursor:
cursor.execute(sql.format(
page_start,
page_end
))
page_start = page_end
class Migration(migrations.Migration):
dependencies = [
('osf', '0136_add_datacite_file_metadata_schema'),
]
operations = [
migrations.RunPython(add_records_to_files_sql, remove_records_from_files),
]
| apache-2.0 |
f1aky/xadmin | xadmin/views/edit.py | 6 | 20307 | import copy
from crispy_forms.utils import TEMPLATE_PACK
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, FieldError
from django.db import models, transaction
from django.forms.models import modelform_factory, modelform_defines_fields
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.utils.text import capfirst, get_text_list
from django.template import loader
from django.utils.translation import ugettext as _
from xadmin import widgets
from xadmin.layout import FormHelper, Layout, Fieldset, TabHolder, Container, Column, Col, Field
from xadmin.util import unquote
from xadmin.views.detail import DetailAdminUtil
from base import ModelAdminView, filter_hook, csrf_protect_m
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
models.DateField: {'widget': widgets.AdminDateWidget},
models.TimeField: {'widget': widgets.AdminTimeWidget},
models.TextField: {'widget': widgets.AdminTextareaWidget},
models.URLField: {'widget': widgets.AdminURLFieldWidget},
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.BigIntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.CharField: {'widget': widgets.AdminTextInputWidget},
models.IPAddressField: {'widget': widgets.AdminTextInputWidget},
models.ImageField: {'widget': widgets.AdminFileWidget},
models.FileField: {'widget': widgets.AdminFileWidget},
models.ForeignKey: {'widget': widgets.AdminSelectWidget},
models.OneToOneField: {'widget': widgets.AdminSelectWidget},
models.ManyToManyField: {'widget': widgets.AdminSelectMultiple},
}
class ReadOnlyField(Field):
template = "xadmin/layout/field_value.html"
def __init__(self, *args, **kwargs):
self.detail = kwargs.pop('detail')
super(ReadOnlyField, self).__init__(*args, **kwargs)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
html = ''
for field in self.fields:
result = self.detail.get_field_result(field)
field = {'auto_id': field}
html += loader.render_to_string(
self.template, {'field': field, 'result': result})
return html
class ModelFormAdminView(ModelAdminView):
form = forms.ModelForm
formfield_overrides = {}
readonly_fields = ()
style_fields = {}
exclude = None
relfield_style = None
save_as = False
save_on_top = False
add_form_template = None
change_form_template = None
form_layout = None
def __init__(self, request, *args, **kwargs):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
super(ModelFormAdminView, self).__init__(request, *args, **kwargs)
@filter_hook
def formfield_for_dbfield(self, db_field, **kwargs):
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if isinstance(db_field, models.ManyToManyField) and not db_field.rel.through._meta.auto_created:
return None
attrs = self.get_field_attrs(db_field, **kwargs)
return db_field.formfield(**dict(attrs, **kwargs))
@filter_hook
def get_field_style(self, db_field, style, **kwargs):
if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
attrs = {'widget': widgets.AdminRadioSelect(
attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
if db_field.choices:
attrs['choices'] = db_field.get_choices(
include_blank=db_field.blank,
blank_choice=[('', _('Null'))]
)
return attrs
if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
'help_text': None}
@filter_hook
def get_field_attrs(self, db_field, **kwargs):
if db_field.name in self.style_fields:
attrs = self.get_field_style(
db_field, self.style_fields[db_field.name], **kwargs)
if attrs:
return attrs
if hasattr(db_field, "rel") and db_field.rel:
related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
if related_modeladmin and hasattr(related_modeladmin, 'relfield_style'):
attrs = self.get_field_style(
db_field, related_modeladmin.relfield_style, **kwargs)
if attrs:
return attrs
if db_field.choices:
return {'widget': widgets.AdminSelectWidget}
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
return self.formfield_overrides[klass].copy()
return {}
@filter_hook
def prepare_form(self):
self.model_form = self.get_model_form()
@filter_hook
def instance_forms(self):
self.form_obj = self.model_form(**self.get_form_datas())
def setup_forms(self):
helper = self.get_form_helper()
if helper:
self.form_obj.helper = helper
@filter_hook
def valid_forms(self):
return self.form_obj.is_valid()
@filter_hook
def get_model_form(self, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields())
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": self.fields and list(self.fields) or None,
"exclude": exclude,
"formfield_callback": self.formfield_for_dbfield,
}
defaults.update(kwargs)
if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
defaults['fields'] = forms.ALL_FIELDS
return modelform_factory(self.model, **defaults)
try:
return modelform_factory(self.model, **defaults)
except FieldError as e:
raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
% (e, self.__class__.__name__))
@filter_hook
def get_form_layout(self):
layout = copy.deepcopy(self.form_layout)
fields = self.form_obj.fields.keys() + list(self.get_readonly_fields())
if layout is None:
layout = Layout(Container(Col('full',
Fieldset("", *fields, css_class="unsort no_title"), horizontal=True, span=12)
))
elif type(layout) in (list, tuple) and len(layout) > 0:
if isinstance(layout[0], Column):
fs = layout
elif isinstance(layout[0], (Fieldset, TabHolder)):
fs = (Col('full', *layout, horizontal=True, span=12),)
else:
fs = (Col('full', Fieldset("", *layout, css_class="unsort no_title"), horizontal=True, span=12),)
layout = Layout(Container(*fs))
rendered_fields = [i[1] for i in layout.get_field_names()]
container = layout[0].fields
other_fieldset = Fieldset(_(u'Other Fields'), *[f for f in fields if f not in rendered_fields])
if len(other_fieldset.fields):
if len(container) and isinstance(container[0], Column):
container[0].fields.append(other_fieldset)
else:
container.append(other_fieldset)
return layout
@filter_hook
def get_form_helper(self):
helper = FormHelper()
helper.form_tag = False
helper.include_media = False
helper.add_layout(self.get_form_layout())
# deal with readonly fields
readonly_fields = self.get_readonly_fields()
if readonly_fields:
detail = self.get_model_view(
DetailAdminUtil, self.model, self.form_obj.instance)
for field in readonly_fields:
helper[field].wrap(ReadOnlyField, detail=detail)
return helper
@filter_hook
def get_readonly_fields(self):
"""
Hook for specifying custom readonly fields.
"""
return self.readonly_fields
@filter_hook
def save_forms(self):
self.new_obj = self.form_obj.save(commit=False)
@filter_hook
def change_message(self):
change_message = []
if self.org_obj is None:
change_message.append(_('Added.'))
elif self.form_obj.changed_data:
change_message.append(_('Changed %s.') % get_text_list(self.form_obj.changed_data, _('and')))
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
@filter_hook
def save_models(self):
self.new_obj.save()
flag = self.org_obj is None and 'create' or 'change'
self.log(flag, self.change_message(), self.new_obj)
@filter_hook
def save_related(self):
self.form_obj.save_m2m()
@csrf_protect_m
@filter_hook
def get(self, request, *args, **kwargs):
self.instance_forms()
self.setup_forms()
return self.get_response()
@csrf_protect_m
@transaction.atomic
@filter_hook
def post(self, request, *args, **kwargs):
self.instance_forms()
self.setup_forms()
if self.valid_forms():
self.save_forms()
self.save_models()
self.save_related()
response = self.post_response()
if isinstance(response, basestring):
return HttpResponseRedirect(response)
else:
return response
return self.get_response()
@filter_hook
def get_context(self):
add = self.org_obj is None
change = self.org_obj is not None
new_context = {
'form': self.form_obj,
'original': self.org_obj,
'show_delete': self.org_obj is not None,
'add': add,
'change': change,
'errors': self.get_error_list(),
'has_add_permission': self.has_add_permission(),
'has_view_permission': self.has_view_permission(),
'has_change_permission': self.has_change_permission(self.org_obj),
'has_delete_permission': self.has_delete_permission(self.org_obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'form_url': '',
'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
}
# for submit line
new_context.update({
'onclick_attrib': '',
'show_delete_link': (new_context['has_delete_permission']
and (change or new_context['show_delete'])),
'show_save_as_new': change and self.save_as,
'show_save_and_add_another': new_context['has_add_permission'] and
(not self.save_as or add),
'show_save_and_continue': new_context['has_change_permission'],
'show_save': True
})
if self.org_obj and new_context['show_delete_link']:
new_context['delete_url'] = self.model_admin_url(
'delete', self.org_obj.pk)
context = super(ModelFormAdminView, self).get_context()
context.update(new_context)
return context
@filter_hook
def get_error_list(self):
errors = forms.utils.ErrorList()
if self.form_obj.is_bound:
errors.extend(self.form_obj.errors.values())
return errors
@filter_hook
def get_media(self):
return super(ModelFormAdminView, self).get_media() + self.form_obj.media + \
self.vendor('xadmin.page.form.js', 'xadmin.form.css')
class CreateAdminView(ModelFormAdminView):
def init_request(self, *args, **kwargs):
self.org_obj = None
if not self.has_add_permission():
raise PermissionDenied
# comm method for both get and post
self.prepare_form()
@filter_hook
def get_form_datas(self):
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
if self.request_method == 'get':
initial = dict(self.request.GET.items())
for k in initial:
try:
f = self.opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
return {'initial': initial}
else:
return {'data': self.request.POST, 'files': self.request.FILES}
@filter_hook
def get_context(self):
new_context = {
'title': _('Add %s') % force_unicode(self.opts.verbose_name),
}
context = super(CreateAdminView, self).get_context()
context.update(new_context)
return context
@filter_hook
def get_breadcrumb(self):
bcs = super(ModelFormAdminView, self).get_breadcrumb()
item = {'title': _('Add %s') % force_unicode(self.opts.verbose_name)}
if self.has_add_permission():
item['url'] = self.model_admin_url('add')
bcs.append(item)
return bcs
@filter_hook
def get_response(self):
context = self.get_context()
context.update(self.kwargs or {})
return TemplateResponse(
self.request, self.add_form_template or self.get_template_list(
'views/model_form.html'),
context)
@filter_hook
def post_response(self):
"""
Determines the HttpResponse for the add_view stage.
"""
request = self.request
msg = _(
'The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(self.opts.verbose_name),
'obj': "<a class='alert-link' href='%s'>%s</a>" % (self.model_admin_url('change', self.new_obj._get_pk_val()), force_unicode(self.new_obj))}
if "_continue" in request.POST:
self.message_user(
msg + ' ' + _("You may edit it again below."), 'success')
return self.model_admin_url('change', self.new_obj._get_pk_val())
if "_addanother" in request.POST:
self.message_user(msg + ' ' + (_("You may add another %s below.") % force_unicode(self.opts.verbose_name)), 'success')
return request.path
else:
self.message_user(msg, 'success')
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if "_redirect" in request.POST:
return request.POST["_redirect"]
elif self.has_view_permission():
return self.model_admin_url('changelist')
else:
return self.get_admin_url('index')
class UpdateAdminView(ModelFormAdminView):
def init_request(self, object_id, *args, **kwargs):
self.org_obj = self.get_object(unquote(object_id))
if not self.has_change_permission(self.org_obj):
raise PermissionDenied
if self.org_obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') %
{'name': force_unicode(self.opts.verbose_name), 'key': escape(object_id)})
# comm method for both get and post
self.prepare_form()
@filter_hook
def get_form_datas(self):
params = {'instance': self.org_obj}
if self.request_method == 'post':
params.update(
{'data': self.request.POST, 'files': self.request.FILES})
return params
@filter_hook
def get_context(self):
new_context = {
'title': _('Change %s') % force_unicode(self.org_obj),
'object_id': str(self.org_obj.pk),
}
context = super(UpdateAdminView, self).get_context()
context.update(new_context)
return context
@filter_hook
def get_breadcrumb(self):
bcs = super(ModelFormAdminView, self).get_breadcrumb()
item = {'title': force_unicode(self.org_obj)}
if self.has_change_permission():
item['url'] = self.model_admin_url('change', self.org_obj.pk)
bcs.append(item)
return bcs
@filter_hook
def get_response(self, *args, **kwargs):
context = self.get_context()
context.update(kwargs or {})
return TemplateResponse(
self.request, self.change_form_template or self.get_template_list(
'views/model_form.html'),
context)
def post(self, request, *args, **kwargs):
if "_saveasnew" in self.request.POST:
return self.get_model_view(CreateAdminView, self.model).post(request)
return super(UpdateAdminView, self).post(request, *args, **kwargs)
@filter_hook
def post_response(self):
"""
Determines the HttpResponse for the change_view stage.
"""
opts = self.new_obj._meta
obj = self.new_obj
request = self.request
verbose_name = opts.verbose_name
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name':
force_unicode(verbose_name), 'obj': force_unicode(obj)}
if "_continue" in request.POST:
self.message_user(
msg + ' ' + _("You may edit it again below."), 'success')
return request.path
elif "_addanother" in request.POST:
self.message_user(msg + ' ' + (_("You may add another %s below.")
% force_unicode(verbose_name)), 'success')
return self.model_admin_url('add')
else:
self.message_user(msg, 'success')
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if "_redirect" in request.POST:
return request.POST["_redirect"]
elif self.has_view_permission():
change_list_url = self.model_admin_url('changelist')
if 'LIST_QUERY' in self.request.session \
and self.request.session['LIST_QUERY'][0] == self.model_info:
change_list_url += '?' + self.request.session['LIST_QUERY'][1]
return change_list_url
else:
return self.get_admin_url('index')
class ModelFormAdminUtil(ModelFormAdminView):
def init_request(self, obj=None):
self.org_obj = obj
self.prepare_form()
self.instance_forms()
@filter_hook
def get_form_datas(self):
return {'instance': self.org_obj}
| bsd-3-clause |
acsone/department | project_issue_department/project_issue.py | 7 | 1835 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# 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.osv import fields, orm
class ProjectIssue(orm.Model):
_inherit = 'project.issue'
_columns = {
'department_id': fields.many2one('hr.department', 'Department'),
}
def on_change_project(self, cr, uid, ids, proj_id=False, context=None):
"""When Project is changed: copy it's Department to the issue."""
res = super(ProjectIssue, self).on_change_project(
cr, uid, ids, proj_id, context=context)
res.setdefault('value', {})
if proj_id:
proj = self.pool.get('project.project').browse(
cr, uid, proj_id, context)
dept = getattr(proj, 'department_id', None)
if dept:
res['value'].update({'department_id': dept.id})
else:
res['value'].update({'department_id': None})
return res
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
unaizalakain/django | tests/flatpages_tests/test_forms.py | 155 | 4568 | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.flatpages.forms import FlatpageForm
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from django.utils import translation
@modify_settings(INSTALLED_APPS={'append': ['django.contrib.flatpages', ]})
@override_settings(SITE_ID=1)
class FlatpageAdminFormTests(TestCase):
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
def setUp(self):
# Site fields cache needs to be cleared after flatpages is added to
# INSTALLED_APPS
Site._meta._expire_cache()
self.form_data = {
'title': "A test page",
'content': "This is a test",
'sites': [settings.SITE_ID],
}
def test_flatpage_admin_form_url_validation(self):
"The flatpage admin form correctly validates urls"
self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid())
self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid())
self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid())
self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid())
self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid())
self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid())
self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid())
self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid())
def test_flatpage_requires_leading_slash(self):
form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data))
with translation.override('en'):
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['url'], ["URL is missing a leading slash."])
@override_settings(APPEND_SLASH=True,
MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
def test_flatpage_requires_trailing_slash_with_append_slash(self):
form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
with translation.override('en'):
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])
@override_settings(APPEND_SLASH=False,
MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self):
form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
self.assertTrue(form.is_valid())
def test_flatpage_admin_form_url_uniqueness_validation(self):
"The flatpage admin form correctly enforces url uniqueness among flatpages of the same site"
data = dict(url='/myflatpage1/', **self.form_data)
FlatpageForm(data=data).save()
f = FlatpageForm(data=data)
with translation.override('en'):
self.assertFalse(f.is_valid())
self.assertEqual(
f.errors,
{'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']})
def test_flatpage_admin_form_edit(self):
"""
Existing flatpages can be edited in the admin form without triggering
the url-uniqueness validation.
"""
existing = FlatPage.objects.create(
url="/myflatpage1/", title="Some page", content="The content")
existing.sites.add(settings.SITE_ID)
data = dict(url='/myflatpage1/', **self.form_data)
f = FlatpageForm(data=data, instance=existing)
self.assertTrue(f.is_valid(), f.errors)
updated = f.save()
self.assertEqual(updated.title, "A test page")
def test_flatpage_nosites(self):
data = dict(url='/myflatpage1/', **self.form_data)
data.update({'sites': ''})
f = FlatpageForm(data=data)
self.assertFalse(f.is_valid())
self.assertEqual(
f.errors,
{'sites': [translation.ugettext('This field is required.')]})
| bsd-3-clause |
seocam/django | django/db/models/fields/related.py | 8 | 114152 | from __future__ import unicode_literals
import warnings
from operator import attrgetter
from django import forms
from django.apps import apps
from django.core import checks, exceptions
from django.core.exceptions import FieldDoesNotExist
from django.db import connection, connections, router, transaction
from django.db.backends import utils
from django.db.models import Q, signals
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields import (
BLANK_CHOICE_DASH, AutoField, Field, IntegerField, PositiveIntegerField,
PositiveSmallIntegerField,
)
from django.db.models.lookups import IsNull
from django.db.models.query import QuerySet
from django.db.models.query_utils import PathInfo
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text, smart_text
from django.utils.functional import cached_property, curry
from django.utils.translation import ugettext_lazy as _
RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
def add_lazy_relation(cls, field, relation, operation):
"""
Adds a lookup on ``cls`` when a related field is defined using a string,
i.e.::
class MyModel(Model):
fk = ForeignKey("AnotherModel")
This string can be:
* RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
relation.
* The name of a model (i.e "AnotherModel") to indicate another model in
the same app.
* An app-label and model name (i.e. "someapp.AnotherModel") to indicate
another model in a different app.
If the other model hasn't yet been loaded -- almost a given if you're using
lazy relationships -- then the relation won't be set up until the
class_prepared signal fires at the end of model initialization.
``operation`` is the work that must be performed once the relation can be
resolved.
"""
# Check for recursive relations
if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
app_label = cls._meta.app_label
model_name = cls.__name__
else:
# Look for an "app.Model" relation.
if isinstance(relation, six.string_types):
try:
app_label, model_name = relation.split(".")
except ValueError:
# If we can't split, assume a model in current app.
app_label = cls._meta.app_label
model_name = relation
else:
# It's actually a model class.
app_label = relation._meta.app_label
model_name = relation._meta.object_name
# Try to look up the related model, and if it's already loaded resolve the
# string right away. If get_registered_model raises a LookupError, it means
# that the related model isn't loaded yet, so we need to pend the relation
# until the class is prepared.
try:
model = cls._meta.apps.get_registered_model(app_label, model_name)
except LookupError:
key = (app_label, model_name)
value = (cls, field, operation)
cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
else:
operation(field, model, cls)
def do_pending_lookups(sender, **kwargs):
"""
Sent from class_prepared to handle pending relations to the sending model.
"""
key = (sender._meta.app_label, sender.__name__)
for cls, field, operation in sender._meta.apps._pending_lookups.pop(key, []):
operation(field, sender, cls)
signals.class_prepared.connect(do_pending_lookups)
class RelatedField(Field):
"""
Base class that all relational fields inherit from.
"""
# Field flags
one_to_many = False
one_to_one = False
many_to_many = False
many_to_one = False
@cached_property
def related_model(self):
# Can't cache this property until all the models are loaded.
apps.check_models_ready()
return self.rel.to
def check(self, **kwargs):
errors = super(RelatedField, self).check(**kwargs)
errors.extend(self._check_related_name_is_valid())
errors.extend(self._check_relation_model_exists())
errors.extend(self._check_referencing_to_swapped_model())
errors.extend(self._check_clashes())
return errors
def _check_related_name_is_valid(self):
import re
import keyword
related_name = self.rel.related_name
is_valid_id = (related_name and re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', related_name)
and not keyword.iskeyword(related_name))
if related_name and not (is_valid_id or related_name.endswith('+')):
return [
checks.Error(
"The name '%s' is invalid related_name for field %s.%s" %
(self.rel.related_name, self.model._meta.object_name,
self.name),
hint="Related name must be a valid Python identifier or end with a '+'",
obj=self,
id='fields.E306',
)
]
return []
def _check_relation_model_exists(self):
rel_is_missing = self.rel.to not in apps.get_models()
rel_is_string = isinstance(self.rel.to, six.string_types)
model_name = self.rel.to if rel_is_string else self.rel.to._meta.object_name
if rel_is_missing and (rel_is_string or not self.rel.to._meta.swapped):
return [
checks.Error(
("Field defines a relation with model '%s', which "
"is either not installed, or is abstract.") % model_name,
hint=None,
obj=self,
id='fields.E300',
)
]
return []
def _check_referencing_to_swapped_model(self):
if (self.rel.to not in apps.get_models() and
not isinstance(self.rel.to, six.string_types) and
self.rel.to._meta.swapped):
model = "%s.%s" % (
self.rel.to._meta.app_label,
self.rel.to._meta.object_name
)
return [
checks.Error(
("Field defines a relation with the model '%s', "
"which has been swapped out.") % model,
hint="Update the relation to point at 'settings.%s'." % self.rel.to._meta.swappable,
obj=self,
id='fields.E301',
)
]
return []
def _check_clashes(self):
"""
Check accessor and reverse query name clashes.
"""
from django.db.models.base import ModelBase
errors = []
opts = self.model._meta
# `f.rel.to` may be a string instead of a model. Skip if model name is
# not resolved.
if not isinstance(self.rel.to, ModelBase):
return []
# If the field doesn't install backward relation on the target model (so
# `is_hidden` returns True), then there are no clashes to check and we
# can skip these fields.
if self.rel.is_hidden():
return []
try:
self.rel
except AttributeError:
return []
# Consider that we are checking field `Model.foreign` and the models
# are:
#
# class Target(models.Model):
# model = models.IntegerField()
# model_set = models.IntegerField()
#
# class Model(models.Model):
# foreign = models.ForeignKey(Target)
# m2m = models.ManyToManyField(Target)
rel_opts = self.rel.to._meta
# rel_opts.object_name == "Target"
rel_name = self.rel.get_accessor_name() # i. e. "model_set"
rel_query_name = self.related_query_name() # i. e. "model"
field_name = "%s.%s" % (opts.object_name,
self.name) # i. e. "Model.field"
# Check clashes between accessor or reverse query name of `field`
# and any other field name -- i.e. accessor for Model.foreign is
# model_set and it clashes with Target.model_set.
potential_clashes = rel_opts.fields + rel_opts.many_to_many
for clash_field in potential_clashes:
clash_name = "%s.%s" % (rel_opts.object_name,
clash_field.name) # i. e. "Target.model_set"
if clash_field.name == rel_name:
errors.append(
checks.Error(
"Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),
hint=("Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'.") % (clash_name, field_name),
obj=self,
id='fields.E302',
)
)
if clash_field.name == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name),
hint=("Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'.") % (clash_name, field_name),
obj=self,
id='fields.E303',
)
)
# Check clashes between accessors/reverse query names of `field` and
# any other field accessor -- i. e. Model.foreign accessor clashes with
# Model.m2m accessor.
potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
for clash_field in potential_clashes:
clash_name = "%s.%s" % ( # i. e. "Model.m2m"
clash_field.related_model._meta.object_name,
clash_field.field.name)
if clash_field.get_accessor_name() == rel_name:
errors.append(
checks.Error(
"Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),
hint=("Add or change a related_name argument "
"to the definition for '%s' or '%s'.") % (field_name, clash_name),
obj=self,
id='fields.E304',
)
)
if clash_field.get_accessor_name() == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with reverse query name for '%s'."
% (field_name, clash_name),
hint=("Add or change a related_name argument "
"to the definition for '%s' or '%s'.") % (field_name, clash_name),
obj=self,
id='fields.E305',
)
)
return errors
def db_type(self, connection):
# By default related field will not have a column as it relates to
# columns from another table.
return None
def contribute_to_class(self, cls, name, virtual_only=False):
sup = super(RelatedField, self)
self.opts = cls._meta
if hasattr(sup, 'contribute_to_class'):
sup.contribute_to_class(cls, name, virtual_only=virtual_only)
if not cls._meta.abstract:
if self.rel.related_name:
related_name = force_text(self.rel.related_name) % {
'class': cls.__name__.lower(),
'app_label': cls._meta.app_label.lower()
}
self.rel.related_name = related_name
other = self.rel.to
if isinstance(other, six.string_types) or other._meta.pk is None:
def resolve_related_class(field, model, cls):
field.rel.to = model
field.do_related_class(model, cls)
add_lazy_relation(cls, self, other, resolve_related_class)
else:
self.do_related_class(other, cls)
@property
def swappable_setting(self):
"""
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
"""
if self.swappable:
# Work out string form of "to"
if isinstance(self.rel.to, six.string_types):
to_string = self.rel.to
else:
to_string = "%s.%s" % (
self.rel.to._meta.app_label,
self.rel.to._meta.object_name,
)
# See if anything swapped/swappable matches
for model in apps.get_models(include_swapped=True):
if model._meta.swapped:
if model._meta.swapped == to_string:
return model._meta.swappable
if ("%s.%s" % (model._meta.app_label, model._meta.object_name)) == to_string and model._meta.swappable:
return model._meta.swappable
return None
def set_attributes_from_rel(self):
self.name = self.name or (self.rel.to._meta.model_name + '_' + self.rel.to._meta.pk.name)
if self.verbose_name is None:
self.verbose_name = self.rel.to._meta.verbose_name
self.rel.set_field_name()
@property
def related(self):
warnings.warn(
"Usage of field.related has been deprecated. Use field.rel instead.",
RemovedInDjango20Warning, 2)
return self.rel
def do_related_class(self, other, cls):
self.set_attributes_from_rel()
if not cls._meta.abstract:
self.contribute_to_related_class(other, self.rel)
def get_limit_choices_to(self):
"""
Return ``limit_choices_to`` for this model field.
If it is a callable, it will be invoked and the result will be
returned.
"""
if callable(self.rel.limit_choices_to):
return self.rel.limit_choices_to()
return self.rel.limit_choices_to
def formfield(self, **kwargs):
"""
Pass ``limit_choices_to`` to the field being constructed.
Only passes it if there is a type that supports related fields.
This is a similar strategy used to pass the ``queryset`` to the field
being constructed.
"""
defaults = {}
if hasattr(self.rel, 'get_related_field'):
# If this is a callable, do not invoke it here. Just pass
# it in the defaults for when the form class will later be
# instantiated.
limit_choices_to = self.rel.limit_choices_to
defaults.update({
'limit_choices_to': limit_choices_to,
})
defaults.update(kwargs)
return super(RelatedField, self).formfield(**defaults)
def related_query_name(self):
"""
Define the name that can be used to identify this related object in a
table-spanning query.
"""
return self.rel.related_query_name or self.rel.related_name or self.opts.model_name
class SingleRelatedObjectDescriptor(object):
"""
Accessor to the related object on the reverse side of a one-to-one
relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
``place.restaurant`` is a ``SingleRelatedObjectDescriptor`` instance.
"""
def __init__(self, related):
self.related = related
self.cache_name = related.get_cache_name()
@cached_property
def RelatedObjectDoesNotExist(self):
# The exception isn't created at initialization time for the sake of
# consistency with `ReverseSingleRelatedObjectDescriptor`.
return type(
str('RelatedObjectDoesNotExist'),
(self.related.related_model.DoesNotExist, AttributeError),
{}
)
def is_cached(self, instance):
return hasattr(instance, self.cache_name)
def get_queryset(self, **hints):
manager = self.related.related_model._default_manager
# If the related manager indicates that it should be used for
# related fields, respect that.
if not getattr(manager, 'use_for_related_fields', False):
manager = self.related.related_model._base_manager
return manager.db_manager(hints=hints).all()
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = self.get_queryset()
queryset._add_hints(instance=instances[0])
rel_obj_attr = attrgetter(self.related.field.attname)
instance_attr = lambda obj: obj._get_pk_val()
instances_dict = {instance_attr(inst): inst for inst in instances}
query = {'%s__in' % self.related.field.name: instances}
queryset = queryset.filter(**query)
# Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually.
rel_obj_cache_name = self.related.field.get_cache_name()
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
setattr(rel_obj, rel_obj_cache_name, instance)
return queryset, rel_obj_attr, instance_attr, True, self.cache_name
def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
rel_obj = getattr(instance, self.cache_name)
except AttributeError:
related_pk = instance._get_pk_val()
if related_pk is None:
rel_obj = None
else:
params = {}
for lh_field, rh_field in self.related.field.related_fields:
params['%s__%s' % (self.related.field.name, rh_field.name)] = getattr(instance, rh_field.attname)
try:
rel_obj = self.get_queryset(instance=instance).get(**params)
except self.related.related_model.DoesNotExist:
rel_obj = None
else:
setattr(rel_obj, self.related.field.get_cache_name(), instance)
setattr(instance, self.cache_name, rel_obj)
if rel_obj is None:
raise self.RelatedObjectDoesNotExist(
"%s has no %s." % (
instance.__class__.__name__,
self.related.get_accessor_name()
)
)
else:
return rel_obj
def __set__(self, instance, value):
# The similarity of the code below to the code in
# ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch
# of small differences that would make a common base class convoluted.
# If null=True, we can assign null here, but otherwise the value needs
# to be an instance of the related class.
if value is None and self.related.field.null is False:
raise ValueError(
'Cannot assign None: "%s.%s" does not allow null values.' % (
instance._meta.object_name,
self.related.get_accessor_name(),
)
)
elif value is not None and not isinstance(value, self.related.related_model):
raise ValueError(
'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
value,
instance._meta.object_name,
self.related.get_accessor_name(),
self.related.related_model._meta.object_name,
)
)
elif value is not None:
if instance._state.db is None:
instance._state.db = router.db_for_write(instance.__class__, instance=value)
elif value._state.db is None:
value._state.db = router.db_for_write(value.__class__, instance=instance)
elif value._state.db is not None and instance._state.db is not None:
if not router.allow_relation(value, instance):
raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
related_pk = tuple(getattr(instance, field.attname) for field in self.related.field.foreign_related_fields)
if None in related_pk:
raise ValueError(
'Cannot assign "%r": "%s" instance isn\'t saved in the database.' %
(value, instance._meta.object_name)
)
# Set the value of the related field to the value of the related object's related field
for index, field in enumerate(self.related.field.local_related_fields):
setattr(value, field.attname, related_pk[index])
# Since we already know what the related object is, seed the related
# object caches now, too. This avoids another db hit if you get the
# object you just set.
setattr(instance, self.cache_name, value)
setattr(value, self.related.field.get_cache_name(), instance)
class ReverseSingleRelatedObjectDescriptor(object):
"""
Accessor to the related object on the forward side of a many-to-one or
one-to-one relation.
In the example::
class Choice(Model):
poll = ForeignKey(Place, related_name='choices')
`choice.poll` is a ReverseSingleRelatedObjectDescriptor instance.
"""
def __init__(self, field_with_rel):
self.field = field_with_rel
self.cache_name = self.field.get_cache_name()
@cached_property
def RelatedObjectDoesNotExist(self):
# The exception can't be created at initialization time since the
# related model might not be resolved yet; `rel.to` might still be
# a string model reference.
return type(
str('RelatedObjectDoesNotExist'),
(self.field.rel.to.DoesNotExist, AttributeError),
{}
)
def is_cached(self, instance):
return hasattr(instance, self.cache_name)
def get_queryset(self, **hints):
manager = self.field.rel.to._default_manager
# If the related manager indicates that it should be used for
# related fields, respect that.
if not getattr(manager, 'use_for_related_fields', False):
manager = self.field.rel.to._base_manager
return manager.db_manager(hints=hints).all()
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = self.get_queryset()
queryset._add_hints(instance=instances[0])
rel_obj_attr = self.field.get_foreign_related_value
instance_attr = self.field.get_local_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
related_field = self.field.foreign_related_fields[0]
# FIXME: This will need to be revisited when we introduce support for
# composite fields. In the meantime we take this practical approach to
# solve a regression on 1.6 when the reverse manager in hidden
# (related_name ends with a '+'). Refs #21410.
# The check for len(...) == 1 is a special case that allows the query
# to be join-less and smaller. Refs #21760.
if self.field.rel.is_hidden() or len(self.field.foreign_related_fields) == 1:
query = {'%s__in' % related_field.name: set(instance_attr(inst)[0] for inst in instances)}
else:
query = {'%s__in' % self.field.related_query_name(): instances}
queryset = queryset.filter(**query)
# Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually.
if not self.field.rel.multiple:
rel_obj_cache_name = self.field.rel.get_cache_name()
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
setattr(rel_obj, rel_obj_cache_name, instance)
return queryset, rel_obj_attr, instance_attr, True, self.cache_name
def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
rel_obj = getattr(instance, self.cache_name)
except AttributeError:
val = self.field.get_local_related_value(instance)
if None in val:
rel_obj = None
else:
params = {
rh_field.attname: getattr(instance, lh_field.attname)
for lh_field, rh_field in self.field.related_fields}
qs = self.get_queryset(instance=instance)
extra_filter = self.field.get_extra_descriptor_filter(instance)
if isinstance(extra_filter, dict):
params.update(extra_filter)
qs = qs.filter(**params)
else:
qs = qs.filter(extra_filter, **params)
# Assuming the database enforces foreign keys, this won't fail.
rel_obj = qs.get()
if not self.field.rel.multiple:
setattr(rel_obj, self.field.rel.get_cache_name(), instance)
setattr(instance, self.cache_name, rel_obj)
if rel_obj is None and not self.field.null:
raise self.RelatedObjectDoesNotExist(
"%s has no %s." % (self.field.model.__name__, self.field.name)
)
else:
return rel_obj
def __set__(self, instance, value):
# If null=True, we can assign null here, but otherwise the value needs
# to be an instance of the related class.
if value is None and self.field.null is False:
raise ValueError(
'Cannot assign None: "%s.%s" does not allow null values.' %
(instance._meta.object_name, self.field.name)
)
elif value is not None and not isinstance(value, self.field.rel.to):
raise ValueError(
'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
value,
instance._meta.object_name,
self.field.name,
self.field.rel.to._meta.object_name,
)
)
elif value is not None:
if instance._state.db is None:
instance._state.db = router.db_for_write(instance.__class__, instance=value)
elif value._state.db is None:
value._state.db = router.db_for_write(value.__class__, instance=instance)
elif value._state.db is not None and instance._state.db is not None:
if not router.allow_relation(value, instance):
raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
# If we're setting the value of a OneToOneField to None, we need to clear
# out the cache on any old related object. Otherwise, deleting the
# previously-related object will also cause this object to be deleted,
# which is wrong.
if value is None:
# Look up the previously-related object, which may still be available
# since we've not yet cleared out the related field.
# Use the cache directly, instead of the accessor; if we haven't
# populated the cache, then we don't care - we're only accessing
# the object to invalidate the accessor cache, so there's no
# need to populate the cache just to expire it again.
related = getattr(instance, self.cache_name, None)
# If we've got an old related object, we need to clear out its
# cache. This cache also might not exist if the related object
# hasn't been accessed yet.
if related is not None:
setattr(related, self.field.rel.get_cache_name(), None)
for lh_field, rh_field in self.field.related_fields:
setattr(instance, lh_field.attname, None)
# Set the values of the related field.
else:
for lh_field, rh_field in self.field.related_fields:
pk = value._get_pk_val()
if pk is None:
raise ValueError(
'Cannot assign "%r": "%s" instance isn\'t saved in the database.' %
(value, self.field.rel.to._meta.object_name)
)
setattr(instance, lh_field.attname, getattr(value, rh_field.attname))
# Since we already know what the related object is, seed the related
# object caches now, too. This avoids another db hit if you get the
# object you just set.
setattr(instance, self.cache_name, value)
if value is not None and not self.field.rel.multiple:
setattr(value, self.field.rel.get_cache_name(), instance)
def create_foreign_related_manager(superclass, rel):
"""
Factory function to create a manager that subclasses another manager
(generally the default manager of a given model) and adds behaviors
specific to many-to-one relations.
"""
class RelatedManager(superclass):
def __init__(self, instance):
super(RelatedManager, self).__init__()
self.instance = instance
self.model = rel.related_model
self.field = rel.field
self.core_filters = {self.field.name: instance}
def __call__(self, **kwargs):
# We use **kwargs rather than a kwarg argument to enforce the
# `manager='manager_name'` syntax.
manager = getattr(self.model, kwargs.pop('manager'))
manager_class = create_foreign_related_manager(manager.__class__, rel)
return manager_class(self.instance)
do_not_call_in_templates = True
def get_queryset(self):
try:
return self.instance._prefetched_objects_cache[self.field.related_query_name()]
except (AttributeError, KeyError):
db = self._db or router.db_for_read(self.model, instance=self.instance)
empty_strings_as_null = connections[db].features.interprets_empty_strings_as_nulls
qs = super(RelatedManager, self).get_queryset()
qs._add_hints(instance=self.instance)
if self._db:
qs = qs.using(self._db)
qs = qs.filter(**self.core_filters)
for field in self.field.foreign_related_fields:
val = getattr(self.instance, field.attname)
if val is None or (val == '' and empty_strings_as_null):
return qs.none()
qs._known_related_objects = {self.field: {self.instance.pk: self.instance}}
return qs
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = super(RelatedManager, self).get_queryset()
queryset._add_hints(instance=instances[0])
queryset = queryset.using(queryset._db or self._db)
rel_obj_attr = self.field.get_local_related_value
instance_attr = self.field.get_foreign_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
query = {'%s__in' % self.field.name: instances}
queryset = queryset.filter(**query)
# Since we just bypassed this class' get_queryset(), we must manage
# the reverse relation manually.
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
setattr(rel_obj, self.field.name, instance)
cache_name = self.field.related_query_name()
return queryset, rel_obj_attr, instance_attr, False, cache_name
def add(self, *objs):
objs = list(objs)
db = router.db_for_write(self.model, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
for obj in objs:
if not isinstance(obj, self.model):
raise TypeError("'%s' instance expected, got %r" %
(self.model._meta.object_name, obj))
setattr(obj, self.field.name, self.instance)
obj.save()
add.alters_data = True
def create(self, **kwargs):
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).create(**kwargs)
create.alters_data = True
def get_or_create(self, **kwargs):
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs)
get_or_create.alters_data = True
def update_or_create(self, **kwargs):
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).update_or_create(**kwargs)
update_or_create.alters_data = True
# remove() and clear() are only provided if the ForeignKey can have a value of null.
if rel.field.null:
def remove(self, *objs, **kwargs):
if not objs:
return
bulk = kwargs.pop('bulk', True)
val = self.field.get_foreign_related_value(self.instance)
old_ids = set()
for obj in objs:
# Is obj actually part of this descriptor set?
if self.field.get_local_related_value(obj) == val:
old_ids.add(obj.pk)
else:
raise self.field.rel.to.DoesNotExist("%r is not related to %r." % (obj, self.instance))
self._clear(self.filter(pk__in=old_ids), bulk)
remove.alters_data = True
def clear(self, **kwargs):
bulk = kwargs.pop('bulk', True)
self._clear(self, bulk)
clear.alters_data = True
def _clear(self, queryset, bulk):
db = router.db_for_write(self.model, instance=self.instance)
queryset = queryset.using(db)
if bulk:
# `QuerySet.update()` is intrinsically atomic.
queryset.update(**{self.field.name: None})
else:
with transaction.atomic(using=db, savepoint=False):
for obj in queryset:
setattr(obj, self.field.name, None)
obj.save(update_fields=[self.field.name])
_clear.alters_data = True
def set(self, objs, **kwargs):
# Force evaluation of `objs` in case it's a queryset whose value
# could be affected by `manager.clear()`. Refs #19816.
objs = tuple(objs)
clear = kwargs.pop('clear', False)
if self.field.null:
db = router.db_for_write(self.model, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
if clear:
self.clear()
self.add(*objs)
else:
old_objs = set(self.using(db).all())
new_objs = []
for obj in objs:
if obj in old_objs:
old_objs.remove(obj)
else:
new_objs.append(obj)
self.remove(*old_objs)
self.add(*new_objs)
else:
self.add(*objs)
set.alters_data = True
return RelatedManager
class ForeignRelatedObjectsDescriptor(object):
"""
Accessor to the related objects manager on the reverse side of a
many-to-one relation.
In the example::
class Choice(Model):
poll = ForeignKey(Place, related_name='choices')
``poll.choices`` is a ``ForeignRelatedObjectsDescriptor`` instance.
"""
def __init__(self, rel):
self.rel = rel
self.field = rel.field
@cached_property
def related_manager_cls(self):
return create_foreign_related_manager(
self.rel.related_model._default_manager.__class__,
self.rel,
)
def __get__(self, instance, instance_type=None):
if instance is None:
return self
return self.related_manager_cls(instance)
def __set__(self, instance, value):
manager = self.__get__(instance)
manager.set(value)
def create_many_related_manager(superclass, rel, reverse):
"""
Factory function to create a manager that subclasses another manager
(generally the default manager of a given model) and adds behaviors
specific to many-to-many relations.
"""
class ManyRelatedManager(superclass):
def __init__(self, instance=None):
super(ManyRelatedManager, self).__init__()
self.instance = instance
if not reverse:
self.model = rel.to
self.query_field_name = rel.field.related_query_name()
self.prefetch_cache_name = rel.field.name
self.source_field_name = rel.field.m2m_field_name()
self.target_field_name = rel.field.m2m_reverse_field_name()
self.symmetrical = rel.symmetrical
else:
self.model = rel.related_model
self.query_field_name = rel.field.name
self.prefetch_cache_name = rel.field.related_query_name()
self.source_field_name = rel.field.m2m_reverse_field_name()
self.target_field_name = rel.field.m2m_field_name()
self.symmetrical = False
self.through = rel.through
self.reverse = reverse
self.source_field = self.through._meta.get_field(self.source_field_name)
self.target_field = self.through._meta.get_field(self.target_field_name)
self.core_filters = {}
for lh_field, rh_field in self.source_field.related_fields:
self.core_filters['%s__%s' % (self.query_field_name, rh_field.name)] = getattr(instance, rh_field.attname)
self.related_val = self.source_field.get_foreign_related_value(instance)
if None in self.related_val:
raise ValueError('"%r" needs to have a value for field "%s" before '
'this many-to-many relationship can be used.' %
(instance, self.source_field_name))
# Even if this relation is not to pk, we require still pk value.
# The wish is that the instance has been already saved to DB,
# although having a pk value isn't a guarantee of that.
if instance.pk is None:
raise ValueError("%r instance needs to have a primary key value before "
"a many-to-many relationship can be used." %
instance.__class__.__name__)
def __call__(self, **kwargs):
# We use **kwargs rather than a kwarg argument to enforce the
# `manager='manager_name'` syntax.
manager = getattr(self.model, kwargs.pop('manager'))
manager_class = create_many_related_manager(manager.__class__, rel, reverse)
return manager_class(instance=self.instance)
do_not_call_in_templates = True
def _build_remove_filters(self, removed_vals):
filters = Q(**{self.source_field_name: self.related_val})
# No need to add a subquery condition if removed_vals is a QuerySet without
# filters.
removed_vals_filters = (not isinstance(removed_vals, QuerySet) or
removed_vals._has_filters())
if removed_vals_filters:
filters &= Q(**{'%s__in' % self.target_field_name: removed_vals})
if self.symmetrical:
symmetrical_filters = Q(**{self.target_field_name: self.related_val})
if removed_vals_filters:
symmetrical_filters &= Q(
**{'%s__in' % self.source_field_name: removed_vals})
filters |= symmetrical_filters
return filters
def get_queryset(self):
try:
return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
except (AttributeError, KeyError):
qs = super(ManyRelatedManager, self).get_queryset()
qs._add_hints(instance=self.instance)
if self._db:
qs = qs.using(self._db)
return qs._next_is_sticky().filter(**self.core_filters)
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = super(ManyRelatedManager, self).get_queryset()
queryset._add_hints(instance=instances[0])
queryset = queryset.using(queryset._db or self._db)
query = {'%s__in' % self.query_field_name: instances}
queryset = queryset._next_is_sticky().filter(**query)
# M2M: need to annotate the query in order to get the primary model
# that the secondary model was actually related to. We know that
# there will already be a join on the join table, so we can just add
# the select.
# For non-autocreated 'through' models, can't assume we are
# dealing with PK values.
fk = self.through._meta.get_field(self.source_field_name)
join_table = self.through._meta.db_table
connection = connections[queryset.db]
qn = connection.ops.quote_name
queryset = queryset.extra(select={
'_prefetch_related_val_%s' % f.attname:
'%s.%s' % (qn(join_table), qn(f.column)) for f in fk.local_related_fields})
return (
queryset,
lambda result: tuple(
getattr(result, '_prefetch_related_val_%s' % f.attname)
for f in fk.local_related_fields
),
lambda inst: tuple(getattr(inst, f.attname) for f in fk.foreign_related_fields),
False,
self.prefetch_cache_name,
)
def add(self, *objs):
if not rel.through._meta.auto_created:
opts = self.through._meta
raise AttributeError(
"Cannot use add() on a ManyToManyField which specifies an "
"intermediary model. Use %s.%s's Manager instead." %
(opts.app_label, opts.object_name)
)
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
self._add_items(self.source_field_name, self.target_field_name, *objs)
# If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
if self.symmetrical:
self._add_items(self.target_field_name, self.source_field_name, *objs)
add.alters_data = True
def remove(self, *objs):
if not rel.through._meta.auto_created:
opts = self.through._meta
raise AttributeError(
"Cannot use remove() on a ManyToManyField which specifies "
"an intermediary model. Use %s.%s's Manager instead." %
(opts.app_label, opts.object_name)
)
self._remove_items(self.source_field_name, self.target_field_name, *objs)
remove.alters_data = True
def clear(self):
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
signals.m2m_changed.send(sender=self.through, action="pre_clear",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=None, using=db)
filters = self._build_remove_filters(super(ManyRelatedManager, self).get_queryset().using(db))
self.through._default_manager.using(db).filter(filters).delete()
signals.m2m_changed.send(sender=self.through, action="post_clear",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=None, using=db)
clear.alters_data = True
def set(self, objs, **kwargs):
if not rel.through._meta.auto_created:
opts = self.through._meta
raise AttributeError(
"Cannot set values on a ManyToManyField which specifies an "
"intermediary model. Use %s.%s's Manager instead." %
(opts.app_label, opts.object_name)
)
# Force evaluation of `objs` in case it's a queryset whose value
# could be affected by `manager.clear()`. Refs #19816.
objs = tuple(objs)
clear = kwargs.pop('clear', False)
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
if clear:
self.clear()
self.add(*objs)
else:
old_ids = set(self.using(db).values_list(self.target_field.related_field.attname, flat=True))
new_objs = []
for obj in objs:
fk_val = (self.target_field.get_foreign_related_value(obj)[0]
if isinstance(obj, self.model) else obj)
if fk_val in old_ids:
old_ids.remove(fk_val)
else:
new_objs.append(obj)
self.remove(*old_ids)
self.add(*new_objs)
set.alters_data = True
def create(self, **kwargs):
# This check needs to be done here, since we can't later remove this
# from the method lookup table, as we do with add and remove.
if not self.through._meta.auto_created:
opts = self.through._meta
raise AttributeError(
"Cannot use create() on a ManyToManyField which specifies "
"an intermediary model. Use %s.%s's Manager instead." %
(opts.app_label, opts.object_name)
)
db = router.db_for_write(self.instance.__class__, instance=self.instance)
new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs)
self.add(new_obj)
return new_obj
create.alters_data = True
def get_or_create(self, **kwargs):
db = router.db_for_write(self.instance.__class__, instance=self.instance)
obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs)
# We only need to add() if created because if we got an object back
# from get() then the relationship already exists.
if created:
self.add(obj)
return obj, created
get_or_create.alters_data = True
def update_or_create(self, **kwargs):
db = router.db_for_write(self.instance.__class__, instance=self.instance)
obj, created = super(ManyRelatedManager, self.db_manager(db)).update_or_create(**kwargs)
# We only need to add() if created because if we got an object back
# from get() then the relationship already exists.
if created:
self.add(obj)
return obj, created
update_or_create.alters_data = True
def _add_items(self, source_field_name, target_field_name, *objs):
# source_field_name: the PK fieldname in join table for the source object
# target_field_name: the PK fieldname in join table for the target object
# *objs - objects to add. Either object instances, or primary keys of object instances.
# If there aren't any objects, there is nothing to do.
from django.db.models import Model
if objs:
new_ids = set()
for obj in objs:
if isinstance(obj, self.model):
if not router.allow_relation(obj, self.instance):
raise ValueError(
'Cannot add "%r": instance is on database "%s", value is on database "%s"' %
(obj, self.instance._state.db, obj._state.db)
)
fk_val = self.through._meta.get_field(
target_field_name).get_foreign_related_value(obj)[0]
if fk_val is None:
raise ValueError(
'Cannot add "%r": the value for field "%s" is None' %
(obj, target_field_name)
)
new_ids.add(fk_val)
elif isinstance(obj, Model):
raise TypeError(
"'%s' instance expected, got %r" %
(self.model._meta.object_name, obj)
)
else:
new_ids.add(obj)
db = router.db_for_write(self.through, instance=self.instance)
vals = (self.through._default_manager.using(db)
.values_list(target_field_name, flat=True)
.filter(**{
source_field_name: self.related_val[0],
'%s__in' % target_field_name: new_ids,
}))
new_ids = new_ids - set(vals)
with transaction.atomic(using=db, savepoint=False):
if self.reverse or source_field_name == self.source_field_name:
# Don't send the signal when we are inserting the
# duplicate data row for symmetrical reverse entries.
signals.m2m_changed.send(sender=self.through, action='pre_add',
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=new_ids, using=db)
# Add the ones that aren't there already
self.through._default_manager.using(db).bulk_create([
self.through(**{
'%s_id' % source_field_name: self.related_val[0],
'%s_id' % target_field_name: obj_id,
})
for obj_id in new_ids
])
if self.reverse or source_field_name == self.source_field_name:
# Don't send the signal when we are inserting the
# duplicate data row for symmetrical reverse entries.
signals.m2m_changed.send(sender=self.through, action='post_add',
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=new_ids, using=db)
def _remove_items(self, source_field_name, target_field_name, *objs):
# source_field_name: the PK colname in join table for the source object
# target_field_name: the PK colname in join table for the target object
# *objs - objects to remove
if not objs:
return
# Check that all the objects are of the right type
old_ids = set()
for obj in objs:
if isinstance(obj, self.model):
fk_val = self.target_field.get_foreign_related_value(obj)[0]
old_ids.add(fk_val)
else:
old_ids.add(obj)
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
# Send a signal to the other end if need be.
signals.m2m_changed.send(sender=self.through, action="pre_remove",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=old_ids, using=db)
target_model_qs = super(ManyRelatedManager, self).get_queryset()
if target_model_qs._has_filters():
old_vals = target_model_qs.using(db).filter(**{
'%s__in' % self.target_field.related_field.attname: old_ids})
else:
old_vals = old_ids
filters = self._build_remove_filters(old_vals)
self.through._default_manager.using(db).filter(filters).delete()
signals.m2m_changed.send(sender=self.through, action="post_remove",
instance=self.instance, reverse=self.reverse,
model=self.model, pk_set=old_ids, using=db)
return ManyRelatedManager
class ManyRelatedObjectsDescriptor(ForeignRelatedObjectsDescriptor):
"""
Accessor to the related objects manager on the forward and reverse sides of
a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
``pizza.toppings`` and ``topping.pizzas`` are ManyRelatedObjectsDescriptor
instances.
"""
def __init__(self, rel, reverse=False):
super(ManyRelatedObjectsDescriptor, self).__init__(rel)
self.reverse = reverse
@property
def through(self):
# through is provided so that you have easy access to the through
# model (Book.authors.through) for inlines, etc. This is done as
# a property to ensure that the fully resolved value is returned.
return self.rel.through
@cached_property
def related_manager_cls(self):
model = self.rel.related_model if self.reverse else self.rel.to
return create_many_related_manager(
model._default_manager.__class__,
self.rel,
reverse=self.reverse,
)
class ForeignObjectRel(object):
"""
Used by ForeignObject to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
# Field flags
auto_created = True
concrete = False
editable = False
is_relation = True
def __init__(self, field, to, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, on_delete=None):
self.field = field
self.to = to
self.related_name = related_name
self.related_query_name = related_query_name
self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to
self.parent_link = parent_link
self.on_delete = on_delete
self.symmetrical = False
self.multiple = True
# Some of the following cached_properties can't be initialized in
# __init__ as the field doesn't have its model yet. Calling these methods
# before field.contribute_to_class() has been called will result in
# AttributeError
@cached_property
def model(self):
return self.to
@cached_property
def hidden(self):
return self.is_hidden()
@cached_property
def name(self):
return self.field.related_query_name()
@cached_property
def related_model(self):
if not self.field.model:
raise AttributeError(
"This property can't be accessed before self.field.contribute_to_class has been called.")
return self.field.model
@cached_property
def many_to_many(self):
return self.field.many_to_many
@cached_property
def many_to_one(self):
return self.field.one_to_many
@cached_property
def one_to_many(self):
return self.field.many_to_one
@cached_property
def one_to_one(self):
return self.field.one_to_one
def __repr__(self):
return '<%s: %s.%s>' % (
type(self).__name__,
self.related_model._meta.app_label,
self.related_model._meta.model_name,
)
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH,
limit_to_currently_related=False):
"""
Return choices with a default blank choices included, for use as
SelectField choices for this field.
Analog of django.db.models.fields.Field.get_choices(), provided
initially for utilization by RelatedFieldListFilter.
"""
first_choice = blank_choice if include_blank else []
queryset = self.related_model._default_manager.all()
if limit_to_currently_related:
queryset = queryset.complex_filter(
{'%s__isnull' % self.related_model._meta.model_name: False}
)
lst = [(x._get_pk_val(), smart_text(x)) for x in queryset]
return first_choice + lst
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
# Defer to the actual field definition for db prep
return self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=prepared)
def is_hidden(self):
"Should the related object be hidden?"
return self.related_name is not None and self.related_name[-1] == '+'
def get_joining_columns(self):
return self.field.get_reverse_joining_columns()
def get_extra_restriction(self, where_class, alias, related_alias):
return self.field.get_extra_restriction(where_class, related_alias, alias)
def set_field_name(self):
"""
Sets the related field's name, this is not available until later stages
of app loading, so set_field_name is called from
set_attributes_from_rel()
"""
# By default foreign object doesn't relate to any remote field (for
# example custom multicolumn joins currently have no remote field).
self.field_name = None
def get_accessor_name(self, model=None):
# This method encapsulates the logic that decides what name to give an
# accessor descriptor that retrieves related many-to-one or
# many-to-many objects. It uses the lower-cased object_name + "_set",
# but this can be overridden with the "related_name" option.
# Due to backwards compatibility ModelForms need to be able to provide
# an alternate model. See BaseInlineFormSet.get_default_prefix().
opts = model._meta if model else self.related_model._meta
model = model or self.related_model
if self.multiple:
# If this is a symmetrical m2m relation on self, there is no reverse accessor.
if self.symmetrical and model == self.to:
return None
if self.related_name:
return self.related_name
if opts.default_related_name:
return opts.default_related_name % {
'model_name': opts.model_name.lower(),
'app_label': opts.app_label.lower(),
}
return opts.model_name + ('_set' if self.multiple else '')
def get_cache_name(self):
return "_%s_cache" % self.get_accessor_name()
def get_path_info(self):
return self.field.get_reverse_path_info()
class ManyToOneRel(ForeignObjectRel):
"""
Used by the ForeignKey field to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
Note: Because we somewhat abuse the Rel objects by using them as reverse
fields we get the funny situation where
``ManyToOneRel.many_to_one == False`` and
``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual
ManyToOneRel class is a private API and there is work underway to turn
reverse relations into actual fields.
"""
def __init__(self, field, to, field_name, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, on_delete=None):
super(ManyToOneRel, self).__init__(
field, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
self.field_name = field_name
def get_related_field(self):
"""
Return the Field in the 'to' object to which this relationship is tied.
"""
field = self.to._meta.get_field(self.field_name)
if not field.concrete:
raise FieldDoesNotExist("No related field named '%s'" %
self.field_name)
return field
def set_field_name(self):
self.field_name = self.field_name or self.to._meta.pk.name
class OneToOneRel(ManyToOneRel):
"""
Used by OneToOneField to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
def __init__(self, field, to, field_name, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, on_delete=None):
super(OneToOneRel, self).__init__(
field, to, field_name,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
self.multiple = False
class ManyToManyRel(ForeignObjectRel):
"""
Used by ManyToManyField to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
def __init__(self, field, to, related_name=None, related_query_name=None,
limit_choices_to=None, symmetrical=True, through=None, through_fields=None,
db_constraint=True):
super(ManyToManyRel, self).__init__(
field, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
)
if through and not db_constraint:
raise ValueError("Can't supply a through model and db_constraint=False")
self.through = through
if through_fields and not through:
raise ValueError("Cannot specify through_fields without a through model")
self.through_fields = through_fields
self.symmetrical = symmetrical
self.db_constraint = db_constraint
def get_related_field(self):
"""
Return the field in the 'to' object to which this relationship is tied.
Provided for symmetry with ManyToOneRel.
"""
opts = self.through._meta
if self.through_fields:
field = opts.get_field(self.through_fields[0])
else:
for field in opts.fields:
rel = getattr(field, 'rel', None)
if rel and rel.to == self.to:
break
return field.foreign_related_fields[0]
class ForeignObject(RelatedField):
"""
Abstraction of the ForeignKey relation, supports multi-column relations.
"""
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
requires_unique_target = True
related_accessor_class = ForeignRelatedObjectsDescriptor
rel_class = ForeignObjectRel
def __init__(self, to, from_fields, to_fields, rel=None, related_name=None,
related_query_name=None, limit_choices_to=None, parent_link=False,
on_delete=CASCADE, swappable=True, **kwargs):
if rel is None:
rel = self.rel_class(
self, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
super(ForeignObject, self).__init__(rel=rel, **kwargs)
self.from_fields = from_fields
self.to_fields = to_fields
self.swappable = swappable
def check(self, **kwargs):
errors = super(ForeignObject, self).check(**kwargs)
errors.extend(self._check_unique_target())
return errors
def _check_unique_target(self):
rel_is_string = isinstance(self.rel.to, six.string_types)
if rel_is_string or not self.requires_unique_target:
return []
try:
self.foreign_related_fields
except FieldDoesNotExist:
return []
try:
self.rel
except AttributeError:
return []
has_unique_field = any(rel_field.unique
for rel_field in self.foreign_related_fields)
if not has_unique_field and len(self.foreign_related_fields) > 1:
field_combination = ', '.join("'%s'" % rel_field.name
for rel_field in self.foreign_related_fields)
model_name = self.rel.to.__name__
return [
checks.Error(
"None of the fields %s on model '%s' have a unique=True constraint."
% (field_combination, model_name),
hint=None,
obj=self,
id='fields.E310',
)
]
elif not has_unique_field:
field_name = self.foreign_related_fields[0].name
model_name = self.rel.to.__name__
return [
checks.Error(
("'%s.%s' must set unique=True "
"because it is referenced by a foreign key.") % (model_name, field_name),
hint=None,
obj=self,
id='fields.E311',
)
]
else:
return []
def deconstruct(self):
name, path, args, kwargs = super(ForeignObject, self).deconstruct()
kwargs['from_fields'] = self.from_fields
kwargs['to_fields'] = self.to_fields
if self.rel.related_name is not None:
kwargs['related_name'] = self.rel.related_name
if self.rel.related_query_name is not None:
kwargs['related_query_name'] = self.rel.related_query_name
if self.rel.on_delete != CASCADE:
kwargs['on_delete'] = self.rel.on_delete
if self.rel.parent_link:
kwargs['parent_link'] = self.rel.parent_link
# Work out string form of "to"
if isinstance(self.rel.to, six.string_types):
kwargs['to'] = self.rel.to
else:
kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error
if hasattr(kwargs['to'], "setting_name"):
if kwargs['to'].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ForeignKey pointing to a model "
"that is swapped in place of more than one model (%s and %s)"
% (kwargs['to'].setting_name, swappable_setting)
)
# Set it
from django.db.migrations.writer import SettingsReference
kwargs['to'] = SettingsReference(
kwargs['to'],
swappable_setting,
)
return name, path, args, kwargs
def resolve_related_fields(self):
if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
raise ValueError('Foreign Object from and to fields must be the same non-zero length')
if isinstance(self.rel.to, six.string_types):
raise ValueError('Related model %r cannot be resolved' % self.rel.to)
related_fields = []
for index in range(len(self.from_fields)):
from_field_name = self.from_fields[index]
to_field_name = self.to_fields[index]
from_field = (self if from_field_name == 'self'
else self.opts.get_field(from_field_name))
to_field = (self.rel.to._meta.pk if to_field_name is None
else self.rel.to._meta.get_field(to_field_name))
related_fields.append((from_field, to_field))
return related_fields
@property
def related_fields(self):
if not hasattr(self, '_related_fields'):
self._related_fields = self.resolve_related_fields()
return self._related_fields
@property
def reverse_related_fields(self):
return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]
@property
def local_related_fields(self):
return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)
@property
def foreign_related_fields(self):
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
def get_local_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.local_related_fields)
def get_foreign_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.foreign_related_fields)
@staticmethod
def get_instance_value_for_fields(instance, fields):
ret = []
opts = instance._meta
for field in fields:
# Gotcha: in some cases (like fixture loading) a model can have
# different values in parent_ptr_id and parent's id. So, use
# instance.pk (that is, parent_ptr_id) when asked for instance.id.
if field.primary_key:
possible_parent_link = opts.get_ancestor_link(field.model)
if (not possible_parent_link or
possible_parent_link.primary_key or
possible_parent_link.model._meta.abstract):
ret.append(instance.pk)
continue
ret.append(getattr(instance, field.attname))
return tuple(ret)
def get_attname_column(self):
attname, column = super(ForeignObject, self).get_attname_column()
return attname, None
def get_joining_columns(self, reverse_join=False):
source = self.reverse_related_fields if reverse_join else self.related_fields
return tuple((lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source)
def get_reverse_joining_columns(self):
return self.get_joining_columns(reverse_join=True)
def get_extra_descriptor_filter(self, instance):
"""
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field.
The filter should be either a dict usable in .filter(**kwargs) call or
a Q-object. The condition will be ANDed together with the relation's
joining columns.
A parallel method is get_extra_restriction() which is used in
JOIN and subquery conditions.
"""
return {}
def get_extra_restriction(self, where_class, alias, related_alias):
"""
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method.
Note that currently referring both the 'alias' and 'related_alias'
will not work in some conditions, like subquery pushdown.
A parallel method is get_extra_descriptor_filter() which is used in
instance.fieldname related object fetching.
"""
return None
def get_path_info(self):
"""
Get path from this field to the related model.
"""
opts = self.rel.to._meta
from_opts = self.model._meta
return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)]
def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.rel.to._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
return pathinfos
def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookups,
raw_value):
from django.db.models.sql.where import SubqueryConstraint, AND, OR
root_constraint = constraint_class()
assert len(targets) == len(sources)
if len(lookups) > 1:
raise exceptions.FieldError('Relation fields do not support nested lookups')
lookup_type = lookups[0]
def get_normalized_value(value):
from django.db.models import Model
if isinstance(value, Model):
value_list = []
for source in sources:
# Account for one-to-one relations when sent a different model
while not isinstance(value, source.model) and source.rel:
source = source.rel.to._meta.get_field(source.rel.field_name)
value_list.append(getattr(value, source.attname))
return tuple(value_list)
elif not isinstance(value, tuple):
return (value,)
return value
is_multicolumn = len(self.related_fields) > 1
if (hasattr(raw_value, '_as_sql') or
hasattr(raw_value, 'get_compiler')):
root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
[source.name for source in sources], raw_value),
AND)
elif lookup_type == 'isnull':
root_constraint.add(IsNull(targets[0].get_col(alias, sources[0]), raw_value), AND)
elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
and not is_multicolumn)):
value = get_normalized_value(raw_value)
for target, source, val in zip(targets, sources, value):
lookup_class = target.get_lookup(lookup_type)
root_constraint.add(
lookup_class(target.get_col(alias, source), val), AND)
elif lookup_type in ['range', 'in'] and not is_multicolumn:
values = [get_normalized_value(value) for value in raw_value]
value = [val[0] for val in values]
lookup_class = targets[0].get_lookup(lookup_type)
root_constraint.add(lookup_class(targets[0].get_col(alias, sources[0]), value), AND)
elif lookup_type == 'in':
values = [get_normalized_value(value) for value in raw_value]
root_constraint.connector = OR
for value in values:
value_constraint = constraint_class()
for source, target, val in zip(sources, targets, value):
lookup_class = target.get_lookup('exact')
lookup = lookup_class(target.get_col(alias, source), val)
value_constraint.add(lookup, AND)
root_constraint.add(value_constraint, OR)
else:
raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
return root_constraint
@property
def attnames(self):
return tuple(field.attname for field in self.local_related_fields)
def get_defaults(self):
return tuple(field.get_default() for field in self.local_related_fields)
def contribute_to_class(self, cls, name, virtual_only=False):
super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self))
def contribute_to_related_class(self, cls, related):
# Internal FK's - i.e., those with a related name ending with '+' -
# and swapped models don't get a related descriptor.
if not self.rel.is_hidden() and not related.related_model._meta.swapped:
setattr(cls, related.get_accessor_name(), self.related_accessor_class(related))
# While 'limit_choices_to' might be a callable, simply pass
# it along for later - this is too early because it's still
# model load time.
if self.rel.limit_choices_to:
cls._meta.related_fkey_lookups.append(self.rel.limit_choices_to)
class ForeignKey(ForeignObject):
"""
Provide a many-to-one relation by adding a column to the local model
to hold the remote value.
By default ForeignKey will target the pk of the remote model but this
behavior can be changed by using the ``to_field`` argument.
"""
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
rel_class = ManyToOneRel
empty_strings_allowed = False
default_error_messages = {
'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
}
description = _("Foreign Key (type determined by related field)")
def __init__(self, to, to_field=None, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, on_delete=CASCADE,
db_constraint=True, **kwargs):
try:
to._meta.model_name
except AttributeError:
assert isinstance(to, six.string_types), (
"%s(%r) is invalid. First parameter to ForeignKey must be "
"either a model, a model name, or the string %r" % (
self.__class__.__name__, to,
RECURSIVE_RELATIONSHIP_CONSTANT,
)
)
else:
# For backwards compatibility purposes, we need to *try* and set
# the to_field during FK construction. It won't be guaranteed to
# be correct until contribute_to_class is called. Refs #12190.
to_field = to_field or (to._meta.pk and to._meta.pk.name)
kwargs['rel'] = self.rel_class(
self, to, to_field,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
kwargs['db_index'] = kwargs.get('db_index', True)
super(ForeignKey, self).__init__(
to, from_fields=['self'], to_fields=[to_field], **kwargs)
self.db_constraint = db_constraint
def check(self, **kwargs):
errors = super(ForeignKey, self).check(**kwargs)
errors.extend(self._check_on_delete())
errors.extend(self._check_unique())
return errors
def _check_on_delete(self):
on_delete = getattr(self.rel, 'on_delete', None)
if on_delete == SET_NULL and not self.null:
return [
checks.Error(
'Field specifies on_delete=SET_NULL, but cannot be null.',
hint='Set null=True argument on the field, or change the on_delete rule.',
obj=self,
id='fields.E320',
)
]
elif on_delete == SET_DEFAULT and not self.has_default():
return [
checks.Error(
'Field specifies on_delete=SET_DEFAULT, but has no default value.',
hint='Set a default value, or change the on_delete rule.',
obj=self,
id='fields.E321',
)
]
else:
return []
def _check_unique(self, **kwargs):
return [
checks.Warning(
'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
obj=self,
id='fields.W342',
)
] if self.unique else []
def deconstruct(self):
name, path, args, kwargs = super(ForeignKey, self).deconstruct()
del kwargs['to_fields']
del kwargs['from_fields']
# Handle the simpler arguments
if self.db_index:
del kwargs['db_index']
else:
kwargs['db_index'] = False
if self.db_constraint is not True:
kwargs['db_constraint'] = self.db_constraint
# Rel needs more work.
to_meta = getattr(self.rel.to, "_meta", None)
if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
kwargs['to_field'] = self.rel.field_name
return name, path, args, kwargs
@property
def related_field(self):
return self.foreign_related_fields[0]
def get_reverse_path_info(self):
"""
Get path from the related model to this field's model.
"""
opts = self.model._meta
from_opts = self.rel.to._meta
pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
return pathinfos
def validate(self, value, model_instance):
if self.rel.parent_link:
return
super(ForeignKey, self).validate(value, model_instance)
if value is None:
return
using = router.db_for_read(model_instance.__class__, instance=model_instance)
qs = self.rel.to._default_manager.using(using).filter(
**{self.rel.field_name: value}
)
qs = qs.complex_filter(self.get_limit_choices_to())
if not qs.exists():
raise exceptions.ValidationError(
self.error_messages['invalid'],
code='invalid',
params={
'model': self.rel.to._meta.verbose_name, 'pk': value,
'field': self.rel.field_name, 'value': value,
}, # 'pk' is included for backwards compatibility
)
def get_attname(self):
return '%s_id' % self.name
def get_attname_column(self):
attname = self.get_attname()
column = self.db_column or attname
return attname, column
def get_default(self):
"Here we check if the default value is an object and return the to_field if so."
field_default = super(ForeignKey, self).get_default()
if isinstance(field_default, self.rel.to):
return getattr(field_default, self.related_field.attname)
return field_default
def get_db_prep_save(self, value, connection):
if value is None or (value == '' and
(not self.related_field.empty_strings_allowed or
connection.features.interprets_empty_strings_as_nulls)):
return None
else:
return self.related_field.get_db_prep_save(value, connection=connection)
def value_to_string(self, obj):
if not obj:
# In required many-to-one fields with only one available choice,
# select that one available choice. Note: For SelectFields
# we have to check that the length of choices is *2*, not 1,
# because SelectFields always have an initial "blank" value.
if not self.blank and self.choices:
choice_list = self.get_choices_default()
if len(choice_list) == 2:
return smart_text(choice_list[1][0])
return super(ForeignKey, self).value_to_string(obj)
def contribute_to_related_class(self, cls, related):
super(ForeignKey, self).contribute_to_related_class(cls, related)
if self.rel.field_name is None:
self.rel.field_name = cls._meta.pk.name
def formfield(self, **kwargs):
db = kwargs.pop('using', None)
if isinstance(self.rel.to, six.string_types):
raise ValueError("Cannot create form field for %r yet, because "
"its related model %r has not been loaded yet" %
(self.name, self.rel.to))
defaults = {
'form_class': forms.ModelChoiceField,
'queryset': self.rel.to._default_manager.using(db),
'to_field_name': self.rel.field_name,
}
defaults.update(kwargs)
return super(ForeignKey, self).formfield(**defaults)
def db_type(self, connection):
# The database column type of a ForeignKey is the column type
# of the field to which it points. An exception is if the ForeignKey
# points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
# in which case the column type is simply that of an IntegerField.
# If the database needs similar types for key fields however, the only
# thing we can do is making AutoField an IntegerField.
rel_field = self.related_field
if (isinstance(rel_field, AutoField) or
(not connection.features.related_fields_match_type and
isinstance(rel_field, (PositiveIntegerField,
PositiveSmallIntegerField)))):
return IntegerField().db_type(connection=connection)
return rel_field.db_type(connection=connection)
def db_parameters(self, connection):
return {"type": self.db_type(connection), "check": []}
def convert_empty_strings(self, value, expression, connection, context):
if (not value) and isinstance(value, six.string_types):
return None
return value
def get_db_converters(self, connection):
converters = super(ForeignKey, self).get_db_converters(connection)
if connection.features.interprets_empty_strings_as_nulls:
converters += [self.convert_empty_strings]
return converters
def get_col(self, alias, output_field=None):
return super(ForeignKey, self).get_col(alias, output_field or self.related_field)
class OneToOneField(ForeignKey):
"""
A OneToOneField is essentially the same as a ForeignKey, with the exception
that it always carries a "unique" constraint with it and the reverse
relation always returns the object pointed to (since there will only ever
be one), rather than returning a list.
"""
# Field flags
many_to_many = False
many_to_one = False
one_to_many = False
one_to_one = True
related_accessor_class = SingleRelatedObjectDescriptor
rel_class = OneToOneRel
description = _("One-to-one relationship")
def __init__(self, to, to_field=None, **kwargs):
kwargs['unique'] = True
super(OneToOneField, self).__init__(to, to_field, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(OneToOneField, self).deconstruct()
if "unique" in kwargs:
del kwargs['unique']
return name, path, args, kwargs
def formfield(self, **kwargs):
if self.rel.parent_link:
return None
return super(OneToOneField, self).formfield(**kwargs)
def save_form_data(self, instance, data):
if isinstance(data, self.rel.to):
setattr(instance, self.name, data)
else:
setattr(instance, self.attname, data)
def _check_unique(self, **kwargs):
# Override ForeignKey since check isn't applicable here.
return []
def create_many_to_many_intermediary_model(field, klass):
from django.db import models
managed = True
if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT:
to_model = field.rel.to
to = to_model.split('.')[-1]
def set_managed(field, model, cls):
field.rel.through._meta.managed = model._meta.managed or cls._meta.managed
add_lazy_relation(klass, field, to_model, set_managed)
elif isinstance(field.rel.to, six.string_types):
to = klass._meta.object_name
to_model = klass
managed = klass._meta.managed
else:
to = field.rel.to._meta.object_name
to_model = field.rel.to
managed = klass._meta.managed or to_model._meta.managed
name = '%s_%s' % (klass._meta.object_name, field.name)
if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name:
from_ = 'from_%s' % to.lower()
to = 'to_%s' % to.lower()
else:
from_ = klass._meta.model_name
to = to.lower()
meta = type(str('Meta'), (object,), {
'db_table': field._get_m2m_db_table(klass._meta),
'managed': managed,
'auto_created': klass,
'app_label': klass._meta.app_label,
'db_tablespace': klass._meta.db_tablespace,
'unique_together': (from_, to),
'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
'apps': field.model._meta.apps,
})
# Construct and return the new class.
return type(str(name), (models.Model,), {
'Meta': meta,
'__module__': klass.__module__,
from_: models.ForeignKey(
klass,
related_name='%s+' % name,
db_tablespace=field.db_tablespace,
db_constraint=field.rel.db_constraint,
),
to: models.ForeignKey(
to_model,
related_name='%s+' % name,
db_tablespace=field.db_tablespace,
db_constraint=field.rel.db_constraint,
)
})
class ManyToManyField(RelatedField):
"""
Provide a many-to-many relation by using an intermediary model that
holds two ForeignKey fields pointed at the two sides of the relation.
Unless a ``through`` model was provided, ManyToManyField will use the
create_many_to_many_intermediary_model factory to automatically generate
the intermediary model.
"""
# Field flags
many_to_many = True
many_to_one = False
one_to_many = False
one_to_one = False
rel_class = ManyToManyRel
description = _("Many-to-many relationship")
def __init__(self, to, related_name=None, related_query_name=None,
limit_choices_to=None, symmetrical=None, through=None,
through_fields=None, db_constraint=True, db_table=None,
swappable=True, **kwargs):
try:
to._meta
except AttributeError:
assert isinstance(to, six.string_types), (
"%s(%r) is invalid. First parameter to ManyToManyField must be "
"either a model, a model name, or the string %r" %
(self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
)
# Class names must be ASCII in Python 2.x, so we forcibly coerce it
# here to break early if there's a problem.
to = str(to)
if symmetrical is None:
symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT)
if through is not None:
assert db_table is None, (
"Cannot specify a db_table if an intermediary model is used."
)
kwargs['rel'] = self.rel_class(
self, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
symmetrical=symmetrical,
through=through,
through_fields=through_fields,
db_constraint=db_constraint,
)
super(ManyToManyField, self).__init__(**kwargs)
self.db_table = db_table
self.swappable = swappable
def check(self, **kwargs):
errors = super(ManyToManyField, self).check(**kwargs)
errors.extend(self._check_unique(**kwargs))
errors.extend(self._check_relationship_model(**kwargs))
errors.extend(self._check_ignored_options(**kwargs))
return errors
def _check_unique(self, **kwargs):
if self.unique:
return [
checks.Error(
'ManyToManyFields cannot be unique.',
hint=None,
obj=self,
id='fields.E330',
)
]
return []
def _check_ignored_options(self, **kwargs):
warnings = []
if self.null:
warnings.append(
checks.Warning(
'null has no effect on ManyToManyField.',
hint=None,
obj=self,
id='fields.W340',
)
)
if len(self._validators) > 0:
warnings.append(
checks.Warning(
'ManyToManyField does not support validators.',
hint=None,
obj=self,
id='fields.W341',
)
)
return warnings
def _check_relationship_model(self, from_model=None, **kwargs):
if hasattr(self.rel.through, '_meta'):
qualified_model_name = "%s.%s" % (
self.rel.through._meta.app_label, self.rel.through.__name__)
else:
qualified_model_name = self.rel.through
errors = []
if self.rel.through not in apps.get_models(include_auto_created=True):
# The relationship model is not installed.
errors.append(
checks.Error(
("Field specifies a many-to-many relation through model "
"'%s', which has not been installed.") %
qualified_model_name,
hint=None,
obj=self,
id='fields.E331',
)
)
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
# Set some useful local variables
to_model = self.rel.to
from_model_name = from_model._meta.object_name
if isinstance(to_model, six.string_types):
to_model_name = to_model
else:
to_model_name = to_model._meta.object_name
relationship_model_name = self.rel.through._meta.object_name
self_referential = from_model == to_model
# Check symmetrical attribute.
if (self_referential and self.rel.symmetrical and
not self.rel.through._meta.auto_created):
errors.append(
checks.Error(
'Many-to-many fields with intermediate tables must not be symmetrical.',
hint=None,
obj=self,
id='fields.E332',
)
)
# Count foreign keys in intermediate model
if self_referential:
seen_self = sum(from_model == getattr(field.rel, 'to', None)
for field in self.rel.through._meta.fields)
if seen_self > 2 and not self.rel.through_fields:
errors.append(
checks.Error(
("The model is used as an intermediate model by "
"'%s', but it has more than two foreign keys "
"to '%s', which is ambiguous. You must specify "
"which two foreign keys Django should use via the "
"through_fields keyword argument.") % (self, from_model_name),
hint=("Use through_fields to specify which two "
"foreign keys Django should use."),
obj=self.rel.through,
id='fields.E333',
)
)
else:
# Count foreign keys in relationship model
seen_from = sum(from_model == getattr(field.rel, 'to', None)
for field in self.rel.through._meta.fields)
seen_to = sum(to_model == getattr(field.rel, 'to', None)
for field in self.rel.through._meta.fields)
if seen_from > 1 and not self.rel.through_fields:
errors.append(
checks.Error(
("The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"from '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument.") % (self, from_model_name),
hint=('If you want to create a recursive relationship, '
'use ForeignKey("self", symmetrical=False, '
'through="%s").') % relationship_model_name,
obj=self,
id='fields.E334',
)
)
if seen_to > 1 and not self.rel.through_fields:
errors.append(
checks.Error(
("The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"to '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument.") % (self, to_model_name),
hint=('If you want to create a recursive '
'relationship, use ForeignKey("self", '
'symmetrical=False, through="%s").') % relationship_model_name,
obj=self,
id='fields.E335',
)
)
if seen_from == 0 or seen_to == 0:
errors.append(
checks.Error(
("The model is used as an intermediate model by "
"'%s', but it does not have a foreign key to '%s' or '%s'.") % (
self, from_model_name, to_model_name
),
hint=None,
obj=self.rel.through,
id='fields.E336',
)
)
# Validate `through_fields`.
if self.rel.through_fields is not None:
# Validate that we're given an iterable of at least two items
# and that none of them is "falsy".
if not (len(self.rel.through_fields) >= 2 and
self.rel.through_fields[0] and self.rel.through_fields[1]):
errors.append(
checks.Error(
("Field specifies 'through_fields' but does not "
"provide the names of the two link fields that should be "
"used for the relation through model "
"'%s'.") % qualified_model_name,
hint=("Make sure you specify 'through_fields' as "
"through_fields=('field1', 'field2')"),
obj=self,
id='fields.E337',
)
)
# Validate the given through fields -- they should be actual
# fields on the through model, and also be foreign keys to the
# expected models.
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
source, through, target = from_model, self.rel.through, self.rel.to
source_field_name, target_field_name = self.rel.through_fields[:2]
for field_name, related_model in ((source_field_name, source),
(target_field_name, target)):
possible_field_names = []
for f in through._meta.fields:
if hasattr(f, 'rel') and getattr(f.rel, 'to', None) == related_model:
possible_field_names.append(f.name)
if possible_field_names:
hint = ("Did you mean one of the following foreign "
"keys to '%s': %s?") % (related_model._meta.object_name,
', '.join(possible_field_names))
else:
hint = None
try:
field = through._meta.get_field(field_name)
except FieldDoesNotExist:
errors.append(
checks.Error(
("The intermediary model '%s' has no field '%s'.") % (
qualified_model_name, field_name),
hint=hint,
obj=self,
id='fields.E338',
)
)
else:
if not (hasattr(field, 'rel') and
getattr(field.rel, 'to', None) == related_model):
errors.append(
checks.Error(
"'%s.%s' is not a foreign key to '%s'." % (
through._meta.object_name, field_name,
related_model._meta.object_name),
hint=hint,
obj=self,
id='fields.E339',
)
)
return errors
def deconstruct(self):
name, path, args, kwargs = super(ManyToManyField, self).deconstruct()
# Handle the simpler arguments.
if self.db_table is not None:
kwargs['db_table'] = self.db_table
if self.rel.db_constraint is not True:
kwargs['db_constraint'] = self.rel.db_constraint
if self.rel.related_name is not None:
kwargs['related_name'] = self.rel.related_name
if self.rel.related_query_name is not None:
kwargs['related_query_name'] = self.rel.related_query_name
# Rel needs more work.
if isinstance(self.rel.to, six.string_types):
kwargs['to'] = self.rel.to
else:
kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
if getattr(self.rel, 'through', None) is not None:
if isinstance(self.rel.through, six.string_types):
kwargs['through'] = self.rel.through
elif not self.rel.through._meta.auto_created:
kwargs['through'] = "%s.%s" % (self.rel.through._meta.app_label, self.rel.through._meta.object_name)
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error.
if hasattr(kwargs['to'], "setting_name"):
if kwargs['to'].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ManyToManyField pointing to a "
"model that is swapped in place of more than one model "
"(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
)
from django.db.migrations.writer import SettingsReference
kwargs['to'] = SettingsReference(
kwargs['to'],
swappable_setting,
)
return name, path, args, kwargs
def _get_path_info(self, direct=False):
"""
Called by both direct and indirect m2m traversal.
"""
pathinfos = []
int_model = self.rel.through
linkfield1 = int_model._meta.get_field(self.m2m_field_name())
linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
if direct:
join1infos = linkfield1.get_reverse_path_info()
join2infos = linkfield2.get_path_info()
else:
join1infos = linkfield2.get_reverse_path_info()
join2infos = linkfield1.get_path_info()
pathinfos.extend(join1infos)
pathinfos.extend(join2infos)
return pathinfos
def get_path_info(self):
return self._get_path_info(direct=True)
def get_reverse_path_info(self):
return self._get_path_info(direct=False)
def get_choices_default(self):
return Field.get_choices(self, include_blank=False)
def _get_m2m_db_table(self, opts):
"""
Function that can be curried to provide the m2m table name for this
relation.
"""
if self.rel.through is not None:
return self.rel.through._meta.db_table
elif self.db_table:
return self.db_table
else:
return utils.truncate_name('%s_%s' % (opts.db_table, self.name),
connection.ops.max_name_length())
def _get_m2m_attr(self, related, attr):
"""
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
if self.rel.through_fields is not None:
link_field_name = self.rel.through_fields[0]
else:
link_field_name = None
for f in self.rel.through._meta.fields:
if (f.is_relation and f.rel.to == related.related_model and
(link_field_name is None or link_field_name == f.name)):
setattr(self, cache_attr, getattr(f, attr))
return getattr(self, cache_attr)
def _get_m2m_reverse_attr(self, related, attr):
"""
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
"""
cache_attr = '_m2m_reverse_%s_cache' % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
found = False
if self.rel.through_fields is not None:
link_field_name = self.rel.through_fields[1]
else:
link_field_name = None
for f in self.rel.through._meta.fields:
if f.is_relation and f.rel.to == related.model:
if link_field_name is None and related.related_model == related.model:
# If this is an m2m-intermediate to self,
# the first foreign key you find will be
# the source column. Keep searching for
# the second foreign key.
if found:
setattr(self, cache_attr, getattr(f, attr))
break
else:
found = True
elif link_field_name is None or link_field_name == f.name:
setattr(self, cache_attr, getattr(f, attr))
break
return getattr(self, cache_attr)
def value_to_string(self, obj):
data = ''
if obj:
qs = getattr(obj, self.name).all()
data = [instance._get_pk_val() for instance in qs]
else:
# In required many-to-many fields with only one available choice,
# select that one available choice.
if not self.blank:
choices_list = self.get_choices_default()
if len(choices_list) == 1:
data = [choices_list[0][0]]
return smart_text(data)
def contribute_to_class(self, cls, name, **kwargs):
# To support multiple relations to self, it's useful to have a non-None
# related name on symmetrical relations for internal reasons. The
# concept doesn't make a lot of sense externally ("you want me to
# specify *what* on my non-reversible relation?!"), so we set it up
# automatically. The funky name reduces the chance of an accidental
# clash.
if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name):
self.rel.related_name = "%s_rel_+" % name
super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs)
# The intermediate m2m model is not auto created if:
# 1) There is a manually specified intermediate, or
# 2) The class owning the m2m field is abstract.
# 3) The class owning the m2m field has been swapped out.
if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped:
self.rel.through = create_many_to_many_intermediary_model(self, cls)
# Add the descriptor for the m2m relation.
setattr(cls, self.name, ManyRelatedObjectsDescriptor(self.rel, reverse=False))
# Set up the accessor for the m2m table name for the relation.
self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)
# Populate some necessary rel arguments so that cross-app relations
# work correctly.
if not cls._meta.abstract and isinstance(self.rel.through, six.string_types):
def resolve_through_model(field, model, cls):
field.rel.through = model
add_lazy_relation(cls, self, self.rel.through, resolve_through_model)
def contribute_to_related_class(self, cls, related):
# Internal M2Ms (i.e., those with a related name ending with '+')
# and swapped models don't get a related descriptor.
if not self.rel.is_hidden() and not related.related_model._meta.swapped:
setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(self.rel, reverse=True))
# Set up the accessors for the column names on the m2m table.
self.m2m_column_name = curry(self._get_m2m_attr, related, 'column')
self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column')
self.m2m_field_name = curry(self._get_m2m_attr, related, 'name')
self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name')
get_m2m_rel = curry(self._get_m2m_attr, related, 'rel')
self.m2m_target_field_name = lambda: get_m2m_rel().field_name
get_m2m_reverse_rel = curry(self._get_m2m_reverse_attr, related, 'rel')
self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
def set_attributes_from_rel(self):
pass
def value_from_object(self, obj):
"""
Return the value of this field in the given model instance.
"""
return getattr(obj, self.attname).all()
def save_form_data(self, instance, data):
setattr(instance, self.attname, data)
def formfield(self, **kwargs):
db = kwargs.pop('using', None)
defaults = {
'form_class': forms.ModelMultipleChoiceField,
'queryset': self.rel.to._default_manager.using(db),
}
defaults.update(kwargs)
# If initial is passed in, it's a list of related objects, but the
# MultipleChoiceField takes a list of IDs.
if defaults.get('initial') is not None:
initial = defaults['initial']
if callable(initial):
initial = initial()
defaults['initial'] = [i._get_pk_val() for i in initial]
return super(ManyToManyField, self).formfield(**defaults)
def db_type(self, connection):
# A ManyToManyField is not represented by a single column,
# so return None.
return None
def db_parameters(self, connection):
return {"type": None, "check": None}
| bsd-3-clause |
dannyperry571/theapprentice | script.module.streamhub/default.py | 1 | 28411 | import base64,hashlib,os,random,re,requests,shutil,string,sys,urllib,urllib2,json,urlresolver,ssl
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,xbmcvfs
from addon.common.addon import Addon
from addon.common.net import Net
from resources import control
addon_id = 'script.module.streamhub'
selfAddon = xbmcaddon.Addon(id=addon_id)
addon = Addon(addon_id, sys.argv)
addon_name = selfAddon.getAddonInfo('name')
icon = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id , 'fanart.jpg'))
User_Agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
putlockerhd = 'http://putlockerhd.co'
ccurl = 'http://cartooncrazy.me'
s = requests.session()
net = Net()
ccurl = 'http://cartooncrazy.me'
xxxurl ='http://www.xvideos.com'
kidsurl = base64.b64decode ('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3NDbGFya2VJc0JhY2svU3RyZWFtSHViL21hc3Rlci9MaW5rcy9LaWRzL2tpZHNjb3JuZXIueG1s')
docurl = 'http://documentaryheaven.com'
mov2 = 'http://zmovies.to'
wwe = 'http://watchwrestling.in'
tv = base64.b64decode ('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3NDbGFya2VJc0JhY2svU3RyZWFtSHViL21hc3Rlci9MaW5rcy8yNDcvMjQ3dHYueG1s')
proxy = 'http://www.justproxy.co.uk/index.php?q='
def CAT():
addDir('MOVIES','url',100,icon,fanart,'')
addDir('MOVIES2','url',37,icon,fanart,'')
addDir('KIDS SECTION',kidsurl,16,icon,fanart,'')
addDir('XXX SECTION','URL',31,icon,fanart,'')
addDir('DOCS',docurl+'/watch-online/',35,icon,fanart,'')
addDir('24/7 TV',tv,48,icon,fanart,'')
def MovieCAT():
addDir('RECENT MOVIES',putlockerhd+'/recent_movies',19,icon,fanart,'')
addDir('COMEDY MOVIES',putlockerhd+'/comedy_movies',19,icon,fanart,'')
addDir('CRIME MOVIES',putlockerhd+'/crime_movies',19,icon,fanart,'')
addDir('WAR MOVIES',putlockerhd+'/war_movies',19,icon,fanart,'')
addDir('ROMANCE MOVIES',putlockerhd+'/romance_movies',19,icon,fanart,'')
addDir('MUSICAL MOVIES',putlockerhd+'/musical_movies',19,icon,fanart,'')
addDir('SPORT MOVIES',putlockerhd+'/sport_movies',19,icon,fanart,'')
addDir('KIDS MOVIES',putlockerhd+'/family_movies',19,icon,fanart,'')
addDir('DOCUMENTARY MOVIES',putlockerhd+'/documentary_movies',19,icon,fanart,'')
def MOV2CAT():
addDir('[COLOR red]R[/COLOR]ecently Added',mov2,38,icon,fanart,'')
addDir('[COLOR red]G[/COLOR]enres',mov2+'/genres/',41,icon,fanart,'')
addDir('[COLOR red]Y[/COLOR]ears',mov2+'/years/',41,icon,fanart,'')
addDir('[COLOR red]S[/COLOR]earch','url',40,icon,fanart,'')
def TVREQUESTCAT():
addDir('Everybody Loves Raymond','ELR',50,'http://www.gstatic.com/tv/thumb/tvbanners/184243/p184243_b_v8_ab.jpg','','')
addDir('How i Met Your Mother','HIMYM',50,'http://www.gstatic.com/tv/thumb/tvbanners/9916255/p9916255_b_v8_aa.jpg','','')
addDir('Naked And Afraid','NAA',50,'http://www.gstatic.com/tv/thumb/tvbanners/9974211/p9974211_b_v8_ad.jpg','','')
addDir('The Walking Dead','TWD',50,'http://www.gstatic.com/tv/thumb/tvbanners/13176393/p13176393_b_v8_ab.jpg','','')
addDir('[COLOR red][B]IF IT FAILS THE FIRST TIME CLICK IT AGAIN[/COLOR][/B]','url','','','','')
def xxxCAT():
addDir("[COLOR orange]G[/COLOR][COLOR white]enre's[/COLOR]",xxxurl+'/a',99,icon,fanart,'')
def regex_from_to(text, from_string, to_string, excluding=True):
if excluding:
try: r = re.search("(?i)" + from_string + "([\S\s]+?)" + to_string, text).group(1)
except: r = ''
else:
try: r = re.search("(?i)(" + from_string + "[\S\s]+?" + to_string + ")", text).group(1)
except: r = ''
return r
def regex_get_all(text, start_with, end_with):
r = re.findall("(?i)(" + start_with + "[\S\s]+?" + end_with + ")", text)
return r
def get_params():
param=[]
paramstring=sys.argv[2]
if len(paramstring)>=2:
params=sys.argv[2]
cleanedparams=params.replace('?','')
if (params[len(params)-1]=='/'):
params=params[0:len(params)-2]
pairsofparams=cleanedparams.split('&')
param={}
for i in range(len(pairsofparams)):
splitparams={}
splitparams=pairsofparams[i].split('=')
if (len(splitparams))==2:
param[splitparams[0]]=splitparams[1]
return param
def addDir(name,url,mode,iconimage,fanart,description):
u=sys.argv[0]+"?url="+url+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={"Title": name,"Plot":description})
liz.setProperty('fanart_image', fanart)
if mode==3 or mode==7 or mode==17 or mode==15 or mode==23 or mode==30 or mode==27 or mode ==36 or mode==39 or mode==50:
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
xbmcplugin.endOfDirectory
def addDirPlay(name,url,mode,iconimage,fanart,description):
u=sys.argv[0]+"?url="+url+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
if mode==44:
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
xbmcplugin.endOfDirectory
def OPEN_URL(url):
headers = {}
headers['User-Agent'] = User_Agent
link = s.get(url, headers=headers, verify=False).text
link = link.encode('ascii', 'ignore')
return link
def tvlist(url):
thumb = ''
art = ''
OPEN = Open_Url(url)
Regex = re.compile('<title>(.+?)</title>.+?url>(.+?)</url>.+?thumb>(.+?)</thumb>',re.DOTALL).findall(OPEN)
addDir('[COLOR red][B]Requested 24/7 Shows[/B][/COLOR]','url',49,'','','')
for name,url,icon in Regex:
addDir(name,url,46,icon,fanart,'')
def toonlist(url):
OPEN = Open_Url(url)
Regex = re.compile('<title>(.+?)</title>.+?url>(.+?)</url>.+?thumb>(.+?)</thumb>.+?art>(.+?)</art>',re.DOTALL).findall(OPEN)
for name,url,icon,fanart in Regex:
addDir(name,url,18,icon,fanart,'')
def toon_get(url):
OPEN = Open_Url(url)
Regex = re.compile(' <a href="(.+?)">(.+?)</a>',re.DOTALL).findall(OPEN)
for url,name in Regex:
name = name.replace('’','')
addDir(name,url,17,iconimage,fanart,'')
np = re.compile('<a href="(.+?)">(.+?)</a>',re.DOTALL).findall(OPEN)
for url,name in np:
if 'Next' in name:
addDir('[B][COLOR red]More >[/COLOR][/B]',url,2,iconimage,fanart,'')
xbmc.executebuiltin('Container.SetViewMode(50)')
xbmcplugin.endOfDirectory
def resolvetoons(name,url,iconimage,description):
OPEN = Open_Url(url)
url1=regex_from_to(OPEN,'Playlist 1</span></div><div><iframe src="','"')
url2=regex_from_to(OPEN,'Playlist 2</span></div><div><iframe src="','"')
url3=regex_from_to(OPEN,'Playlist 3</span></div><div><iframe src="','"')
url4=regex_from_to(OPEN,'Playlist 4</span></div><div><iframe src="','"')
try:
play=urlresolver.HostedMediaFile(url1).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
except:pass
try:
play=urlresolver.HostedMediaFile(url2).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
except:pass
try:
play=urlresolver.HostedMediaFile(url3).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
except:pass
try:
play=urlresolver.HostedMediaFile(url4).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
except:pass
def Open_Url(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
link=response.read()
response.close()
return link
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def OPEN_URLputlockerhd(url):
headers = {}
headers['User-Agent'] = User_Agent
link = requests.get(url, headers=headers, allow_redirects=False).text
link = link.encode('ascii', 'ignore').decode('ascii')
return link
def addDirputlockerhd(name,url,mode,iconimage,fanart,description):
u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name,"Plot":description} )
liz.setProperty('fanart_image', fanart)
if mode==3 or mode ==15:
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
def putlockerhdread(url):
url = url.replace('https','http')
link = OPEN_URLputlockerhd(url)
all_videos = regex_get_all(link, 'cell_container', '<div><b>')
items = len(all_videos)
for a in all_videos:
name = regex_from_to(a, 'a title="', '\(')
name = addon.unescape(name)
url = regex_from_to(a, 'href="', '"').replace("&","&")
thumb = regex_from_to(a, 'src="', '"')
addDirputlockerhd(name,putlockerhd+url,15,'http://'+thumb,fanart,'')
try:
match = re.compile('<a href="(.*?)\?page\=(.*?)">').findall(link)
for url, pn in match:
url = putlockerhd+url+'?page='+pn
addDir('[I][B][COLOR red]Page %s [/COLOR][/B][/I]' %pn,url,19,icon,fanart,'')
except: pass
def putlockerhdplay(url):
try:
url = re.split(r'#', url, re.I)[0]
request_url = putlockerhd+'/video_info/iframe'
link = OPEN_URLputlockerhd(url)
form_data={'v': re.search(r'v\=(.*?)$',url,re.I).group(1)}
headers = {'origin':'http://putlockerhd.co', 'referer': url,
'user-agent':User_Agent,'x-requested-with':'XMLHttpRequest'}
r = requests.post(request_url, data=form_data, headers=headers, allow_redirects=False)
try:
url = re.findall(r'url\=(.*?)"', str(r.text), re.I|re.DOTALL)[-1]
except:
url = re.findall(r'url\=(.*?)"', str(r.text), re.I|re.DOTALL)[0]
url = url.replace("&","&").replace('%3A',':').replace('%3D','=').replace('%2F','/')
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title':description})
liz.setProperty("IsPlayable","true")
liz.setPath(str(url))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
except:pass
def xxx(url):
link = OPEN_URL(url)
xxxadd_next_button(link)
all_videos = regex_get_all(link, 'class="thumb-block ">', '</a></p>')
for a in all_videos:
name = regex_from_to(a, 'title="', '"')
name = str(name).replace("&","&").replace(''',"'").replace('"','"').replace(''',"'").replace(''',"'")
url = regex_from_to(a, 'href="', '"').replace("&","&")
thumb = regex_from_to(a, '<img src="', '"')
addDir(name,'http://www.xvideos.com'+url,27,thumb,'','')
def xxxadd_next_button(link):
try:
if '/tags/' in link:
link = str(link).replace('\n','').replace('\r','').replace('\t','').replace(' ','').replace(' ','')
nextp=regex_from_to(link,'<aclass="active"href="">.+?</a></li><li><ahref="','"')
addDir('[B][COLOR red]Next Page>>>[/COLOR][/B]',xxxurl+nextp,24,'','','')
except: pass
try:
if '/tags/' not in link:
link = str(link).replace('\n','').replace('\r','').replace('\t','').replace(' ','').replace(' ','')
nextp = regex_from_to(link,'<aclass="active"href="">.+?</a></li><li><ahref="','"')
xbmc.log(str(nextp))
addDir('[B][COLOR red]Next Page[/COLOR][/B]',xxxurl+nextp,24,'','','')
except: pass
return
def xxxgenre(url):
link = passpopup(url)
link = OPEN_URL(link)
main = regex_from_to(link,'<strong>All tags</strong>','mobile-hide')
all_videos = regex_get_all(main, '<li>', '</li>')
for a in all_videos:
name = regex_from_to(a, '"><b>', '</b><span').replace("&","&")
url = regex_from_to(a, 'href="', '"').replace("&","&")
url = url+'/'
thumb = regex_from_to(a, 'navbadge default">', '<')
addDir('%s [B][COLOR red](%s Videos)[/COLOR][/B]' %(name,thumb),xxxurl+url,24,'','','')
def resolvexxx(url):
base = 'http://www.xvideos.com'
page = OPEN_URL(url)
page=urllib.unquote(page.encode("utf8"))
page=str(page).replace('\t','').replace('\n','').replace('\r','').replace(' ','')
play = regex_from_to(page,"setVideoUrlHigh.+?'","'")
url = str(play).replace('[','').replace("'","").replace(']','')
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=icon)
liz.setInfo(type='Video', infoLabels={'Title':description})
liz.setProperty("IsPlayable","true")
liz.setPath(str(url))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def passpopup(url):
kb =xbmc.Keyboard ('', 'heading', True)
kb.setHeading('Enter 18+ Password') # optional
kb.setHiddenInput(True) # optional
kb.doModal()
if (kb.isConfirmed()):
text = kb.getText()
if 'saucy' in text:
text = str(text).replace('saucy','/tags')
return (str(xxxurl+text)).replace('%3a','').replace('%2f','')
else:
Msg=" Incorrect Password\n\n Password is available from\n [COLOR red]http://facebook.com/groups/streamhub[/COLOR]"
dialog = xbmcgui.Dialog()
ok = dialog.ok('Attention', Msg)
return False
'''def resolvecartooncrazy(url,icon):
bypass = cloudflare.create_scraper()
u = bypass.get(url).content
embed = re.compile('<iframe src="(.+?)"').findall(u)
embed = str(embed).replace("', '/300.html', '/300.html']","").replace('[','').replace("'","")
get = OPEN_URL(embed)
regex = re.compile('<iframe src=(.+?)"').findall(get)
regex = str(regex).replace('[','').replace('"','').replace(']','').replace("'","")
geturl = OPEN_URL(regex)
stream = re.compile('file: "(.+?)"').findall(geturl)
stream = str(stream).replace('[','').replace('"','').replace(']','').replace("'","")
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=icon)
liz.setInfo(type='Video', infoLabels={"Title": name})
liz.setProperty("IsPlayable","true")
liz.setPath(url)
xbmc.Player().play(stream,liz)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def opencartooncrazy(url):
bypass = cloudflare.create_scraper()
u = bypass.get(url).content
regex = regex_from_to(u,'data-id="','"')
url = ccurl+'/ep.php?id='+regex
#link = regex_from_to(u,'<img src="','"')
openurl = bypass.get(url).content
all_videos = regex_get_all(openurl, '<tr>', '</tr>')
for a in all_videos:
name = regex_from_to(a, '<h2>', '</h2>')
name = str(name).replace("&","&").replace(''',"'").replace('"','"').replace(''',"'").replace('–',' - ').replace('’',"'").replace('‘',"'").replace('&','&').replace('â','')
url = regex_from_to(a, 'href="', '"')
addDir(name,ccurl+url,30,'','','')
def CartooncrazyList():
OPEN = Open_Url('http://mkodi.co.uk/streamhub/lists/cartooncrazy.xml')
Regex = re.compile('<title>(.+?)</title>.+?url>(.+?)</url>.+?thumb>(.+?)</thumb>',re.DOTALL).findall(OPEN)
for name,url,icon in Regex:
fanart='http://'
addDir(name,url,34,icon,fanart,'')
xbmc.executebuiltin('Container.SetViewMode(50)')
def CartooncrazysubList(url):
OPEN = Open_Url(url)
Regex = re.compile('<title>(.+?)</title>.+?url>(.+?)</url>.+?thumb>(.+?)</thumb>',re.DOTALL).findall(OPEN)
for name,url,icon in Regex:
fanart='http://'
addDir(name,url,26,icon,fanart,'')
xbmc.executebuiltin('Container.SetViewMode(50)')'''
def documentary(url):
addDir('DOCUMENTARY MOVIES',putlockerhd+'/documentary_movies',19,icon,fanart,'')
OPEN = OPEN_URL(url)
regex = regex_get_all(OPEN,'<h2><a href','alt="')
for a in regex:
url = regex_from_to(a,'="','"')
title = regex_from_to(a,'">','<').replace("&","&").replace(''',"'").replace('"','"').replace(''',"'").replace('–',' - ').replace('’',"'").replace('‘',"'").replace('&','&').replace('â','')
thumb = regex_from_to(a,'img src="','"')
vids = regex_from_to(a,'</a> (',')</h2>').replace('(','').replace(')','')
if vids == "":
addDir(title,url,36,thumb,fanart,'')
else:
addDir(title,docurl+url,35,thumb,fanart,'')
try:
link = re.compile('<li class="next-btn"><a href="(.+?)"').findall(OPEN)
link = str(link).replace('[','').replace(']','').replace("'","")
xbmc.log(str(link))
if link == "":
return False
else:
addDir('[B][COLOR red]NEXT PAGE[/COLOR][/B]',link,35,thumb,fanart,'')
except:pass
def resolvedoc(url):
open = OPEN_URL(url)
xbmc.log(str(open))
url = regex_from_to(open,'height=".*?" src="','"')
link = urlresolver.HostedMediaFile(url).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(link))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
'''def openmov2(url):
link = OPEN_URL(url)
link = link.encode('ascii', 'ignore').decode('ascii')
nexp=regex_from_to(link,'<link rel="next" href="','"')
if nexp=="":
nexp = 'none'
else:
addDir('[COLOR red]NEXT PAGE[/COLOR]',nexp,38,'','','')
all_videos = regex_get_all(link, '<div class="featured-thumbnail">', '</header>')
for a in all_videos:
icon = regex_from_to(a, 'src="', '"').replace("&","&").replace(''',"'").replace('"','"').replace(''',"'")
url = regex_from_to(a, ' <a href="', '" title=.+?').replace("&","&")
name = regex_from_to(a, 'rel="bookmark">', '<').replace('’',"'")
addDir(name,url,39,icon,fanart,'')
def SEARCHmov2(type):
keyb = xbmc.Keyboard('', 'Type in Query')
keyb.doModal()
if (keyb.isConfirmed()):
search = keyb.getText().replace(' ','+')
if search == '':
xbmc.executebuiltin("XBMC.Notification([COLOR gold][B]EMPTY QUERY[/B][/COLOR],Aborting search,7000,"+icon+")")
return
else: pass
url = mov2+'/?s='+search
print url
openmov2(url)
def GENREmov2(url):
link = OPEN_URL(url)
link = link.encode('ascii', 'ignore')
match=regex_get_all(link,'<button type="button">','</button>')
xbmc.log(str(match))
for a in match:
link = regex_from_to(a,'href="','"').replace('https','http')
name = regex_from_to(a,'target="_blank">','<')
xbmc.log(str(link))
xbmc.log(str(name))
addDir(name,link,38,icon,fanart,'')
def playmov2(url):
link = OPEN_URL(url)
referer = url
vid = re.compile('link: "(.*?)"').findall(link)[0]
url2 = 'http://zmovies.to/wp-content/themes/magxp/phim/getlink.php?poster=&link='+vid
page = OPEN_URL(url2)
xbmc.log(str(page))
if '720p' in page:
play = re.compile(',{"file":"(.*?)","type":"mp4","label":"720p"').findall(page)[0]
pla2 = str(play).replace('\/','/').replace("[",'').replace(':"','').replace("'","").replace(']','').replace('":','')
play3 = str(pla2).replace('\\','').replace('//','/').replace('https:/','https://')
play4 =urlresolver.HostedMediaFile(play3).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=icon)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play4))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
if 'openload' in page:
url = regex_from_to(page,'<iframe src="','"')
play=urlresolver.HostedMediaFile(url).resolve()
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=icon)
liz.setInfo(type='Video', infoLabels={'Title': name, 'Plot': description})
liz.setProperty('IsPlayable','true')
liz.setPath(str(play))
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
else:
all_links = regex_get_all(page,'"file"','}')
url = regex_from_to(page,':"','"')
url = str(url).replace('\/','/').replace("[",'').replace(':"','').replace("'","").replace(']','').replace('":','')
url = str(url).replace('\\','').replace('//','/').replace('https:/','https://')
xbmc.log('******************')
xbmc.log(str(url))
qual = regex_from_to(page,'"label":"','"')
addDir(qual,url,39,icon,fanart,'')'''
def opentwentyfourseven(url):
page = proxy+url
m3ubase= 'plugin://plugin.video.f4mTester/?streamtype=HLS&url='
m3ubase2= '&name='
all_vids=re.compile('<li id="menu-item-(.*?)</div> </div></div>').findall(page)
xbmc.log(str(all_vids))
for a in all_vids:
url = regex_from_to(a,'<a href="','"')
name = regex_from_to(a,'<span class="link_text">\n','\n')
xbmc.log(str(url))
xbmc.log(str(name))
def resolvetwentyfourseven(url,icon):
m3ubase= 'plugin://plugin.video.f4mTester/?streamtype=HLS&url='
name='24/7'
m3ubase2= '&icon='+icon+'&name='+name
xbmc.log(str(proxy)+str(url))
open = OPEN_URL(proxy+url)
m3u = re.compile('<source.*?src="(.*?)"',re.DOTALL).findall(open)[0]
play = m3ubase+m3u+m3ubase2
liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=icon)
xbmc.Player().play(play,liz)
tvlist(tv)
def home():
home = xbmc.executebuiltin('XBMC.RunAddon(plugin://plugin.video.streamhub/?action=)')
return home
#get = OPEN_URL(cartoons)
#xbmc.log(str(get))
def TVREQUESTCATPLAY(name,url,icon):
if 'TWD' in url:
play='plugin://plugin.video.streamhub/?action=tvtuner&url=<preset>tvtuner</preset><url>http://opentuner.is/the-walking-dead-2010/</url><thumbnail>https://fanart.tv/fanart/tv/153021/clearart/TheWalkingDead-153021-5.png</thumbnail><fanart>0</fanart><content>tvtuner</content><imdb>tt1520211</imdb><tvdb>153021</tvdb><tvshowtitle>The+Walking+Dead</tvshowtitle><year>2010</year>&content=tvtuners'
elif 'ELR' in url:
play='plugin://plugin.video.streamhub/?action=tvtuner&url=<preset>tvtuner</preset><url>http://opentuner.is/everybody-loves-raymond-1996/</url><thumbnail>http://www.gstatic.com/tv/thumb/tvbanners/184243/p184243_b_v8_ab.jpg</thumbnail><fanart>0</fanart><content>tvtuner</content><imdb>tt0115167</imdb><tvdb>73663</tvdb><tvshowtitle>Everybody+Loves+Raymond</tvshowtitle><year>1996</year>&content=tvtuners'
elif 'NAA' in url:
play='plugin://plugin.video.streamhub/?action=tvtuner&url=<preset>tvtuner</preset><url>http://opentuner.is/naked-and-afraid-2013/</url><thumbnail>http://www.gstatic.com/tv/thumb/tvbanners/9974211/p9974211_b_v8_ad.jpg</thumbnail><fanart>0</fanart><content>tvtuner</content><imdb>tt3007640</imdb><tvdb>270693</tvdb><tvshowtitle>Naked+And+Afraid</tvshowtitle><year>2013</year>&content=tvtuners'
elif 'HIMYM' in url:
play='plugin://plugin.video.streamhub/?action=tvtuner&url=<preset>tvtuner</preset><url>http://opentuner.is/how-i-met-your-mother-2005/</url><thumbnail>http://www.gstatic.com/tv/thumb/tvbanners/9916255/p9916255_b_v8_aa.jpg</thumbnail><fanart>0</fanart><content>tvtuner</content><imdb>tt0460649</imdb><tvdb>75760</tvdb><tvshowtitle>How+I+Met+Your+Mother</tvshowtitle><year>2005</year>&content=tvtuners'
xbmc.executebuiltin('XBMC.RunPlugin('+play+')')
def replacemalicious():
target = xbmc.translatePath('special://home/addons/plugin.video.exodus/resources/lib/modules/sources.py')
home = xbmc.translatePath('special://home/addons/script.module.streamhub/resources/')
if os.path.exists(target):
file = open(os.path.join(home, 'exodusclean.py'))
data = file.read()
file.close()
file = open(target,"w")
file.write(data)
file.close()
if xbmc.getCondVisibility('System.HasAddon(plugin.video.exodus'):
try:
targetfolder = xbmc.translatePath('special://home/addons/plugin.video.exodus/resources/lib/modules/')
targetfile = open(os.path.join(targetfolder, 'sources.py'))
targetread = targetfile.read()
targetclose = targetfile.close()
if 'mkodi' in targetread:
replacemalicious()
except:
pass
params=get_params()
url=None
name=None
mode=None
iconimage=None
description=None
query=None
type=None
# OpenELEQ: query & type-parameter (added 2 lines above)
try:
url=urllib.unquote_plus(params["url"])
except:
pass
try:
name=urllib.unquote_plus(params["name"])
except:
pass
try:
iconimage=urllib.unquote_plus(params["iconimage"])
except:
pass
try:
mode=int(params["mode"])
except:
pass
try:
description=urllib.unquote_plus(params["description"])
except:
pass
try:
query=urllib.unquote_plus(params["query"])
except:
pass
try:
type=urllib.unquote_plus(params["type"])
except:
pass
# OpenELEQ: query & type-parameter (added 8 lines above)
if mode==None or url==None or len(url)<1:
CAT()
elif mode==2:
INDEX2(url)
elif mode==3:
LINKS(url)
elif mode==4:
TV()
elif mode==6:
EPIS(url)
elif mode==7:
LINKS2(url,description)
elif mode==8:
SEARCH(query,type)
# OpenELEQ: query & type-parameter (added to line above)
elif mode==9:
GENRE(url)
elif mode==10:
COUNTRY(url)
elif mode==11:
YEAR(url)
elif mode==12:
INDEX3(url)
elif mode==13:
resolve(name,url,iconimage,description)
elif mode==19:
putlockerhdread(url)
elif mode==15:
putlockerhdplay(url)
elif mode==16:
toonlist(url)
elif mode==17:
resolvetoons(name,url,iconimage,description)
elif mode==18:
toon_get(url)
elif mode==24:
xxx(url)
elif mode==25:
LiveTV()
elif mode==26:
opencartooncrazy(url)
elif mode==27:
resolvexxx(url)
elif mode==99:
xxxgenre(url)
elif mode==30:
resolvecartooncrazy(url,icon)
elif mode==31:
xxxCAT()
elif mode==32:
CartooncrazyList()
elif mode==33:
listgenre(url)
elif mode==34:
CartooncrazysubList(url)
elif mode==35:
documentary(url)
elif mode==36:
resolvedoc(url)
elif mode==43:
wweopen(url)
elif mode==44:
playwwe(url,description)
elif mode==45:
wwepages(url)
elif mode==46:
resolvetwentyfourseven(url,icon)
elif mode==47:
opentwentyfourseven(url)
elif mode==48:
tvlist(url)
elif mode==49:
TVREQUESTCAT()
elif mode==50:
TVREQUESTCATPLAY(name,url,icon)
elif mode==98:
xxxstars(url)
elif mode==100:
MovieCAT()
elif mode==999:
home()
xbmcplugin.endOfDirectory(int(sys.argv[1])) | gpl-2.0 |
Sarah-Alsinan/muypicky | lib/python3.6/site-packages/pip/_vendor/requests/packages/chardet/langhebrewmodel.py | 2763 | 11318 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Simon Montagu
# Portions created by the Initial Developer are Copyright (C) 2005
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
# Shoshannah Forbes - original C code (?)
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
# 255: Control characters that usually does not exist in any text
# 254: Carriage/Return
# 253: symbol (punctuation) that does not belong to word
# 252: 0 - 9
# Windows-1255 language model
# Character Mapping Table:
win1255_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253, 69, 91, 79, 80, 92, 89, 97, 90, 68,111,112, 82, 73, 95, 85, # 40
78,121, 86, 71, 67,102,107, 84,114,103,115,253,253,253,253,253, # 50
253, 50, 74, 60, 61, 42, 76, 70, 64, 53,105, 93, 56, 65, 54, 49, # 60
66,110, 51, 43, 44, 63, 81, 77, 98, 75,108,253,253,253,253,253, # 70
124,202,203,204,205, 40, 58,206,207,208,209,210,211,212,213,214,
215, 83, 52, 47, 46, 72, 32, 94,216,113,217,109,218,219,220,221,
34,116,222,118,100,223,224,117,119,104,125,225,226, 87, 99,227,
106,122,123,228, 55,229,230,101,231,232,120,233, 48, 39, 57,234,
30, 59, 41, 88, 33, 37, 36, 31, 29, 35,235, 62, 28,236,126,237,
238, 38, 45,239,240,241,242,243,127,244,245,246,247,248,249,250,
9, 8, 20, 16, 3, 2, 24, 14, 22, 1, 25, 15, 4, 11, 6, 23,
12, 19, 13, 26, 18, 27, 21, 17, 7, 10, 5,251,252,128, 96,253,
)
# Model Table:
# total sequences: 100%
# first 512 sequences: 98.4004%
# first 1024 sequences: 1.5981%
# rest sequences: 0.087%
# negative sequences: 0.0015%
HebrewLangModel = (
0,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,2,1,2,0,1,0,0,
3,0,3,1,0,0,1,3,2,0,1,1,2,0,2,2,2,1,1,1,1,2,1,1,1,2,0,0,2,2,0,1,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,
1,2,1,2,1,2,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,
1,2,1,3,1,1,0,0,2,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,1,2,2,1,3,
1,2,1,1,2,2,0,0,2,2,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,2,3,2,
1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,2,2,1,2,2,2,2,
1,2,1,1,2,2,0,1,2,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,2,2,2,2,2,
0,2,0,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,2,2,
0,2,1,2,2,2,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,2,2,
1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,
3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,2,0,2,
0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,1,2,1,1,1,
0,1,1,1,1,1,3,0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,
0,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,
0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,2,3,3,3,2,1,2,3,3,2,3,3,3,3,2,3,2,1,2,0,2,1,2,
0,2,0,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,
3,3,3,3,3,3,3,3,3,2,3,3,3,1,2,2,3,3,2,3,2,3,2,2,3,1,2,2,0,2,2,2,
0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,2,2,3,3,3,3,1,3,2,2,2,
0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,2,3,2,2,2,1,2,2,0,2,2,2,2,
0,2,0,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,1,3,2,3,3,2,3,3,2,2,1,2,2,2,2,2,2,
0,2,1,2,1,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,3,2,3,3,3,3,3,2,2,2,2,2,2,2,1,
0,2,0,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,3,3,3,2,1,2,3,3,3,3,3,3,3,2,3,2,3,2,1,2,3,0,2,1,2,2,
0,2,1,1,2,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,2,0,
3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,1,3,1,2,2,2,1,2,3,3,1,2,1,2,2,2,2,
0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,1,3,3,3,1,2,2,2,2,1,1,2,2,2,2,2,2,
0,2,0,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,1,2,3,2,3,2,2,2,2,1,2,1,1,1,2,2,
0,2,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0,
1,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,2,3,3,2,3,1,2,2,2,2,3,2,3,1,1,2,2,1,2,2,1,1,0,2,2,2,2,
0,1,0,1,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
3,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0,
0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
3,2,2,1,2,2,2,2,2,2,2,1,2,2,1,2,2,1,1,1,1,1,1,1,1,2,1,1,0,3,3,3,
0,3,0,2,2,2,2,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2,2,2,1,1,1,2,0,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,0,0,0,0,
0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,0,2,1,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
0,3,1,1,2,2,2,2,2,1,2,2,2,1,1,2,2,2,2,2,2,2,1,2,2,1,0,1,1,1,1,0,
0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,1,1,1,1,2,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,
0,0,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0,
2,1,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2,1,2,1,1,1,1,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,1,2,1,1,1,2,1,2,1,2,0,1,0,1,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,2,1,2,1,1,0,1,0,1,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,
0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,2,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,0,
0,1,1,1,2,1,2,2,2,0,2,0,2,0,1,1,2,1,1,1,1,2,1,0,1,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,1,0,0,0,0,0,1,0,1,2,2,0,1,0,0,1,1,2,2,1,2,0,2,0,0,0,1,2,0,1,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,2,0,2,1,2,0,2,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,1,2,2,0,0,1,0,0,0,1,0,0,1,
1,1,2,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,2,1,
0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,
2,0,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,2,1,1,2,0,1,0,0,0,1,1,0,1,
1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,0,0,2,1,1,2,0,2,0,0,0,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,2,2,1,2,1,1,0,1,0,0,0,1,1,0,1,
2,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,2,1,1,1,0,2,1,1,0,0,0,2,1,0,1,
1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,0,2,1,1,0,1,0,0,0,1,1,0,1,
2,2,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,0,1,2,1,0,2,0,0,0,1,1,0,1,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
0,1,0,0,2,0,2,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1,
1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,2,1,1,1,1,1,0,1,0,0,0,0,1,0,1,
0,1,1,1,2,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,0,
)
Win1255HebrewModel = {
'charToOrderMap': win1255_CharToOrderMap,
'precedenceMatrix': HebrewLangModel,
'mTypicalPositiveRatio': 0.984004,
'keepEnglishLetter': False,
'charsetName': "windows-1255"
}
# flake8: noqa
| mit |
aminert/scikit-learn | benchmarks/bench_plot_neighbors.py | 287 | 6433 | """
Plot the scaling of the nearest neighbors algorithms with k, D, and N
"""
from time import time
import numpy as np
import pylab as pl
from matplotlib import ticker
from sklearn import neighbors, datasets
def get_data(N, D, dataset='dense'):
if dataset == 'dense':
np.random.seed(0)
return np.random.random((N, D))
elif dataset == 'digits':
X = datasets.load_digits().data
i = np.argsort(X[0])[::-1]
X = X[:, i]
return X[:N, :D]
else:
raise ValueError("invalid dataset: %s" % dataset)
def barplot_neighbors(Nrange=2 ** np.arange(1, 11),
Drange=2 ** np.arange(7),
krange=2 ** np.arange(10),
N=1000,
D=64,
k=5,
leaf_size=30,
dataset='digits'):
algorithms = ('kd_tree', 'brute', 'ball_tree')
fiducial_values = {'N': N,
'D': D,
'k': k}
#------------------------------------------------------------
# varying N
N_results_build = dict([(alg, np.zeros(len(Nrange)))
for alg in algorithms])
N_results_query = dict([(alg, np.zeros(len(Nrange)))
for alg in algorithms])
for i, NN in enumerate(Nrange):
print("N = %i (%i out of %i)" % (NN, i + 1, len(Nrange)))
X = get_data(NN, D, dataset)
for algorithm in algorithms:
nbrs = neighbors.NearestNeighbors(n_neighbors=min(NN, k),
algorithm=algorithm,
leaf_size=leaf_size)
t0 = time()
nbrs.fit(X)
t1 = time()
nbrs.kneighbors(X)
t2 = time()
N_results_build[algorithm][i] = (t1 - t0)
N_results_query[algorithm][i] = (t2 - t1)
#------------------------------------------------------------
# varying D
D_results_build = dict([(alg, np.zeros(len(Drange)))
for alg in algorithms])
D_results_query = dict([(alg, np.zeros(len(Drange)))
for alg in algorithms])
for i, DD in enumerate(Drange):
print("D = %i (%i out of %i)" % (DD, i + 1, len(Drange)))
X = get_data(N, DD, dataset)
for algorithm in algorithms:
nbrs = neighbors.NearestNeighbors(n_neighbors=k,
algorithm=algorithm,
leaf_size=leaf_size)
t0 = time()
nbrs.fit(X)
t1 = time()
nbrs.kneighbors(X)
t2 = time()
D_results_build[algorithm][i] = (t1 - t0)
D_results_query[algorithm][i] = (t2 - t1)
#------------------------------------------------------------
# varying k
k_results_build = dict([(alg, np.zeros(len(krange)))
for alg in algorithms])
k_results_query = dict([(alg, np.zeros(len(krange)))
for alg in algorithms])
X = get_data(N, DD, dataset)
for i, kk in enumerate(krange):
print("k = %i (%i out of %i)" % (kk, i + 1, len(krange)))
for algorithm in algorithms:
nbrs = neighbors.NearestNeighbors(n_neighbors=kk,
algorithm=algorithm,
leaf_size=leaf_size)
t0 = time()
nbrs.fit(X)
t1 = time()
nbrs.kneighbors(X)
t2 = time()
k_results_build[algorithm][i] = (t1 - t0)
k_results_query[algorithm][i] = (t2 - t1)
pl.figure(figsize=(8, 11))
for (sbplt, vals, quantity,
build_time, query_time) in [(311, Nrange, 'N',
N_results_build,
N_results_query),
(312, Drange, 'D',
D_results_build,
D_results_query),
(313, krange, 'k',
k_results_build,
k_results_query)]:
ax = pl.subplot(sbplt, yscale='log')
pl.grid(True)
tick_vals = []
tick_labels = []
bottom = 10 ** np.min([min(np.floor(np.log10(build_time[alg])))
for alg in algorithms])
for i, alg in enumerate(algorithms):
xvals = 0.1 + i * (1 + len(vals)) + np.arange(len(vals))
width = 0.8
c_bar = pl.bar(xvals, build_time[alg] - bottom,
width, bottom, color='r')
q_bar = pl.bar(xvals, query_time[alg],
width, build_time[alg], color='b')
tick_vals += list(xvals + 0.5 * width)
tick_labels += ['%i' % val for val in vals]
pl.text((i + 0.02) / len(algorithms), 0.98, alg,
transform=ax.transAxes,
ha='left',
va='top',
bbox=dict(facecolor='w', edgecolor='w', alpha=0.5))
pl.ylabel('Time (s)')
ax.xaxis.set_major_locator(ticker.FixedLocator(tick_vals))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(tick_labels))
for label in ax.get_xticklabels():
label.set_rotation(-90)
label.set_fontsize(10)
title_string = 'Varying %s' % quantity
descr_string = ''
for s in 'NDk':
if s == quantity:
pass
else:
descr_string += '%s = %i, ' % (s, fiducial_values[s])
descr_string = descr_string[:-2]
pl.text(1.01, 0.5, title_string,
transform=ax.transAxes, rotation=-90,
ha='left', va='center', fontsize=20)
pl.text(0.99, 0.5, descr_string,
transform=ax.transAxes, rotation=-90,
ha='right', va='center')
pl.gcf().suptitle("%s data set" % dataset.capitalize(), fontsize=16)
pl.figlegend((c_bar, q_bar), ('construction', 'N-point query'),
'upper right')
if __name__ == '__main__':
barplot_neighbors(dataset='digits')
barplot_neighbors(dataset='dense')
pl.show()
| bsd-3-clause |
zsiciarz/django | django/apps/registry.py | 17 | 17223 | import functools
import sys
import threading
import warnings
from collections import Counter, OrderedDict, defaultdict
from functools import partial
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
from .config import AppConfig
class Apps:
"""
A registry that stores the configuration of installed applications.
It also keeps track of models, e.g. to provide reverse relations.
"""
def __init__(self, installed_apps=()):
# installed_apps is set to None when creating the master registry
# because it cannot be populated at that point. Other registries must
# provide a list of installed apps and are populated immediately.
if installed_apps is None and hasattr(sys.modules[__name__], 'apps'):
raise RuntimeError("You must supply an installed_apps argument.")
# Mapping of app labels => model names => model classes. Every time a
# model is imported, ModelBase.__new__ calls apps.register_model which
# creates an entry in all_models. All imported models are registered,
# regardless of whether they're defined in an installed application
# and whether the registry has been populated. Since it isn't possible
# to reimport a module safely (it could reexecute initialization code)
# all_models is never overridden or reset.
self.all_models = defaultdict(OrderedDict)
# Mapping of labels to AppConfig instances for installed apps.
self.app_configs = OrderedDict()
# Stack of app_configs. Used to store the current state in
# set_available_apps and set_installed_apps.
self.stored_app_configs = []
# Whether the registry is populated.
self.apps_ready = self.models_ready = self.ready = False
# Lock for thread-safe population.
self._lock = threading.RLock()
self.loading = False
# Maps ("app_label", "modelname") tuples to lists of functions to be
# called when the corresponding model is ready. Used by this class's
# `lazy_model_operation()` and `do_pending_operations()` methods.
self._pending_operations = defaultdict(list)
# Populate apps and models, unless it's the master registry.
if installed_apps is not None:
self.populate(installed_apps)
def populate(self, installed_apps=None):
"""
Load application configurations and models.
Import each application module and then each model module.
It is thread-safe and idempotent, but not reentrant.
"""
if self.ready:
return
# populate() might be called by two threads in parallel on servers
# that create threads before initializing the WSGI callable.
with self._lock:
if self.ready:
return
# An RLock prevents other threads from entering this section. The
# compare and set operation below is atomic.
if self.loading:
# Prevent reentrant calls to avoid running AppConfig.ready()
# methods twice.
raise RuntimeError("populate() isn't reentrant")
self.loading = True
# Phase 1: initialize app configs and import app modules.
for entry in installed_apps:
if isinstance(entry, AppConfig):
app_config = entry
else:
app_config = AppConfig.create(entry)
if app_config.label in self.app_configs:
raise ImproperlyConfigured(
"Application labels aren't unique, "
"duplicates: %s" % app_config.label)
self.app_configs[app_config.label] = app_config
app_config.apps = self
# Check for duplicate app names.
counts = Counter(
app_config.name for app_config in self.app_configs.values())
duplicates = [
name for name, count in counts.most_common() if count > 1]
if duplicates:
raise ImproperlyConfigured(
"Application names aren't unique, "
"duplicates: %s" % ", ".join(duplicates))
self.apps_ready = True
# Phase 2: import models modules.
for app_config in self.app_configs.values():
app_config.import_models()
self.clear_cache()
self.models_ready = True
# Phase 3: run ready() methods of app configs.
for app_config in self.get_app_configs():
app_config.ready()
self.ready = True
def check_apps_ready(self):
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
raise AppRegistryNotReady("Apps aren't loaded yet.")
def check_models_ready(self):
"""Raise an exception if all models haven't been imported yet."""
if not self.models_ready:
raise AppRegistryNotReady("Models aren't loaded yet.")
def get_app_configs(self):
"""Import applications and return an iterable of app configs."""
self.check_apps_ready()
return self.app_configs.values()
def get_app_config(self, app_label):
"""
Import applications and returns an app config for the given label.
Raise LookupError if no application exists with this label.
"""
self.check_apps_ready()
try:
return self.app_configs[app_label]
except KeyError:
message = "No installed app with label '%s'." % app_label
for app_config in self.get_app_configs():
if app_config.name == app_label:
message += " Did you mean '%s'?" % app_config.label
break
raise LookupError(message)
# This method is performance-critical at least for Django's test suite.
@functools.lru_cache(maxsize=None)
def get_models(self, include_auto_created=False, include_swapped=False):
"""
Return a list of all installed models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have been swapped out.
Set the corresponding keyword argument to True to include such models.
"""
self.check_models_ready()
result = []
for app_config in self.app_configs.values():
result.extend(list(app_config.get_models(include_auto_created, include_swapped)))
return result
def get_model(self, app_label, model_name=None, require_ready=True):
"""
Return the model matching the given app_label and model_name.
As a shortcut, app_label may be in the form <app_label>.<model_name>.
model_name is case-insensitive.
Raise LookupError if no application exists with this label, or no
model exists with this name in the application. Raise ValueError if
called with a single argument that doesn't contain exactly one dot.
"""
if require_ready:
self.check_models_ready()
else:
self.check_apps_ready()
if model_name is None:
app_label, model_name = app_label.split('.')
app_config = self.get_app_config(app_label)
if not require_ready and app_config.models is None:
app_config.import_models()
return app_config.get_model(model_name, require_ready=require_ready)
def register_model(self, app_label, model):
# Since this method is called when models are imported, it cannot
# perform imports because of the risk of import loops. It mustn't
# call get_app_config().
model_name = model._meta.model_name
app_models = self.all_models[app_label]
if model_name in app_models:
if (model.__name__ == app_models[model_name].__name__ and
model.__module__ == app_models[model_name].__module__):
warnings.warn(
"Model '%s.%s' was already registered. "
"Reloading models is not advised as it can lead to inconsistencies, "
"most notably with related models." % (app_label, model_name),
RuntimeWarning, stacklevel=2)
else:
raise RuntimeError(
"Conflicting '%s' models in application '%s': %s and %s." %
(model_name, app_label, app_models[model_name], model))
app_models[model_name] = model
self.do_pending_operations(model)
self.clear_cache()
def is_installed(self, app_name):
"""
Check whether an application with this name exists in the registry.
app_name is the full name of the app e.g. 'django.contrib.admin'.
"""
self.check_apps_ready()
return any(ac.name == app_name for ac in self.app_configs.values())
def get_containing_app_config(self, object_name):
"""
Look for an app config containing a given object.
object_name is the dotted Python path to the object.
Return the app config for the inner application in case of nesting.
Return None if the object isn't in any registered app config.
"""
self.check_apps_ready()
candidates = []
for app_config in self.app_configs.values():
if object_name.startswith(app_config.name):
subpath = object_name[len(app_config.name):]
if subpath == '' or subpath[0] == '.':
candidates.append(app_config)
if candidates:
return sorted(candidates, key=lambda ac: -len(ac.name))[0]
def get_registered_model(self, app_label, model_name):
"""
Similar to get_model(), but doesn't require that an app exists with
the given app_label.
It's safe to call this method at import time, even while the registry
is being populated.
"""
model = self.all_models[app_label].get(model_name.lower())
if model is None:
raise LookupError(
"Model '%s.%s' not registered." % (app_label, model_name))
return model
@functools.lru_cache(maxsize=None)
def get_swappable_settings_name(self, to_string):
"""
For a given model string (e.g. "auth.User"), return the name of the
corresponding settings name if it refers to a swappable model. If the
referred model is not swappable, return None.
This method is decorated with lru_cache because it's performance
critical when it comes to migrations. Since the swappable settings don't
change after Django has loaded the settings, there is no reason to get
the respective settings attribute over and over again.
"""
for model in self.get_models(include_swapped=True):
swapped = model._meta.swapped
# Is this model swapped out for the model given by to_string?
if swapped and swapped == to_string:
return model._meta.swappable
# Is this model swappable and the one given by to_string?
if model._meta.swappable and model._meta.label == to_string:
return model._meta.swappable
return None
def set_available_apps(self, available):
"""
Restrict the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in TransactionTestCase.
This method is safe in the sense that it doesn't trigger any imports.
"""
available = set(available)
installed = set(app_config.name for app_config in self.get_app_configs())
if not available.issubset(installed):
raise ValueError(
"Available apps isn't a subset of installed apps, extra apps: %s"
% ", ".join(available - installed)
)
self.stored_app_configs.append(self.app_configs)
self.app_configs = OrderedDict(
(label, app_config)
for label, app_config in self.app_configs.items()
if app_config.name in available)
self.clear_cache()
def unset_available_apps(self):
"""Cancel a previous call to set_available_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.clear_cache()
def set_installed_apps(self, installed):
"""
Enable a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exception.
Primarily used as a receiver of the setting_changed signal in tests.
This method may trigger new imports, which may add new models to the
registry of all imported models. They will stay in the registry even
after unset_installed_apps(). Since it isn't possible to replay
imports safely (e.g. that could lead to registering listeners twice),
models are registered when they're imported and never removed.
"""
if not self.ready:
raise AppRegistryNotReady("App registry isn't ready yet.")
self.stored_app_configs.append(self.app_configs)
self.app_configs = OrderedDict()
self.apps_ready = self.models_ready = self.loading = self.ready = False
self.clear_cache()
self.populate(installed)
def unset_installed_apps(self):
"""Cancel a previous call to set_installed_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.apps_ready = self.models_ready = self.ready = True
self.clear_cache()
def clear_cache(self):
"""
Clear all internal caches, for methods that alter the app registry.
This is mostly used in tests.
"""
# Call expire cache on each model. This will purge
# the relation tree and the fields cache.
self.get_models.cache_clear()
if self.ready:
# Circumvent self.get_models() to prevent that the cache is refilled.
# This particularly prevents that an empty value is cached while cloning.
for app_config in self.app_configs.values():
for model in app_config.get_models(include_auto_created=True):
model._meta._expire_cache()
def lazy_model_operation(self, function, *model_keys):
"""
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed to this method must accept exactly n models as
arguments, where n=len(model_keys).
"""
# Base case: no arguments, just execute the function.
if not model_keys:
function()
# Recursive case: take the head of model_keys, wait for the
# corresponding model class to be imported and registered, then apply
# that argument to the supplied function. Pass the resulting partial
# to lazy_model_operation() along with the remaining model args and
# repeat until all models are loaded and all arguments are applied.
else:
next_model, more_models = model_keys[0], model_keys[1:]
# This will be executed after the class corresponding to next_model
# has been imported and registered. The `func` attribute provides
# duck-type compatibility with partials.
def apply_next_model(model):
next_function = partial(apply_next_model.func, model)
self.lazy_model_operation(next_function, *more_models)
apply_next_model.func = function
# If the model has already been imported and registered, partially
# apply it to the function now. If not, add it to the list of
# pending operations for the model, where it will be executed with
# the model class as its sole argument once the model is ready.
try:
model_class = self.get_registered_model(*next_model)
except LookupError:
self._pending_operations[next_model].append(apply_next_model)
else:
apply_next_model(model_class)
def do_pending_operations(self, model):
"""
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of Apps.register_model().
"""
key = model._meta.app_label, model._meta.model_name
for function in self._pending_operations.pop(key, []):
function(model)
apps = Apps(installed_apps=None)
| bsd-3-clause |
jmesteve/saas3 | openerp/addons/hr/res_users.py | 44 | 3136 | from openerp.osv import fields, osv
from openerp.tools.translate import _
class res_users(osv.Model):
""" Update of res.users class
- if adding groups to an user, check if base.group_user is in it
(member of 'Employee'), create an employee form linked to it.
"""
_name = 'res.users'
_inherit = ['res.users']
_columns = {
'display_employees_suggestions': fields.boolean("Display Employees Suggestions"),
}
_defaults = {
'display_employees_suggestions': True,
}
def __init__(self, pool, cr):
""" Override of __init__ to add access rights on
display_employees_suggestions fields. Access rights are disabled by
default, but allowed on some specific fields defined in
self.SELF_{READ/WRITE}ABLE_FIELDS.
"""
init_res = super(res_users, self).__init__(pool, cr)
# duplicate list to avoid modifying the original reference
self.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
self.SELF_WRITEABLE_FIELDS.append('display_employees_suggestions')
# duplicate list to avoid modifying the original reference
self.SELF_READABLE_FIELDS = list(self.SELF_READABLE_FIELDS)
self.SELF_READABLE_FIELDS.append('display_employees_suggestions')
return init_res
def stop_showing_employees_suggestions(self, cr, uid, user_id, context=None):
"""Update display_employees_suggestions value to False"""
if context is None:
context = {}
self.write(cr, uid, user_id, {"display_employees_suggestions": False}, context)
def _create_welcome_message(self, cr, uid, user, context=None):
"""Do not welcome new users anymore, welcome new employees instead"""
return True
def _message_post_get_eid(self, cr, uid, thread_id, context=None):
assert thread_id, "res.users does not support posting global messages"
if context and 'thread_model' in context:
context['thread_model'] = 'hr.employee'
if isinstance(thread_id, (list, tuple)):
thread_id = thread_id[0]
return self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', thread_id)], context=context)
def message_post(self, cr, uid, thread_id, context=None, **kwargs):
""" Redirect the posting of message on res.users to the related employee.
This is done because when giving the context of Chatter on the
various mailboxes, we do not have access to the current partner_id. """
if kwargs.get('type') == 'email':
return super(res_users, self).message_post(cr, uid, thread_id, context=context, **kwargs)
res = None
employee_ids = self._message_post_get_eid(cr, uid, thread_id, context=context)
if not employee_ids: # no employee: fall back on previous behavior
return super(res_users, self).message_post(cr, uid, thread_id, context=context, **kwargs)
for employee_id in employee_ids:
res = self.pool.get('hr.employee').message_post(cr, uid, employee_id, context=context, **kwargs)
return res
| agpl-3.0 |
helgee/pyodedop | odedop.py | 1 | 3965 | from collections import deque
import numpy as np
class ODE:
def __init__(
self, fcn, t, y, tend=None, backwards=False,
params=None, order=8, reltol=None, abstol=None,
init_stepsize=None, max_stepsize=None,
num_steps=100000, num_stiff=1000, num_dense=None,
safe=None, fac1=None, fac2=None, beta=None
):
self.fcn = fcn
self.t = t
self.y = np.atleast_1d(y)
self.tend = tend
self.backwards = backwards
self.params = params
self.order = order
if not reltol:
self.reltol = np.array([1e-6])
else:
self.reltol = np.atleast_1d(reltol)
if not abstol:
self.abstol = np.array([np.sqrt(np.finfo(float).eps)])
else:
self.abstol = np.atleast_1d(abstol)
self.max_stepsize = max_stepsize
self.num_steps = num_steps
self.num_stiff = num_stiff
self.num_dense = num_dense
if not safe:
self.safe = 0.9
else:
if 1e-4 <= safe <= 1.0:
raise ValueError("Curious input for safety factor.")
else:
self.safe = safe
if self.order == 8:
if not fac1:
self.fac1 = 0.333
else:
self.fac1 = fac1
if not fac2:
self.fac2 = 6.0
else:
self.fac2 = fac2
if not beta:
self.beta = 0.0
else:
if beta < 0.0:
self.beta = 0.0
elif beta > 0.2:
raise ValueError("Curious input for beta.")
else:
self.beta = beta
self.expo1 = 1.0/8.0 - self.beta*0.2
elif self.order == 5:
if not fac1:
self.fac1 = 0.2
else:
self.fac1 = fac1
if not fac2:
self.fac2 = 10.0
else:
self.fac2 = fac2
if not beta:
self.beta = 0.04
else:
if beta < 0.0:
self.beta = 0.0
elif beta > 0.2:
raise ValueError("Curious input for beta.")
else:
self.beta = beta
self.expo1 = 0.2 - self.beta*0.75
self.facc1 = 1.0/self.fac1
self.facc2 = 1.0/self.fac2
self._tout = deque()
self._yout = deque()
if self.tend:
self.posneg = np.sign(tend-self.t)
if not self.max_stepsize:
self.max_stepsize = tend-self.t
else:
self.posneg = -1 if backwards else 1
self.max_stepsize = 1e6
if not init_stepsize:
self.init_stepsize = self._get_init_stepsize()
else:
self.init_stepsize = init_stepsize
def integrate(self):
if not self.max_stepsize:
self.max_stepsize = tend-self.t
print(repr(self.init_stepsize))
def _get_init_stepsize(self):
f0 = self.fcn(self.t, self.y, self.params)
sk = self.abstol + self.reltol*np.abs(self.y)
dnf = np.sum(np.square(f0/sk))
dny = np.sum(np.square(self.y/sk))
if dnf <= 1e-10 or dny <= 1e-10:
stepsize = 1e-6
else:
stepsize = np.sqrt(dny/dnf)*0.01
stepsize = np.min([stepsize, self.max_stepsize])
stepsize *= self.posneg
f1 = self.fcn(self.t + stepsize, self.y + stepsize*f0, self.params)
der2 = np.linalg.norm(f1-f0/sk)/stepsize
der12 = np.max([np.abs(der2), np.sqrt(dnf)])
if der12 <= 1e-15:
stepsize1 = np.max([1e-6, np.abs(stepsize)*1e-3])
else:
stepsize1 = (0.01/der12)**(1.0/self.order)
stepsize = np.min(
[100*np.abs(stepsize), stepsize1, self.max_stepsize]
) * self.posneg
return stepsize
| mit |
poiesisconsulting/openerp-restaurant | association/__init__.py | 886 | 1054 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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/>.
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
ximenesuk/openmicroscopy | components/tools/OmeroPy/src/omero/util/script_utils.py | 4 | 43934 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2013 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Utility methods for dealing with scripts.
"""
import logging
import os
from struct import unpack
import omero.clients
from omero.rtypes import rdouble
from omero.rtypes import rint
from omero.rtypes import rstring
from omero.rtypes import unwrap
import omero.util.pixelstypetopython as pixelstypetopython
try:
import hashlib
hash_sha1 = hashlib.sha1
except:
import sha
hash_sha1 = sha.new
# r,g,b,a colours for use in scripts.
COLOURS = {'Red': (255,0,0,255), 'Green': (0,255,0,255), 'Blue': (0,0,255,255), 'Yellow': (255,255,0,255),
'White': (255,255,255,255), }
EXTRA_COLOURS = {'Violet': (238,133,238,255), 'Indigo': (79,6,132,255),
'Black': (0,0,0,255), 'Orange': (254,200,6,255), 'Gray': (130,130,130,255),}
CSV_NS = 'text/csv';
CSV_FORMAT = 'text/csv';
SU_LOG = logging.getLogger("omero.util.script_utils")
def drawTextOverlay(draw, x, y, text, colour='0xffffff'):
"""
Draw test on image.
@param draw The PIL Draw class.
@param x The x-coord to draw.
@param y The y-coord to draw.
@param text The text to render.
@param colour The colour as a PIL colour string to draw the text in.
"""
draw.text((x,y),text, fill=colour)
def drawLineOverlay(draw, x0, y0, x1, y1, colour='0xffffff'):
"""
Draw line on image.
@param draw The PIL Draw class.
@param x0 The x0-coord of line.
@param y0 The y0-coord of line.
@param x1 The x1-coord of line.
@param y1 The y1-coord of line.
@param colour The colour as a PIL colour fill in the line.
"""
draw.line([(x0, y0),(x1,y1)], fill=colour)
def rgbToRGBInt(red, green, blue):
"""
Convert an R,G,B value to an int.
@param R the Red value.
@param G the Green value.
@param B the Blue value.
@return See above.
"""
RGBInt = (red<<16)+(green<<8)+blue;
return int(RGBInt);
def RGBToPIL(RGB):
"""
Convert an RGB value to a PIL colour value.
@param RGB the RGB value.
@return See above.
"""
hexval = hex(int(RGB));
return '#'+(6-len(hexval[2:]))*'0'+hexval[2:];
def rangeToStr(range):
"""
Map a range to a string of numbers
@param range See above.
@return See above.
"""
first = 1;
string = "";
for value in range:
if(first==1):
string = str(value);
first = 0;
else:
string = string + ','+str(value)
return string;
def rmdir_recursive(dir):
for name in os.listdir(dir):
full_name = os.path.join(dir, name)
# on Windows, if we don't have write permission we can't remove
# the file/directory either, so turn that on
if not os.access(full_name, os.W_OK):
os.chmod(full_name, 0600)
if os.path.isdir(full_name):
rmdir_recursive(full_name)
else:
os.remove(full_name)
os.rmdir(dir)
def calcSha1(filename):
"""
Returns a hash of the file identified by filename
@param filename: pathName of the file
@return: The hash of the file
"""
fileHandle = open(filename)
h = hash_sha1()
h.update(fileHandle.read())
hash = h.hexdigest()
fileHandle.close()
return hash;
def calcSha1FromData(data):
"""
Calculate the Sha1 Hash from a data array
@param data The data array.
@return The Hash
"""
h = hash_sha1()
h.update(data)
hash = h.hexdigest()
return hash;
def getFormat(queryService, format):
return queryService.findByQuery("from Format as f where f.value='"+format+"'", None)
def createFile(updateService, filename, mimetype=None, origFilePathName=None):
"""
Creates an original file, saves it to the server and returns the result
@param queryService: The query service E.g. session.getQueryService()
@param updateService: The update service E.g. session.getUpdateService()
@param filename: The file path and name (or name if in same folder). String
@param mimetype: The mimetype (string) or Format object representing the file format
@param origFilePathName: Optional path/name for the original file
@return: The saved OriginalFileI, as returned from the server
"""
originalFile = omero.model.OriginalFileI();
if(origFilePathName == None):
origFilePathName = filename;
path, name = os.path.split(origFilePathName)
originalFile.setName(omero.rtypes.rstring(name));
originalFile.setPath(omero.rtypes.rstring(path));
# just in case we are passed a FormatI object
try:
v = mimetype.getValue()
mt = v.getValue()
except:
# handle the string we expect
mt = mimetype
if mt:
originalFile.mimetype = omero.rtypes.rstring(mt)
originalFile.setSize(omero.rtypes.rlong(os.path.getsize(filename)));
originalFile.setHash(omero.rtypes.rstring(calcSha1(filename)));
return updateService.saveAndReturnObject(originalFile);
def uploadFile(rawFileStore, originalFile, filePath=None):
"""
Uploads an OriginalFile to the server
@param rawFileStore: The Omero rawFileStore
@param originalFile: The OriginalFileI
@param filePath: Where to find the file to upload. If None, use originalFile.getName().getValue()
"""
rawFileStore.setFileId(originalFile.getId().getValue());
fileSize = originalFile.getSize().getValue();
increment = 10000;
cnt = 0;
if filePath == None:
filePath = originalFile.getName().getValue()
fileHandle = open(filePath, 'rb');
done = 0
while(done!=1):
if(increment+cnt<fileSize):
blockSize = increment;
else:
blockSize = fileSize-cnt;
done = 1;
fileHandle.seek(cnt);
block = fileHandle.read(blockSize);
rawFileStore.write(block, cnt, blockSize);
cnt = cnt+blockSize;
fileHandle.close();
def downloadFile(rawFileStore, originalFile, filePath=None):
"""
Downloads an OriginalFile from the server.
@param rawFileStore: The Omero rawFileStore
@param originalFile: The OriginalFileI
@param filePath: Where to download the file. If None, use originalFile.getName().getValue()
"""
fileId = originalFile.getId().getValue()
rawFileStore.setFileId(fileId)
fileSize = originalFile.getSize().getValue()
maxBlockSize = 10000
cnt = 0
if filePath == None:
filePath = originalFile.getName().getValue()
# don't overwrite. Add number before extension
i = 1
path, ext = filePath.rsplit(".", 1)
while os.path.exists(filePath):
filePath = "%s_%s.%s" % (path,i,ext)
i +=1
fileHandle = open(filePath, 'w')
cnt = 0;
fileSize = originalFile.getSize().getValue()
while(cnt<fileSize):
blockSize = min(maxBlockSize, fileSize)
block = rawFileStore.read(cnt, blockSize)
cnt = cnt+blockSize
fileHandle.write(block)
fileHandle.close()
return filePath
def attachFileToParent(updateService, parent, originalFile, description=None, namespace=None):
"""
Attaches the original file (file) to a Project, Dataset or Image (parent)
@param updateService: The update service
@param parent: A ProjectI, DatasetI or ImageI to attach the file to
@param originalFile: The OriginalFileI to attach
@param description: Optional description for the file annotation. String
@param namespace: Optional namespace for file annotataion. String
@return: The saved and returned *AnnotationLinkI (* = Project, Dataset or Image)
"""
fa = omero.model.FileAnnotationI();
fa.setFile(originalFile);
if description:
fa.setDescription(omero.rtypes.rstring(description))
if namespace:
fa.setNs(omero.rtypes.rstring(namespace))
if type(parent) == omero.model.DatasetI:
l = omero.model.DatasetAnnotationLinkI()
elif type(parent) == omero.model.ProjectI:
l = omero.model.ProjectAnnotationLinkI()
elif type(parent) == omero.model.ImageI:
l = omero.model.ImageAnnotationLinkI()
else:
return
parent = parent.__class__(parent.id.val, False) # use unloaded object to avoid update conflicts
l.setParent(parent);
l.setChild(fa);
return updateService.saveAndReturnObject(l);
def uploadAndAttachFile(queryService, updateService, rawFileStore, parent, localName, mimetype, description=None, namespace=None, origFilePathName=None):
"""
Uploads a local file to the server, as an Original File and attaches it to the
parent (Project, Dataset or Image)
@param queryService: The query service
@param updateService: The update service
@param rawFileStore: The rawFileStore
@param parent: The ProjectI or DatasetI or ImageI to attach file to
@param localName: Full Name (and path) of the file location to upload. String
@param mimetype: The original file mimetype. E.g. "PNG". String
@param description: Optional description for the file annotation. String
@param namespace: Namespace to set for the original file
@param origFilePathName: The /path/to/file/fileName.ext you want on the server. If none, use output as name
@return: The originalFileLink child. (FileAnnotationI)
"""
filename = localName
if origFilePathName == None:
origFilePathName = localName
originalFile = createFile(updateService, filename, mimetype, origFilePathName);
uploadFile(rawFileStore, originalFile, localName)
fileLink = attachFileToParent(updateService, parent, originalFile, description, namespace)
return fileLink.getChild()
def createLinkFileAnnotation(conn, localPath, parent, output="Output", parenttype="Image", mimetype=None, desc=None, ns=None, origFilePathAndName=None):
"""
Uploads a local file to the server, as an Original File and attaches it to the
parent (Project, Dataset or Image)
@param conn: The L{omero.gateway.BlitzGateway} connection.
@param parent: The ProjectI or DatasetI or ImageI to attach file to
@param localPath: Full Name (and path) of the file location to upload. String
@param mimetype: The original file mimetype. E.g. "PNG". String
@param description: Optional description for the file annotation. String
@param namespace: Namespace to set for the original file
@param
@param origFilePathName: The /path/to/file/fileName.ext you want on the server. If none, use output as name
@return: The originalFileLink child (FileAnnotationI) and a log message
"""
if os.path.exists(localPath):
fileAnnotation = conn.createFileAnnfromLocalFile(localPath, origFilePathAndName=origFilePathAndName, mimetype=mimetype, ns=ns, desc=desc)
message = "%s created" % output
if parent is not None:
if parent.canAnnotate():
parentClass = parent.OMERO_CLASS
message += " and attached to %s%s %s." % (parentClass[0].lower(), parentClass[1:], parent.getName())
parent.linkAnnotation(fileAnnotation)
else:
message += " but could not be attached."
else:
message = "%s not created." % output
fileAnnotation = None
return fileAnnotation, message
def getObjects(conn, params):
"""
Get the objects specified by the script parameters.
Assume the parameters contain the keys IDs and Data_Type
@param conn: The L{omero.gateway.BlitzGateway} connection.
@param params: The script parameters
@return: The valid objects and a log message
"""
dataType = params["Data_Type"]
ids = params["IDs"]
objects = list(conn.getObjects(dataType,ids))
message = ""
if not objects:
message += "No %s%s found. " % (dataType[0].lower(), dataType[1:])
else:
if not len(objects) == len(ids):
message += "Found %s out of %s %s%s(s). " % (len(objects), len(ids), dataType[0].lower(), dataType[1:])
# Sort the objects according to the order of IDs
idMap = dict( [(o.id, o) for o in objects] )
objects = [idMap[i] for i in ids if i in idMap]
return objects, message
def addAnnotationToImage(updateService, image, annotation):
"""
Add the annotation to an image.
@param updateService The update service to create the annotation link.
@param image The ImageI object that should be annotated.
@param annotation The annotation object
@return The new annotationlink object
"""
l = omero.model.ImageAnnotationLinkI();
l.setParent(image);
l.setChild(annotation);
return updateService.saveAndReturnObject(l);
def readFromOriginalFile(rawFileService, iQuery, fileId, maxBlockSize = 10000):
"""
Read the OriginalFile with fileId and return it as a string.
@param rawFileService The RawFileService service to read the originalfile.
@param iQuery The Query Service.
@param fileId The id of the originalFile object.
@param maxBlockSize The block size of each read.
@return The OriginalFile object contents as a string
"""
fileDetails = iQuery.findByQuery("from OriginalFile as o where o.id = " + str(fileId) , None);
rawFileService.setFileId(fileId);
data = '';
cnt = 0;
fileSize = fileDetails.getSize().getValue();
while(cnt<fileSize):
blockSize = min(maxBlockSize, fileSize);
block = rawFileService.read(cnt, blockSize);
data = data + block;
cnt = cnt+blockSize;
return data[0:fileSize];
def readFileAsArray(rawFileService, iQuery, fileId, row, col, separator = ' '):
"""
Read an OriginalFile with id and column separator and return it as an array.
@param rawFileService The RawFileService service to read the originalfile.
@param iQuery The Query Service.
@param fileId The id of the originalFile object.
@param row The number of rows in the file.
@param col The number of columns in the file.
@param sep the column separator.
@return The file as an NumPy array.
"""
from numpy import fromstring, reshape
textBlock = readFromOriginalFile(rawFileService, iQuery, fileId);
arrayFromFile = fromstring(textBlock,sep = separator);
return reshape(arrayFromFile, (row, col));
def readFlimImageFile(rawPixelsStore, pixels):
"""
Read the RawImageFlimFile with fileId and return it as an array [c, x, y]
@param rawPixelsStore The rawPixelStore service to get the image.
@param pixels The pixels of the image.
@return The Contents of the image for z = 0, t = 0, all channels;
"""
from numpy import zeros
sizeC = pixels.getSizeC().getValue();
sizeX = pixels.getSizeX().getValue();
sizeY = pixels.getSizeY().getValue();
id = pixels.getId().getValue();
pixelsType = pixels.getPixelsType().getValue().getValue();
rawPixelsStore.setPixelsId(id , False);
cRange = range(0, sizeC);
stack = zeros((sizeC, sizeX, sizeY),dtype=pixelstypetopython.toNumpy(pixelsType));
for c in cRange:
plane = downloadPlane(rawPixelsStore, pixels, 0, c, 0);
stack[c,:,:]=plane;
return stack;
def downloadPlane(rawPixelsStore, pixels, z, c, t):
"""
Download the plane [z,c,t] for image pixels. Pixels must have pixelsType loaded.
N.B. The rawPixelsStore must have already been initialised by setPixelsId()
@param rawPixelsStore The rawPixelStore service to get the image.
@param pixels The pixels of the image.
@param z The Z-Section to retrieve.
@param c The C-Section to retrieve.
@param t The T-Section to retrieve.
@return The Plane of the image for z, c, t
"""
from numpy import array
rawPlane = rawPixelsStore.getPlane(z, c, t);
sizeX = pixels.getSizeX().getValue();
sizeY = pixels.getSizeY().getValue();
pixelType = pixels.getPixelsType().getValue().getValue();
convertType ='>'+str(sizeX*sizeY)+pixelstypetopython.toPython(pixelType);
convertedPlane = unpack(convertType, rawPlane);
numpyType = pixelstypetopython.toNumpy(pixelType)
remappedPlane = array(convertedPlane, numpyType);
remappedPlane.resize(sizeY, sizeX);
return remappedPlane;
def getPlaneFromImage(imagePath, rgbIndex=None):
"""
Reads a local image (E.g. single plane tiff) and returns it as a numpy 2D array.
@param imagePath Path to image.
"""
from numpy import asarray
try:
from PIL import Image # see ticket:2597
except ImportError:
import Image # see ticket:2597
i = Image.open(imagePath)
a = asarray(i)
if rgbIndex == None:
return a
else:
return a[:, :, rgbIndex]
def uploadDirAsImages(sf, queryService, updateService, pixelsService, path, dataset = None):
"""
Reads all the images in the directory specified by 'path' and uploads them to OMERO as a single
multi-dimensional image, placed in the specified 'dataset'
Uses regex to determine the Z, C, T position of each image by name,
and therefore determines sizeZ, sizeC, sizeT of the new Image.
@param path the path to the directory containing images.
@param dataset the OMERO dataset, if we want to put images somewhere. omero.model.DatasetI
"""
import re
from numpy import zeros
regex_token = re.compile(r'(?P<Token>.+)\.')
regex_time = re.compile(r'T(?P<T>\d+)')
regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)')
regex_zslice = re.compile(r'_Z(?P<Z>\d+)')
# assume 1 image in this folder for now.
# Make a single map of all images. key is (z,c,t). Value is image path.
imageMap = {}
channelSet = set()
tokens = []
# other parameters we need to determine
sizeZ = 1
sizeC = 1
sizeT = 1
zStart = 1 # could be 0 or 1 ?
tStart = 1
fullpath = None
rgb = False
# process the names and populate our imagemap
for f in os.listdir(path):
fullpath = os.path.join(path, f)
tSearch = regex_time.search(f)
cSearch = regex_channel.search(f)
zSearch = regex_zslice.search(f)
tokSearch = regex_token.search(f)
if f.endswith(".jpg"):
rgb = True
if tSearch == None:
theT = 0
else:
theT = int(tSearch.group('T'))
if cSearch == None:
cName = "0"
else:
cName = cSearch.group('C')
if zSearch == None:
theZ = 0
else:
theZ = int(zSearch.group('Z'))
channelSet.add(cName)
sizeZ = max(sizeZ, theZ)
zStart = min(zStart, theZ)
sizeT = max(sizeT, theT)
tStart = min(tStart, theT)
if tokSearch != None:
tokens.append(tokSearch.group('Token'))
imageMap[(theZ, cName, theT)] = fullpath
colourMap = {}
if not rgb:
channels = list(channelSet)
# see if we can guess what colour the channels should be, based on name.
for i, c in enumerate(channels):
if c == 'rfp':
colourMap[i] = COLOURS["Red"]
if c == 'gfp':
colourMap[i] = COLOURS["Green"]
else:
channels = ("red", "green", "blue")
colourMap[0] = COLOURS["Red"]
colourMap[1] = COLOURS["Green"]
colourMap[2] = COLOURS["Blue"]
sizeC = len(channels)
# use the common stem as the image name
imageName = os.path.commonprefix(tokens).strip('0T_')
description = "Imported from images in %s" % path
SU_LOG.info("Creating image: %s" % imageName)
# use the last image to get X, Y sizes and pixel type
if rgb:
plane = getPlaneFromImage(fullpath, 0)
else:
plane = getPlaneFromImage(fullpath)
pType = plane.dtype.name
# look up the PixelsType object from DB
pixelsType = queryService.findByQuery(\
"from PixelsType as p where p.value='%s'" % pType, None) # omero::model::PixelsType
if pixelsType == None and pType.startswith("float"): # e.g. float32
pixelsType = queryService.findByQuery(\
"from PixelsType as p where p.value='%s'" % "float", None) # omero::model::PixelsType
if pixelsType == None:
SU_LOG.warn("Unknown pixels type for: %s" % pType)
return
sizeY, sizeX = plane.shape
SU_LOG.debug("sizeX: %s sizeY: %s sizeZ: %s sizeC: %s sizeT: %s" % (sizeX, sizeY, sizeZ, sizeC, sizeT))
# code below here is very similar to combineImages.py
# create an image in OMERO and populate the planes with numpy 2D arrays
channelList = range(sizeC)
imageId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT, channelList, pixelsType, imageName, description)
params = omero.sys.ParametersI()
params.addId(imageId)
pixelsId = queryService.projection(\
"select p.id from Image i join i.pixels p where i.id = :id",\
params)[0][0].val
rawPixelStore = sf.createRawPixelsStore()
rawPixelStore.setPixelsId(pixelsId, True)
try:
for theC in range(sizeC):
minValue = 0
maxValue = 0
for theZ in range(sizeZ):
zIndex = theZ + zStart
for theT in range(sizeT):
tIndex = theT + tStart
if rgb:
c = "0"
else:
c = channels[theC]
if (zIndex, c, tIndex) in imageMap:
imagePath = imageMap[(zIndex, c, tIndex)]
if rgb:
SU_LOG.debug("Getting rgb plane from: %s" % imagePath)
plane2D = getPlaneFromImage(imagePath, theC)
else:
SU_LOG.debug("Getting plane from: %s" % imagePath)
plane2D = getPlaneFromImage(imagePath)
else:
SU_LOG.debug("Creating blank plane for .", theZ, channels[theC], theT)
plane2D = zeros((sizeY, sizeX))
SU_LOG.debug("Uploading plane: theZ: %s, theC: %s, theT: %s" % (theZ, theC, theT))
uploadPlane(rawPixelStore, plane2D, theZ, theC, theT)
minValue = min(minValue, plane2D.min())
maxValue = max(maxValue, plane2D.max())
pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue), float(maxValue))
rgba = None
if theC in colourMap:
rgba = colourMap[theC]
try:
renderingEngine = sf.createRenderingEngine()
resetRenderingSettings(renderingEngine, pixelsId, theC, minValue, maxValue, rgba)
finally:
renderingEngine.close()
finally:
rawPixelStore.close()
# add channel names
pixels = pixelsService.retrievePixDescription(pixelsId)
i = 0
for c in pixels.iterateChannels(): # c is an instance of omero.model.ChannelI
lc = c.getLogicalChannel() # returns omero.model.LogicalChannelI
lc.setName(rstring(channels[i]))
updateService.saveObject(lc)
i += 1
# put the image in dataset, if specified.
if dataset:
link = omero.model.DatasetImageLinkI()
link.parent = omero.model.DatasetI(dataset.id.val, False)
link.child = omero.model.ImageI(imageId, False)
updateService.saveAndReturnObject(link)
return imageId
def uploadCecogObjectDetails(updateService, imageId, filePath):
"""
Parses a single line of cecog output and saves as a roi.
Adds a Rectangle (particle) to the current OMERO image, at point x, y.
Uses the self.image (OMERO image) and self.updateService
"""
objects = {}
roi_ids = []
import fileinput
for line in fileinput.input([filePath]):
theT = None
x = None
y = None
parts = line.split("\t")
names = ("frame", "objID", "primaryClassLabel", "primaryClassName", "centerX", "centerY", "mean", "sd", "secondaryClassabel", "secondaryClassName", "secondaryMean", "secondarySd")
values = {}
for idx, name in enumerate(names):
if len(parts) >= idx:
values[name] = parts[idx]
frame = values["frame"]
try:
frame = long(frame)
except ValueError:
SU_LOG.debug("Non-roi line: %s " % line)
continue
theT = frame - 1
objID = values["objID"]
className = values["primaryClassName"]
x = float(values["centerX"])
y = float(values["centerY"])
description = ""
for name in names:
description += ("%s=%s\n" % (name, values.get(name, "(missing)")))
if theT and x and y:
SU_LOG.debug("Adding point '%s' to frame: %s, x: %s, y: %s" % (className, theT, x, y))
try:
shapes = objects[objID]
except KeyError:
shapes = []
objects[objID] = shapes
shapes.append( (theT, className, x, y, values, description) )
for object, shapes in objects.items():
# create an ROI, add the point and save
roi = omero.model.RoiI()
roi.setImage(omero.model.ImageI(imageId, False))
roi.setDescription(omero.rtypes.rstring("objID: %s" % object))
# create and save a point
for shape in shapes:
theT, className, x, y, values, description = shape
point = omero.model.PointI()
point.cx = rdouble(x)
point.cy = rdouble(y)
point.theT = rint(theT)
point.theZ = rint(0) # Workaround for shoola:ticket:1596
if className:
point.setTextValue(rstring(className)) # for display only
# link the point to the ROI and save it
roi.addShape(point)
roi = updateService.saveAndReturnObject(point)
roi_ids.append(roi.id.val)
return roi_ids
def split_image(client, imageId, dir, unformattedImageName = "tubulin_P037_T%05d_C%s_Z%d_S1.tif", dims = ('T', 'C', 'Z')):
"""
Splits the image into component planes, which are saved as local tiffs according to unformattedImageName.
E.g. myLocalDir/tubulin_P037_T%05d_C%s_Z%d_S1.tif which will be formatted according to dims, E.g. ('T', 'C', 'Z')
Channel will be formatted according to channel name, not index.
@param rawPixelsStore The rawPixelStore
@param queryService
@param c The C-Section to retrieve.
@param t The T-Section to retrieve.
@param imageName the local location to save the image.
"""
unformattedImageName = os.path.join(dir, unformattedImageName)
session = client.getSession()
queryService = session.getQueryService()
rawPixelsStore = session.createRawPixelsStore()
pixelsService = session.getPixelsService()
try:
from PIL import Image # see ticket:2597
except:
import Image # see ticket:2597
query_string = "select p from Pixels p join fetch p.image as i join fetch p.pixelsType where i.id='%s'" % imageId
pixels = queryService.findByQuery(query_string, None)
sizeZ = pixels.getSizeZ().getValue()
sizeC = pixels.getSizeC().getValue()
sizeT = pixels.getSizeT().getValue()
rawPixelsStore.setPixelsId(pixels.getId().getValue(), True)
channelMap = {}
cIndex = 0
pixels = pixelsService.retrievePixDescription(pixels.id.val) # load channels
for c in pixels.iterateChannels():
lc = c.getLogicalChannel()
channelMap[cIndex] = lc.getName() and lc.getName().getValue() or str(cIndex)
cIndex += 1
def formatName(unformatted, z, c, t):
# need to turn dims E.g. ('T', 'C', 'Z') into tuple, E.g. (t, c, z)
dimMap = {'T': t, 'C':channelMap[c], 'Z': z}
dd = tuple([dimMap[d] for d in dims])
return unformatted % dd
# cecog does this, but other formats may want to start at 0
zStart = 1
tStart = 1
# loop through dimensions, saving planes as tiffs.
for z in range(sizeZ):
for c in range(sizeC):
for t in range(sizeT):
imageName = formatName(unformattedImageName, z+zStart, c, t+tStart)
SU_LOG.debug("downloading plane z: %s c: %s t: %s to %s" % (z, c, t, imageName))
plane = downloadPlane(rawPixelsStore, pixels, z, c, t)
i = Image.fromarray(plane)
i.save(imageName)
def createFileFromData(updateService, queryService, filename, data):
"""
Create a file from the data of type format, setting sha1, ..
@param updateService The updateService to create the annotation link.
@param filename The name of the file.
@param data The data to save.
@param format The Format of the file.
@return The newly created OriginalFile.
"""
tempFile = omero.model.OriginalFileI();
tempFile.setName(omero.rtypes.rstring(filename));
tempFile.setPath(omero.rtypes.rstring(filename));
tempFile.setMimetype(omero.rtypes.rstring(CSV_FORMAT));
tempFile.setSize(omero.rtypes.rlong(len(data)));
tempFile.setHash(omero.rtypes.rstring(calcSha1FromData(data)));
return updateService.saveAndReturnObject(tempFile);
def attachArrayToImage(updateService, image, file, nameSpace):
"""
Attach an array, stored as a csv file to an image. Returns the annotation.
@param updateService The updateService to create the annotation link.
@param image The image to attach the data to.
@param filename The name of the file.
@param namespace The namespace of the file.
@return
"""
fa = omero.model.FileAnnotationI();
fa.setFile(file);
fa.setNs(omero.rtypes.rstring(nameSpace))
l = omero.model.ImageAnnotationLinkI();
l.setParent(image);
l.setChild(fa);
l = updateService.saveAndReturnObject(l);
return l.getChild();
def uploadArray(rawFileStore, updateService, queryService, image, filename, namespace, array):
"""
Upload the data to the server, creating the OriginalFile Object and attaching it to the image.
@param rawFileStore The rawFileStore used to create the file.
@param updateService The updateService to create the annotation link.
@param image The image to attach the data to.
@param filename The name of the file.
@param namespace The name space associated to the annotation.
@param data The data to save.
@return The newly created file.
"""
data = arrayToCSV(array);
file = createFileFromData(updateService, queryService, filename, data);
rawFileStore.setFileId(file.getId().getValue());
fileSize = len(data);
increment = 10000;
cnt = 0;
done = 0
while(done!=1):
if(increment+cnt<fileSize):
blockSize = increment;
else:
blockSize = fileSize-cnt;
done = 1;
block = data[cnt:cnt+blockSize];
rawFileStore.write(block, cnt, blockSize);
cnt = cnt+blockSize;
return attachArrayToImage(updateService, image, file, namespace);
def arrayToCSV(data):
"""
Convert the numpy array data to a csv file.
@param data the Numpy Array
@return The CSV string.
"""
size = data.shape;
row = size[0];
col = size[1];
strdata ="";
for r in range(0,row):
for c in range(0, col):
strdata = strdata + str(data[r,c])
if(c<col-1):
strdata = strdata+',';
strdata = strdata + '\n';
return strdata;
def uploadPlane(rawPixelsStore, plane, z, c, t):
"""
Upload the plane to the server attching it to the current z,c,t of the already instantiated rawPixelStore.
@param rawPixelsStore The rawPixelStore which is already pointing to the data.
@param plane The data to upload
@param z The Z-Section of the plane.
@param c The C-Section of the plane.
@param t The T-Section of the plane.
"""
byteSwappedPlane = plane.byteswap();
convertedPlane = byteSwappedPlane.tostring();
rawPixelsStore.setPlane(convertedPlane, z, c, t)
def uploadPlaneByRow(rawPixelsStore, plane, z, c, t):
"""
Upload the plane to the server one row at a time,
attching it to the current z,c,t of the already instantiated rawPixelStore.
@param rawPixelsStore The rawPixelStore which is already pointing to the data.
@param plane The data to upload
@param z The Z-Section of the plane.
@param c The C-Section of the plane.
@param t The T-Section of the plane.
"""
byteSwappedPlane = plane.byteswap()
rowCount, colCount = plane.shape
for y in range(rowCount):
row = byteSwappedPlane[y:y+1, :] # slice y axis into rows
convertedRow = row.tostring()
rawPixelsStore.setRow(convertedRow, y, z, c, t)
def getRenderingEngine(session, pixelsId):
"""
Create the renderingEngine for the pixelsId.
@param session The current session to create the renderingEngine from.
@return The renderingEngine Service for the pixels.
"""
renderingEngine = session.createRenderingEngine();
renderingEngine.lookupPixels(pixelsId);
if(renderingEngine.lookupRenderingDef(pixelsId)==0):
renderingEngine.resetDefaults();
renderingEngine.lookupRenderingDef(pixelsId);
renderingEngine.load();
return renderingEngine;
def createPlaneDef(z,t):
"""
Create the plane rendering def, for z,t
@param Z the Z-Section
@param T The T-Point.
@return The RenderingDef Object.
"""
planeDef = omero.romio.PlaneDef()
planeDef.t = t;
planeDef.z = z;
planeDef.x = 0;
planeDef.y = 0;
planeDef.slice = 0;
return planeDef;
def getPlaneAsPackedInt(renderingEngine, z, t):
"""
Get the rendered Image of the plane for the z, t with the default channels.
@param renderingEngine The already instantiated renderEngine.
@param z The Z-section.
@param t The Timepoint.
"""
planeDef = createPlaneDef(z, t);
return renderingEngine.renderAsPackedInt(planeDef);
def getRawPixelsStore(session, pixelsId):
"""
Get the rawPixelsStore for the Image with pixelsId
@param pixelsId The pixelsId of the object to retrieve.
@return The rawPixelsStore service.
"""
rawPixelsStore = session.createRawPixelsStore();
rawPixelsStore.setPixelsId(pixelsId);
return rawPixelsStore;
def getRawFileStore(session, fileId):
"""
Get the rawFileStore for the file with fileId
@param fileId The fileId of the object to retrieve.
@return The rawFileStore service.
"""
rawFileStore = session.createRawFileStore();
rawFileStore.setFileId(fileId);
return rawFileStore;
def getPlaneInfo(iQuery, pixelsId, asOrderedList = True):
"""
Get the plane info for the pixels object returning it in order of z,t,c
@param iQuery The query service.
@param pixelsId The pixels for Id.
@param asOrderedList
@return list of planeInfoTimes or map["z:t:c:]
"""
query = "from PlaneInfo as Info where pixels.id='"+str(pixelsId)+"' orderby info.deltaT"
infoList = iQuery.findAllByQuery(query,None)
if(asOrderedList):
map = {}
for info in infoList:
key = "z:"+str(info.theZ.getValue())+"t:"+str(info.theT.getValue())+"c:"+str(info.theC.getValue());
map[key] = info.deltaT.getValue();
return map;
else:
return infoList;
def IdentityFn(commandArgs):
return commandArgs;
def resetRenderingSettings(renderingEngine, pixelsId, cIndex, minValue, maxValue, rgba=None):
"""
Simply resests the rendering settings for a pixel set, according to the min and max values
The rendering engine does NOT have to be primed with pixelsId, as that is handled by this method.
@param renderingEngine The OMERO rendering engine
@param pixelsId The Pixels ID
@param minValue Minimum value of rendering window
@param maxValue Maximum value of rendering window
@param rgba Option to set the colour of the channel. (r,g,b,a) tuple.
"""
renderingEngine.lookupPixels(pixelsId)
if not renderingEngine.lookupRenderingDef(pixelsId):
renderingEngine.resetDefaults()
if rgba == None:
rgba=COLOURS["White"] # probably don't want E.g. single channel image to be blue!
if not renderingEngine.lookupRenderingDef(pixelsId):
raise Exception("Still No Rendering Def")
renderingEngine.load()
renderingEngine.setChannelWindow(cIndex, float(minValue), float(maxValue))
if rgba:
red, green, blue, alpha = rgba
renderingEngine.setRGBA(cIndex, red, green, blue, alpha)
renderingEngine.saveCurrentSettings()
def createNewImage(session, plane2Dlist, imageName, description, dataset=None):
"""
Creates a new single-channel, single-timepoint image from the list of 2D numpy arrays in plane2Dlist
with each numpy 2D plane becoming a Z-section.
@param session An OMERO service factory or equivalent with getQueryService() etc.
@param plane2Dlist A list of numpy 2D arrays, corresponding to Z-planes of new image.
@param imageName Name of new image
@param description Description for the new image
@param dataset If specified, put the image in this dataset. omero.model.Dataset object
@return The new OMERO image: omero.model.ImageI
"""
queryService = session.getQueryService()
pixelsService = session.getPixelsService()
rawPixelStore = session.createRawPixelsStore()
renderingEngine = session.createRenderingEngine()
containerService = session.getContainerService()
pType = plane2Dlist[0].dtype.name
pixelsType = queryService.findByQuery("from PixelsType as p where p.value='%s'" % pType, None) # omero::model::PixelsType
theC, theT = (0,0)
# all planes in plane2Dlist should be same shape.
shape = plane2Dlist[0].shape
sizeY, sizeX = shape
minValue = plane2Dlist[0].min()
maxValue = plane2Dlist[0].max()
# get some other dimensions and create the image.
channelList = [theC] # omero::sys::IntList
sizeZ, sizeT = (len(plane2Dlist),1)
iId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT, channelList, pixelsType, imageName, description)
imageId = iId.getValue()
image = containerService.getImages("Image", [imageId], None)[0]
# upload plane data
pixelsId = image.getPrimaryPixels().getId().getValue()
rawPixelStore.setPixelsId(pixelsId, True)
for theZ, plane2D in enumerate(plane2Dlist):
minValue = min(minValue, plane2D.min())
maxValue = max(maxValue, plane2D.max())
if plane2D.size > 1000000:
uploadPlaneByRow(rawPixelStore, plane2D, theZ, theC, theT)
else:
uploadPlane(rawPixelStore, plane2D, theZ, theC, theT)
pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue), float(maxValue))
resetRenderingSettings(renderingEngine, pixelsId, theC, minValue, maxValue)
# put the image in dataset, if specified.
if dataset:
link = omero.model.DatasetImageLinkI()
link.parent = omero.model.DatasetI(dataset.id.val, False)
link.child = omero.model.ImageI(image.id.val, False)
session.getUpdateService().saveObject(link)
renderingEngine.close()
rawPixelStore.close()
return image
def parseInputs(client, session, processFn=IdentityFn):
"""
parse the inputs from the client object and map it to some other form, values may be transformed by function.
@param client The client object
@param session The current session.
@param processFn A function to transform data to some other form.
@return Parsed inputs as defined by ProcessFn.
"""
inputKeys = client.getInputKeys();
commandArgs = {};
for key in inputKeys:
commandArgs[key]=client.getInput(key).getValue();
return processFn(commandArgs);
def getROIFromImage(iROIService, imageId, namespace=None):
"""
Get the ROI from the server for the image with the namespace
@param iROIService The iROIService object
@param imageId The imageId to retreive ROI from.
@param namespace The namespace of the ROI.
@return See above.
"""
roiOpts = omero.api.RoiOptions()
if(namespace!=None):
roiOpts.namespace = namespace;
return iROIService.findByImage(imageId, roiOpts);
def toCSV(list):
"""
Convert a list to a Comma Separated Value string.
@param list The list to convert.
@return See above.
"""
lenList = len(list);
cnt = 0;
str = "";
for item in list:
str = str + item;
if(cnt < lenList-1):
str = str + ",";
cnt = cnt +1;
return str;
def toList(csvString):
"""
Convert a csv string to a list of strings
@param csvString The CSV string to convert.
@return See above.
"""
list = csvString.split(',');
for index in range(len(list)):
list[index] = list[index].strip();
return list;
def registerNamespace(iQuery, iUpdate, namespace, keywords):
"""
Register a workflow with the server, if the workflow does not exist create it and returns it,
otherwise it returns the already created workflow.
@param iQuery The query service.
@param iUpdate The update service.
@param namespace The namespace of the workflow.
@param keywords The keywords associated with the workflow.
@return see above.
"""
from omero.util.OmeroPopo import WorkflowData as WorkflowData
# Support rstring and str namespaces
namespace = unwrap(namespace)
keywords = unwrap(keywords)
workflow = iQuery.findByQuery("from Namespace as n where n.name = '" + namespace+"'", None);
workflowData = WorkflowData();
if(workflow!=None):
workflowData = WorkflowData(workflow);
else:
workflowData.setNamespace(namespace);
splitKeywords = keywords.split(',');
SU_LOG.debug(workflowData.asIObject())
for keyword in splitKeywords:
workflowData.addKeyword(keyword);
SU_LOG.debug(workflowData.asIObject())
workflow = iUpdate.saveAndReturnObject(workflowData.asIObject());
return WorkflowData(workflow);
def findROIByImage(roiService, image, namespace):
"""
Finds the ROI with the given namespace linked to the image. Returns a collection of ROIs.
@param roiService The ROI service.
@param image The image the ROIs are linked to .
@param namespace The namespace of the ROI.
@return see above.
"""
from omero.util.OmeroPopo import ROIData as ROIData
roiOptions = omero.api.RoiOptions();
roiOptions.namespace = omero.rtypes.rstring(namespace);
results = roiService.findByImage(image, roiOptions);
roiList = [];
for roi in results.rois:
roiList.append(ROIData(roi));
return roiList;
| gpl-2.0 |
weaver-viii/h2o-3 | h2o-py/docs/conf.py | 11 | 9371 | # -*- coding: utf-8 -*-
#
# H2O documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 5 15:32:52 2015.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'H2O'
copyright = u'2015, H2O'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {sidebarbgcolor:'yellow'}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["../../h2o-docs-theme"]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'H2Odoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'H2O.tex', u'H2O Documentation',
u'H2O', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'H2O', u'H2O Documentation',
[u'Author'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'H2O', u'H2O Documentation',
u'Author', 'H2O', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'H2O'
epub_author = u'H2O'
epub_publisher = u'H2O'
epub_copyright = u'2015, H2O'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
| apache-2.0 |
tttthemanCorp/CardmeleonAppEngine | django/utils/module_loading.py | 222 | 2306 | import imp
import os
import sys
def module_has_submodule(package, module_name):
"""See if 'module' is in 'package'."""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
for finder in sys.meta_path:
if finder.find_module(name):
return True
for entry in package.__path__: # No __path__, then not a package.
try:
# Try the cached finder.
finder = sys.path_importer_cache[entry]
if finder is None:
# Implicit import machinery should be used.
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
continue
# Else see if the finder knows of a loader.
elif finder.find_module(name):
return True
else:
continue
except KeyError:
# No cached finder, so try and make one.
for hook in sys.path_hooks:
try:
finder = hook(entry)
# XXX Could cache in sys.path_importer_cache
if finder.find_module(name):
return True
else:
# Once a finder is found, stop the search.
break
except ImportError:
# Continue the search for a finder.
continue
else:
# No finder found.
# Try the implicit import machinery if searching a directory.
if os.path.isdir(entry):
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
pass
# XXX Could insert None or NullImporter
else:
# Exhausted the search, so the module cannot be found.
return False
| bsd-3-clause |
missionpinball/mpf | mpf/tests/test_Accelerometer.py | 1 | 6292 | """Test accelerometer device."""
import math
from mpf.tests.MpfTestCase import MpfTestCase
class TestAccelerometer(MpfTestCase):
def __init__(self, methodName):
super().__init__(methodName)
# this is the first test. give it some more time
self.expected_duration = 2
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/accelerometer/'
def _event_level1(self, **kwargs):
del kwargs
self._level1 = True
def _event_level2(self, **kwargs):
del kwargs
self._level2 = True
def test_leveling_different_base_angle(self):
accelerometer = self.machine.accelerometers["test_accelerometer"]
# change base angle to 6.5 degree
accelerometer.config['level_x'] = math.sin(math.radians(6.5))
accelerometer.config['level_y'] = 0
accelerometer.config['level_z'] = math.cos(math.radians(6.5))
# machine should be 6.5 degree off
accelerometer.update_acceleration(0.0, 0.0, 1)
self.assertAlmostEqual(math.radians(6.5), accelerometer.get_level_xz())
self.assertAlmostEqual(0.0, accelerometer.get_level_yz())
self.assertAlmostEqual(math.radians(6.5), accelerometer.get_level_xyz())
# add a small tilt
accelerometer.update_acceleration(0.0, math.sin(math.radians(5)), math.cos(math.radians(5)))
self.assertAlmostEqual(math.radians(6.5), accelerometer.get_level_xz())
self.assertAlmostEqual(math.radians(5), accelerometer.get_level_yz())
# leveled
accelerometer.update_acceleration(math.sin(math.radians(6.5)), 0.0, math.cos(math.radians(6.5)))
self.assertAlmostEqual(0.0, accelerometer.get_level_xz())
self.assertAlmostEqual(0.0, accelerometer.get_level_yz())
self.assertAlmostEqual(0.0, accelerometer.get_level_xyz())
# leveled + tilt
accelerometer.update_acceleration(math.sin(math.radians(6.5)) / math.cos(math.radians(6.5)),
math.sin(math.radians(5)) / math.cos(math.radians(5)),
1)
self.assertAlmostEqual(0.0, accelerometer.get_level_xz())
self.assertAlmostEqual(math.radians(5), accelerometer.get_level_yz())
def test_leveling(self):
accelerometer = self.machine.accelerometers["test_accelerometer"]
self._level1 = False
self._level2 = False
self.machine.events.add_handler("event_level1", self._event_level1)
self.machine.events.add_handler("event_level2", self._event_level2)
# perfectly leveled
accelerometer.update_acceleration(0.0, 0.0, 1.0)
self.assertAlmostEqual(0.0, accelerometer.get_level_xz())
self.assertAlmostEqual(0.0, accelerometer.get_level_yz())
self.assertAlmostEqual(0.0, accelerometer.get_level_xyz())
self.machine_run()
self.assertFalse(self._level1)
self.assertFalse(self._level2)
# 90 degree on the side
for _ in range(100):
accelerometer.update_acceleration(1.0, 0.0, 0.0)
self.assertAlmostEqual(math.pi / 2, accelerometer.get_level_xz())
self.assertAlmostEqual(0, accelerometer.get_level_yz())
self.assertAlmostEqual(math.pi / 2, accelerometer.get_level_xyz())
self.machine_run()
self.assertTrue(self._level1)
self.assertTrue(self._level2)
# 90 degree on the back
accelerometer.update_acceleration(0.0, 1.0, 0.0)
self.machine_run()
self.assertAlmostEqual(0, accelerometer.get_level_xz())
self.assertAlmostEqual(math.pi / 2, accelerometer.get_level_yz())
self.assertAlmostEqual(math.pi / 2, accelerometer.get_level_xyz())
# 45 degree on the side
accelerometer.update_acceleration(0.5, 0.0, 0.5)
self.machine_run()
self.assertAlmostEqual(math.pi / 4, accelerometer.get_level_xz())
self.assertAlmostEqual(0, accelerometer.get_level_yz())
self.assertAlmostEqual(math.pi / 4, accelerometer.get_level_xyz())
# 3.01 degree
self._level1 = False
self._level2 = False
for _ in range(100):
accelerometer.update_acceleration(0.0, 0.05, 0.95)
self.machine_run()
self.assertTrue(self._level1)
self.assertFalse(self._level2)
# 6.34 degree
self._level1 = False
self._level2 = False
for _ in range(100):
accelerometer.update_acceleration(0.0, 0.1, 0.9)
self.machine_run()
self.assertTrue(self._level1)
self.assertTrue(self._level2)
def _event_hit1(self, **kwargs):
del kwargs
self._hit1 = True
def _event_hit2(self, **kwargs):
del kwargs
self._hit2 = True
def test_hits(self):
accelerometer = self.machine.accelerometers["test_accelerometer"]
# perfectly leveled
accelerometer.update_acceleration(0.0, 0.0, 1.0)
self.machine_run()
self._hit1 = False
self._hit2 = False
self.machine.events.add_handler("event_hit1", self._event_hit1)
self.machine.events.add_handler("event_hit2", self._event_hit2)
# some noise
accelerometer.update_acceleration(0.01, 0.05, 0.99)
self.machine_run()
self.assertFalse(self._hit1)
self.assertFalse(self._hit2)
# hit from the side
accelerometer.update_acceleration(0.4, 0.4, 1.0)
self.machine_run()
self.assertTrue(self._hit1)
self.assertFalse(self._hit2)
self._hit1 = False
self._hit2 = False
# and it calms
accelerometer.update_acceleration(0.01, 0.05, 0.99)
accelerometer.update_acceleration(0.01, 0.05, 0.99)
accelerometer.update_acceleration(0.01, 0.05, 0.99)
accelerometer.update_acceleration(0.01, 0.05, 0.99)
accelerometer.update_acceleration(0.01, 0.05, 0.99)
self.machine_run()
self.assertFalse(self._hit1)
self.assertFalse(self._hit2)
# strong hit from the side
accelerometer.update_acceleration(1.5, 0.4, 1.0)
self.machine_run()
self.assertTrue(self._hit1)
self.assertTrue(self._hit2)
| mit |
hyperized/ansible | lib/ansible/modules/cloud/ovirt/ovirt_template_info.py | 20 | 4191 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_template_info
short_description: Retrieve information about one or more oVirt/RHV templates
author: "Ondra Machacek (@machacekondra)"
version_added: "2.3"
description:
- "Retrieve information about one or more oVirt/RHV templates."
- This module was called C(ovirt_template_facts) before Ansible 2.9, returning C(ansible_facts).
Note that the M(ovirt_template_info) module no longer returns C(ansible_facts)!
notes:
- "This module returns a variable C(ovirt_templates), which
contains a list of templates. You need to register the result with
the I(register) keyword to use it."
options:
pattern:
description:
- "Search term which is accepted by oVirt/RHV search backend."
- "For example to search template X from datacenter Y use following pattern:
name=X and datacenter=Y"
extends_documentation_fragment: ovirt_info
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather information about all templates which names start with C(centos) and
# belongs to data center C(west):
- ovirt_template_info:
pattern: name=centos* and datacenter=west
register: result
- debug:
msg: "{{ result.ovirt_templates }}"
'''
RETURN = '''
ovirt_templates:
description: "List of dictionaries describing the templates. Template attributes are mapped to dictionary keys,
all templates attributes can be found at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/template."
returned: On success.
type: list
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_info_full_argument_spec,
)
def main():
argument_spec = ovirt_info_full_argument_spec(
pattern=dict(default='', required=False),
)
module = AnsibleModule(argument_spec)
is_old_facts = module._name == 'ovirt_template_facts'
if is_old_facts:
module.deprecate("The 'ovirt_template_facts' module has been renamed to 'ovirt_template_info', "
"and the renamed one no longer returns ansible_facts", version='2.13')
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
templates_service = connection.system_service().templates_service()
templates = templates_service.list(search=module.params['pattern'])
result = dict(
ovirt_templates=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in templates
],
)
if is_old_facts:
module.exit_json(changed=False, ansible_facts=result)
else:
module.exit_json(changed=False, **result)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
| gpl-3.0 |
jcshen007/cloudstack | test/integration/testpaths/testpath_same_vm_name.py | 7 | 6349 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Test case for checking creation of two VM's with same name on VMWare"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources)
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
Configurations
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
)
from marvin.sshClient import SshClient
import time
class TestSameVMName(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestSameVMName, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
try:
cls.skiptest = False
if cls.hypervisor.lower() not in ['vmware']:
cls.skiptest = True
# Create an account
cls.account_1 = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls.account_2 = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
# Create user api client of the account
cls.userapiclient_1 = testClient.getUserApiClient(
UserName=cls.account_1.name,
DomainName=cls.account_1.domain
)
cls.userapiclient_2 = testClient.getUserApiClient(
UserName=cls.account_2.name,
DomainName=cls.account_2.domain
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup = [
cls.account_1,
cls.account_2,
cls.service_offering,
]
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def RestartServer(cls):
"""Restart management server"""
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management restart"
sshClient.execute(command)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
if self.skiptest:
self.skipTest(
"This test is to be checked on VMWare only \
Hence, skip for %s" % self.hypervisor)
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic"])
def test_vms_with_same_name(self):
""" Test vm deployment with same name
# 1. Deploy a VM on with perticular name from account_1
# 2. Try to deploy another vm with same name from account_2
# 3. Verify that second VM deployment fails
"""
# Step 1
# Create VM on cluster wide
configs = Configurations.list(
self.apiclient,
name="vm.instancename.flag")
orig_value = configs[0].value
if orig_value == "false":
Configurations.update(self.apiclient,
name="vm.instancename.flag",
value="true"
)
# Restart management server
self.RestartServer()
time.sleep(120)
self.testdata["small"]["displayname"] = "TestName"
self.testdata["small"]["name"] = "TestName"
VirtualMachine.create(
self.userapiclient_1,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account_1.name,
domainid=self.account_1.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
)
with self.assertRaises(Exception):
VirtualMachine.create(
self.userapiclient_2,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account_2.name,
domainid=self.account_2.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
)
return
| apache-2.0 |
clinton-hall/nzbToMedia | libs/common/pbr/tests/util.py | 32 | 2670 | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
#
# Copyright (C) 2013 Association of Universities for Research in Astronomy
# (AURA)
#
# 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. The name of AURA and its representatives may not be used to
# endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY AURA ``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 AURA BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
import contextlib
import os
import shutil
import stat
import sys
try:
import ConfigParser as configparser
except ImportError:
import configparser
@contextlib.contextmanager
def open_config(filename):
if sys.version_info >= (3, 2):
cfg = configparser.ConfigParser()
else:
cfg = configparser.SafeConfigParser()
cfg.read(filename)
yield cfg
with open(filename, 'w') as fp:
cfg.write(fp)
def rmtree(path):
"""shutil.rmtree() with error handler.
Handle 'access denied' from trying to delete read-only files.
"""
def onerror(func, path, exc_info):
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
return shutil.rmtree(path, onerror=onerror)
| gpl-3.0 |
renard/ansible | test/integration/targets/collections/custom_vars_plugins/vars_req_whitelist.py | 29 | 1536 | # Copyright 2019 RedHat, inc
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#############################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
vars: vars_req_whitelist
version_added: "2.10"
short_description: load host and group vars
description: test loading host and group vars from a collection
options:
stage:
choices: ['all', 'inventory', 'task']
type: str
ini:
- key: stage
section: vars_req_whitelist
env:
- name: ANSIBLE_VARS_PLUGIN_STAGE
'''
from ansible.plugins.vars import BaseVarsPlugin
class VarsModule(BaseVarsPlugin):
REQUIRES_WHITELIST = True
def get_vars(self, loader, path, entities, cache=True):
super(VarsModule, self).get_vars(loader, path, entities)
return {'whitelisted': True, 'collection': False}
| gpl-3.0 |
valix25/H4H | test_data/test2.py | 1 | 2514 | import plotly
import plotly.plotly as py
import pandas as pd
from plotly.widgets import GraphWidget
from IPython.html import widgets
from IPython.display import display, clear_output
import numpy as np
py.sign_in('dswbtest', 'ci8iu7p6wi') #plotly API credentials
food = pd.read_csv("supply.csv")
# Definition of a function that defines the plot settings
def foodmap(year):
year = str(year)
# Properties of the data and how it is displayed
data = [ dict(
type = 'choropleth',
locations = food['Country code'],
z = food[year],
text = food['Country name'],
colorscale = [[0,"rgb(51,160,44)"],
[0.5,"rgb(255,255,51)"],
[1,"rgb(227,26,28)"]],
opacity = 1,
autocolorscale = False,
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(0,0,0)',
width = 0.5
)
),
colorbar = dict(
autotick = True,
title = 'kcal per capita'
),
) ]
# Properties of the plot
layout = dict(
title = 'Food Supply (kcal per capita) in ' + str(year),
geo = dict(
showframe = False,
showcoastlines = False,
showcountry = True,
countrycolor = "rgb(220, 0, 0)",
coastlinecolor = "rgb(220, 0, 0)",
landcolor = "rgb(220, 0, 0)",
projection = dict(
type = 'Mercator',
scale = 1
)
)
)
fig = dict( data=data, layout=layout )
url = py.plot( fig, validate=False, filename='d3-food-map' )
return url
# Graph object
g = GraphWidget(foodmap(1961))
# Definition of a class that will update the graph object
class z_data:
def __init__(self):
self.z = food[str(int(1961))]
def on_z_change(self, name, old_value, new_value):
self.z = food[str(int(new_value))]
self.title = "Food Supply (kcal per capita) in " + str(new_value)
self.replot()
def replot(self):
g.restyle({ 'z': [self.z] })
g.relayout({'title': self.title})
# Interactive object
edu_slider = widgets.IntSlider(min=1961,max=2011,value=1961,step=1)
edu_slider.description = 'Year'
edu_slider.value = 1961
z_state = z_data()
edu_slider.on_trait_change(z_state.on_z_change, 'value')
display(edu_slider)
display(g) | mit |
dturevski/olive-gui | p2w/parser.py | 1 | 8808 | from .nodes import *
import ply.yacc as yacc
# lex & yacc transform the popeye output into a list of Nodes
# the final rule - BuildTree - transforms this list into a tree
def p_BuildTree(t):
'BuildTree : Solution'
t[1][0].unflatten(t[1], 1)
t[1][0].linkContinuedTwins()
t[0] = t[1][0]
def p_Solution_Movelist(t):
'Solution : MoveList'
t[0] = [Node(), VirtualTwinNode()] + t[1]
def p_Solution_TwinList(t):
'Solution : TwinList'
t[0] = [Node()] + t[1]
def p_Solution_Comments(t):
'Solution : Comments Solution'
t[0] = t[2]
t[0][0].setv('comments', t[1])
def p_Comments(t):
'''Comments : COMMENT
| COMMENT Comments'''
if len(t) == 2:
t[0] = [t[1]]
else:
t[0] = [t[1]] + t[2]
def p_Solution_empty(t):
'Solution : '
t[0] = [Node()] # empty input
def p_TwinList(t):
'''TwinList : Twin
| TwinList Twin'''
if len(t) == 2:
t[0] = t[1]
else:
t[0] = t[1] + t[2]
def p_Twin(t):
'Twin : TwinHeader MoveList'
t[0] = [t[1]] + t[2]
def p_TwinHeader_TwinBullet(t):
'TwinHeader : TwinBullet'
t[0] = t[1]
def p_TwinHeader_CommandList(t):
'TwinHeader : TwinBullet CommandList'
t[0] = t[1].setv('commands', t[2])
def p_TwinHeader_Comments(t):
'TwinHeader : TwinHeader Comments'
t[0] = t[1].setv('comments', t[2])
def p_TwinBullet(t):
'''TwinBullet : TWIN_ID
| PLUS TWIN_ID'''
if t[1] != '+':
t[0] = TwinNode(t[1], False)
else:
t[0] = TwinNode(t[2], True)
def p_CommandList(t):
'''CommandList : Command
| CommandList Command'''
if len(t) == 2:
t[0] = [t[1]]
else:
t[0] = t[1] + [t[2]]
def p_Command(t):
'''Command : ROTATE ANGLE
| MIRROR SQUARE DOUBLE_POINTED_ARROW SQUARE
| SHIFT SQUARE LONG_DOUBLE_ARROW SQUARE
| POLISH_TYPE
| IMITATOR SquareList
| LongPieceDecl SQUARE LONG_ARROW SQUARE
| LongPieceDecl SQUARE DOUBLE_POINTED_ARROW LongPieceDecl SQUARE
| DASH LongPieceDecl SQUARE
| PLUS LongPieceDecl SQUARE
| LongPieceDecl SQUARE'''
if len(t) == 5 and t[3] == '-->':
t[0] = TwinCommand("Move", [t[2], t[4]])
elif len(t) == 6 and t[3] == '<-->':
t[0] = TwinCommand("Exchange", [t[2], t[5]])
elif t[1] == '-':
t[0] = TwinCommand("Remove", [t[3]])
elif t[1] == '+':
t[0] = TwinCommand("Add", [t[2], t[3]])
elif t[1] == 'rotate':
t[0] = TwinCommand("Rotate", [t[2]])
elif t[1] == 'mirror':
t[0] = TwinCommand("Mirror", [t[2], t[4]])
elif t[1] == 'shift':
t[0] = TwinCommand("Shift", [t[2], t[4]])
elif t[1] == 'PolishType':
t[0] = TwinCommand("PolishType", [])
elif t[1] == 'Imitator':
t[0] = TwinCommand("Imitator", t[2])
elif len(t) == 3:
t[0] = TwinCommand("Add", [t[1], t[2]])
def p_LongPieceDecl(t):
'''LongPieceDecl : ColorPrefix PIECE_NAME
| ColorPrefix FAIRY_PROPERTIES PIECE_NAME'''
if len(t) == 3:
t[0] = model.Piece(t[2], t[1], "")
else:
t[0] = model.Piece(t[3], t[1], t[2])
def p_ColorPrefix(t):
'''ColorPrefix : COLOR_NEUTRAL
| COLOR_WHITE
| COLOR_BLACK'''
t[0] = t[1]
def p_PieceDecl(t):
'PieceDecl : PIECE_NAME'
t[0] = model.Piece(t[1], "u", "")
def p_PieceDecl_Neutral(t):
'PieceDecl : COLOR_NEUTRAL PIECE_NAME'
t[0] = model.Piece(t[2], t[1], "")
def p_PieceDecl_Neutral_Fairy(t):
'PieceDecl : COLOR_NEUTRAL FAIRY_PROPERTIES PIECE_NAME'
t[0] = model.Piece(t[3], t[1], t[2])
def p_PieceDecl_Fairy(t):
'PieceDecl : FAIRY_PROPERTIES PIECE_NAME'
t[0] = model.Piece(t[2], "u", t[1])
def p_SquareList(t):
'''SquareList : SQUARE
| SQUARE COMMA SquareList
| SQUARE SquareList '''
if len(t) == 2:
t[0] = [t[1]]
elif t[2] == ",":
t[0] = [t[1]] + t[3]
else:
t[0] = [t[1]] + t[2]
def p_MoveList(t):
'''MoveList : Move
| Move MoveList '''
if len(t) == 2:
t[0] = t[1]
else:
t[0] = t[1] + t[2]
def p_Move(t):
'''Move : BUT MOVE_NUMBER HALF_ELLIPSIS HalfMove
| MOVE_NUMBER HALF_ELLIPSIS ELLIPSIS
| MOVE_NUMBER HALF_ELLIPSIS HalfMove
| MOVE_NUMBER HalfMove THREAT
| MOVE_NUMBER HalfMove ZUGZWANG
| MOVE_NUMBER HalfMove HalfMove
| MOVE_NUMBER HalfMove'''
if t[1] == "but":
t[0] = [t[4].setv("depth", t[2] + 1)]
elif t[2] == ".." and t[3] == "...":
t[0] = [NullNode(t[1], False)]
elif t[2] == "..":
t[0] = [t[3].setv("depth", t[1] + 1)]
elif len(t) > 3 and t[3] == "threat:":
t[0] = [t[2].setv("depth", t[1]).setv('childIsThreat', True)]
elif len(t) > 3 and t[3] == "zugzwang.":
t[0] = [t[2].setv("depth", t[1])]
elif len(t) == 4:
t[0] = [t[2].setv("depth", t[1]), t[3].setv("depth", t[1] + 1)]
else:
t[0] = [t[2].setv("depth", t[1])]
def p_HalfMove_Check(t):
'HalfMove : Ply CheckSign'
t[0] = t[1].setv("checksign", t[2])
def p_HalfMove_Ply(t):
'HalfMove : Ply'
t[0] = t[1]
def p_HalfMove_Annotation(t):
'HalfMove : HalfMove ANNOTATION'
t[0] = t[1].setv("annotation", t[2])
def p_HalfMove_Comments(t):
'HalfMove : HalfMove Comments'
t[0] = t[1].setv("comments", t[2])
def p_CheckSign(t):
'''CheckSign : PLUS
| OTHER_CHECK_SIGN'''
t[0] = t[1]
def p_Ply_Body(t):
'Ply : Body'
t[0] = t[1]
def p_Ply_ColorPrefix(t):
'Ply : Ply EQUALS ColorPrefix'
color = model.COLORS_SHORT[t[3]]
t[1].recolorings[color].append(t[1].arrival)
t[0] = t[1]
def p_Ply_Promotion(t):
''' Ply : Ply EQUALS PieceDecl
| Ply EQUALS LongPieceDecl
| Ply EQUALS'''
if len(t) != 3:
t[0] = t[1].setv('promotion', t[3])
else:
t[0] = t[1].setv("checksign", t[2])
def p_Ply_Rebirth_Promotion(t):
'Ply : Ply LEFT_SQUARE_BRACKET PLUS LongPieceDecl SQUARE EQUALS PieceDecl RIGHT_SQUARE_BRACKET'
t[1].rebirths.append({
'unit': t[4], 'at': t[5], 'prom': t[7]
})
t[0] = t[1]
def p_Ply_Rebirth(t):
'Ply : Ply LEFT_SQUARE_BRACKET PLUS LongPieceDecl SQUARE RIGHT_SQUARE_BRACKET'
t[1].rebirths.append({
'unit': t[4], 'at': t[5], 'prom': None
})
t[0] = t[1]
def p_Ply_Antirebirth_Promotion(t):
'Ply : Ply LEFT_SQUARE_BRACKET LongPieceDecl SQUARE ARROW SQUARE EQUALS PieceDecl RIGHT_SQUARE_BRACKET'
t[1].antirebirths.append({
'unit': t[3], 'from': t[4], 'to': t[6], 'prom': t[8]
})
t[0] = t[1]
def p_Ply_Antirebirth(t):
'Ply : Ply LEFT_SQUARE_BRACKET LongPieceDecl SQUARE ARROW SQUARE RIGHT_SQUARE_BRACKET'
t[1].antirebirths.append({
'unit': t[3], 'from': t[4], 'to': t[6], 'prom': None
})
t[0] = t[1]
# remote promotion happens eg in KobulKings capture
def p_Ply_Remote_Promotion(t):
'Ply : Ply LEFT_SQUARE_BRACKET SQUARE EQUALS PieceDecl RIGHT_SQUARE_BRACKET'
t[1].promotions.append({
'unit': t[5],
'at': t[3]
})
t[0] = t[1]
def p_Ply_Recoloring(t):
'Ply : Ply LEFT_SQUARE_BRACKET SQUARE EQUALS ColorPrefix RIGHT_SQUARE_BRACKET'
t[1].recolorings[model.COLORS_SHORT[t[5]]].append(t[3])
t[0] = t[1]
def p_Ply_Removal(t):
'Ply : Ply LEFT_SQUARE_BRACKET DASH SQUARE RIGHT_SQUARE_BRACKET'
t[1].removals.append(t[4])
t[0] = t[1]
def p_Ply_Imitators(t):
'Ply : Ply IMITATOR_MOVEMENT_OPENING_BRACKET SquareList RIGHT_SQUARE_BRACKET'
t[1].imitators = t[3]
t[0] = t[1]
def p_Body_Normal(t):
'Body : PieceDecl Squares'
t[0] = t[2].setv("departant", t[1])
def p_Body_Castling(t):
'Body : Castling'
t[0] = t[1]
def p_Body_PawnMove(t):
'Body : PawnMove'
t[0] = t[1]
def p_Body_EnPassant(t):
'Body : Body EN_PASSANT'
t[0] = t[1].setEnPassant()
def p_PawnMove(t):
'PawnMove : Squares'
t[0] = t[1].setv("departant", model.Piece("P", "u", ""))
def p_Squares(t):
'''Squares : SQUARE DASH SQUARE
| SQUARE ASTERISK SQUARE
| SQUARE ASTERISK SQUARE DASH SQUARE'''
if len(t) == 4 and t[2] == "-":
t[0] = MoveNode(t[1], t[3], -1)
elif len(t) == 4 and t[2] == "*":
t[0] = MoveNode(t[1], t[3], t[3])
else:
t[0] = MoveNode(t[1], t[5], t[3])
def p_Castling(t):
'''Castling : KINGSIDE_CASTLING
| QUEENSIDE_CASTLING'''
t[0] = CastlingNode(t[1] == "0-0")
def p_error(t):
if not t is None:
raise Exception("Syntax error at '%s', line %d, char %d" % (t.value, t.lineno, t.lexpos))
else:
raise Exception("Terminating syntax error")
from .lexer import *
parser = yacc.yacc() | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.